decklight 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +17 -0
  3. package/README.md +53 -25
  4. package/SPEC.md +1239 -67
  5. package/cli/agents.mjs +139 -15
  6. package/cli/bundle.mjs +68 -2
  7. package/cli/cast.mjs +45 -14
  8. package/cli/check-fixes.mjs +12 -4
  9. package/cli/check-watch.mjs +151 -0
  10. package/cli/check.mjs +460 -71
  11. package/cli/code-editor.mjs +287 -0
  12. package/cli/commands.mjs +13 -2
  13. package/cli/commit-message.mjs +34 -7
  14. package/cli/commit-split.mjs +123 -23
  15. package/cli/decklight.mjs +11 -1
  16. package/cli/design-system-edit.mjs +37 -1
  17. package/cli/edit-address.mjs +184 -0
  18. package/cli/edit-git.mjs +21 -4
  19. package/cli/edit-handover.mjs +136 -25
  20. package/cli/edit-look.mjs +45 -1
  21. package/cli/edit-open.mjs +143 -0
  22. package/cli/edit-slides.mjs +1043 -67
  23. package/cli/edit-translate.mjs +243 -0
  24. package/cli/edit.mjs +3182 -267
  25. package/cli/editor-support.mjs +286 -0
  26. package/cli/enhance.mjs +148 -20
  27. package/cli/find-replace.mjs +142 -0
  28. package/cli/fix-review.mjs +368 -0
  29. package/cli/init.mjs +93 -19
  30. package/cli/keep-awake.mjs +68 -0
  31. package/cli/migrate-writing.mjs +214 -0
  32. package/cli/narrate.mjs +51 -10
  33. package/cli/open.mjs +29 -9
  34. package/cli/outside-edit.mjs +257 -0
  35. package/cli/paste.mjs +92 -0
  36. package/cli/pdf.mjs +61 -2
  37. package/cli/pptx-export.mjs +3 -1
  38. package/cli/publish.mjs +24 -3
  39. package/cli/record.mjs +19 -8
  40. package/cli/rewrite.mjs +265 -0
  41. package/cli/runtime-link.mjs +218 -17
  42. package/cli/serve.mjs +7 -4
  43. package/cli/setup.mjs +2 -2
  44. package/cli/skill-content.mjs +212 -8
  45. package/cli/skills/slide-writing.md +333 -0
  46. package/cli/skills/voiceover.md +423 -0
  47. package/cli/skills.mjs +36 -13
  48. package/cli/starter-full.mjs +353 -0
  49. package/cli/supervise.mjs +14 -0
  50. package/cli/theme.mjs +3 -2
  51. package/cli/translate-core.mjs +466 -0
  52. package/cli/translate-files.mjs +149 -0
  53. package/cli/translate.mjs +458 -0
  54. package/cli/util.mjs +25 -0
  55. package/cli/vocabulary-docs.mjs +138 -0
  56. package/dist/decklight.css +2087 -91
  57. package/dist/decklight.js +367 -203
  58. package/dist/decklight.js.map +4 -4
  59. package/docs/GLOSSARY.md +9 -2
  60. package/docs/WRITING_RESEARCH.md +327 -0
  61. package/package.json +5 -3
  62. package/themes/coastal.css +3 -0
  63. package/themes/metropolis.css +2 -0
  64. package/themes/reveal-blood.css +3 -0
  65. package/themes/reveal-league.css +2 -0
  66. package/themes/reveal-moon.css +2 -0
  67. package/themes/reveal-serif.css +1 -0
  68. package/themes/reveal-sky.css +1 -0
  69. package/themes/reveal-solarized.css +4 -0
  70. package/tools/brand-palette.mjs +6 -1
  71. package/tools/build-groups.mjs +28 -8
  72. package/tools/cdp.mjs +176 -0
  73. package/tools/chart-spec.mjs +242 -0
  74. package/tools/click-match.mjs +70 -0
  75. package/tools/code-options.mjs +174 -0
  76. package/tools/conversation.mjs +49 -0
  77. package/tools/deck-family.mjs +101 -0
  78. package/tools/deck-html.mjs +212 -15
  79. package/tools/design-system-format.mjs +15 -1
  80. package/tools/diagram-shapes.mjs +221 -0
  81. package/tools/elevenlabs-tts.mjs +62 -53
  82. package/tools/face-clip.mjs +96 -0
  83. package/tools/face-layout.mjs +94 -0
  84. package/tools/gemini-tts.mjs +1 -1
  85. package/tools/invisible-in-print.mjs +27 -0
  86. package/tools/lipsync-auto.mjs +197 -0
  87. package/tools/lipsync-config.mjs +16 -0
  88. package/tools/lipsync-engines.mjs +22 -4
  89. package/tools/lipsync-server.mjs +8 -5
  90. package/tools/lipsync.mjs +122 -30
  91. package/tools/local-voice.mjs +1 -1
  92. package/tools/mouth-file.mjs +26 -0
  93. package/tools/mouth.mjs +320 -0
  94. package/tools/narration-manifest.mjs +24 -4
  95. package/tools/narration-synth.mjs +96 -76
  96. package/tools/recording-impact.mjs +16 -1
  97. package/tools/sentences.mjs +7 -1
  98. package/tools/starters.mjs +402 -0
  99. package/tools/steps.mjs +118 -0
  100. package/tools/take-check.mjs +146 -0
  101. package/tools/template-theme.mjs +3 -1
  102. package/tools/test-impact.mjs +36 -12
  103. package/tools/theme-check.mjs +196 -1
  104. package/tools/tone-cue.mjs +108 -0
  105. package/tools/tts-cache.mjs +9 -3
  106. package/tools/tts-engines.mjs +100 -11
  107. package/tools/video-cache.mjs +93 -0
  108. package/tools/video-live.mjs +349 -0
  109. package/tools/video-options.mjs +11 -0
  110. package/tools/video.mjs +772 -127
  111. package/tools/viseme-fit.mjs +27 -0
  112. package/tools/viseme-match.mjs +77 -0
  113. package/tools/vocabulary.mjs +397 -0
  114. package/tools/voice-renumber.mjs +605 -0
  115. package/tools/voiceover-server.mjs +42 -11
  116. package/tools/voiceover.mjs +48 -20
  117. package/dist/build-info.json +0 -1
package/cli/init.mjs CHANGED
@@ -8,15 +8,19 @@
8
8
  * without a web search or a guess from Reveal.js memory.
9
9
  *
10
10
  * decklight init ["My Deck"] [-o deck.html] [--dir path] [--inline [--themes …]]
11
- * [--design-system <ref> | --no-design-system]
11
+ * [--starter basic|full] [--design-system <ref> | --no-design-system]
12
12
  * [--git | --no-git] [--remote <url> | --no-remote]
13
13
  * [--no-open] [--force] [--no-skill | --global-skill]
14
+ * [--vscode | --no-vscode]
14
15
  *
15
- * A terminal run can ask up to five questions, each skipped by its flag or
16
- * by a non-TTY run: the deck's title ("My Deck" by default), which design
16
+ * A terminal run can ask up to seven questions, each skipped by its flag or
17
+ * by a non-TTY run: the deck's title ("My Deck" by default), which starter
18
+ * (basic, two slides, or full, one slide per feature), which design
17
19
  * system it is built on (only when a cached catalog offers one), where the
18
20
  * skill goes (the project, or each detected agent's config home), whether to
19
- * create a git repository, and, for a repository it just created, a remote.
21
+ * write VS Code's completions and snippets (only when VS Code's `code` is on
22
+ * the PATH), whether to create a git repository, and, for a repository it
23
+ * just created, a remote.
20
24
  *
21
25
  * The deck is data by default: slides plus a JSON configuration block, with
22
26
  * no runtime in the file. `decklight <deck>` serves the installed runtime into
@@ -46,12 +50,14 @@ import { TARGETS, detectedTargets, installGlobalSkill, display, syncLibrarySkill
46
50
  import { librarySkills } from './units.mjs';
47
51
  import { onPath } from './agents.mjs';
48
52
  import { escapeHtml } from './edit.mjs';
53
+ import { STARTERS, fullStarterSlides } from './starter-full.mjs';
49
54
  import {
50
55
  classifyRemoteError, createRepo, foreignWarning, git as gitRun, inGitRepo, isIdentityError,
51
56
  looksLikeGitUrl, noPromptEnv, oneline, remoteNames, splitDeckPaths,
52
57
  } from './git.mjs';
53
58
  import { makeFail, runMain } from './util.mjs';
54
59
  import { configHome } from './marketplace.mjs';
60
+ import { writeEditorSupport } from './editor-support.mjs';
55
61
  import { openCommand, openDeck, openUrl } from './open-browser.mjs';
56
62
 
57
63
  // still exported from here — record and review used to import the opener from init
@@ -421,6 +427,23 @@ export async function wireDesignSystem(build, qualified, { home = configHome(),
421
427
  return { html, label, installs, warnings, deckRef };
422
428
  }
423
429
 
430
+ // ── the starter: basic by default, full as the choice offered ───────────────
431
+ // The same shape again: `--starter <name>` (or `--starter=<name>`) decides, a
432
+ // bare terminal run is asked, and a headless run keeps today's basic deck.
433
+ export function planStarter({ args = [], tty = false } = {}) {
434
+ const eq = args.find((a) => a.startsWith('--starter='));
435
+ const i = args.indexOf('--starter');
436
+ if (!eq && i < 0) return tty ? { action: 'ask' } : { action: 'use', starter: STARTERS[0] };
437
+ const value = eq ? eq.slice('--starter='.length) : args[i + 1];
438
+ if (!value || value.startsWith('-')) return { action: 'refuse', why: `--starter needs a starter: ${STARTERS.join(' or ')}` };
439
+ if (!STARTERS.includes(value)) return { action: 'refuse', why: `--starter: no starter "${value}" (${STARTERS.join(' or ')})` };
440
+ return { action: 'use', starter: value };
441
+ }
442
+
443
+ /** The question a terminal run asks, and what an answer to it picks (Enter, or the end of input: basic). */
444
+ export const STARTER_QUESTION = 'starter: basic (a title and a build slide) or full (one slide per feature, each naming the spec section to read)? [B/f] ';
445
+ export const pickStarter = (answer = '') => (/^\s*f/i.test(answer) ? 'full' : 'basic');
446
+
424
447
  // ── the skill scope: project by default, global as a proposition ────────────
425
448
  // The same shape as planGit: a pure decision table over flags and the TTY
426
449
  // gate. --no-skill skips skill AND question, --global-skill preselects the
@@ -432,6 +455,18 @@ export function planSkill({ args = [], tty = false } = {}) {
432
455
  return { action: tty ? 'ask' : 'project' };
433
456
  }
434
457
 
458
+ /**
459
+ * VS Code's completions and snippets (cli/editor-support.mjs), the same
460
+ * shape again: a flag says, a terminal run with VS Code on the PATH is asked
461
+ * (yes by default: the author uses it), and every other run writes nothing,
462
+ * since a .vscode/ folder nobody's editor reads is clutter.
463
+ */
464
+ export function planVscode({ args = [], tty = false, hasCode = false } = {}) {
465
+ if (args.includes('--no-vscode')) return { action: 'skip' };
466
+ if (args.includes('--vscode')) return { action: 'write' };
467
+ return { action: tty && hasCode ? 'ask' : 'skip' };
468
+ }
469
+
435
470
  /**
436
471
  * Create the repository (via the shared createRepo seam, so it starts with
437
472
  * the starter .gitignore) and commit everything init just wrote. The deck is
@@ -484,7 +519,7 @@ export function epilogue({ deckPath, tty = false, noColor = false }) {
484
519
  }
485
520
 
486
521
 
487
- function starterDeck(title, themeNames, activeTheme, { inline = false, titleSlide = null } = {}) {
522
+ function starterDeck(title, themeNames, activeTheme, { inline = false, titleSlide = null, starter = 'basic' } = {}) {
488
523
  title = escapeHtml(title); // a prompt invites &, < and quotes
489
524
  // The deck is DATA (#520): slides, plus one JSON block holding its
490
525
  // configuration and the version it was written for. No runtime in the file
@@ -503,7 +538,7 @@ ${configBlockHtml({ theme: activeTheme })}
503
538
  </head>
504
539
  <body>
505
540
  <div class="decklight">
506
- ${starterSlides(title, titleSlide)}
541
+ ${starterSlides(title, titleSlide, { starter })}
507
542
  </div>
508
543
  </body>
509
544
  </html>
@@ -529,7 +564,7 @@ ${themeBlocks}
529
564
  </head>
530
565
  <body>
531
566
  <div class="decklight">
532
- ${starterSlides(title)}
567
+ ${starterSlides(title, null, { starter })}
533
568
  </div>
534
569
  <script data-decklight-runtime="js">${runtimeJs()}</script>
535
570
  <script>Decklight.init({});</script>
@@ -539,15 +574,21 @@ ${starterSlides(title)}
539
574
  }
540
575
 
541
576
  /**
542
- * The two starter slides, shared by the linked and the self-contained
543
- * scaffold. `title` is already escaped. `titleSlide` (`titleSlideTemplate`)
544
- * puts the title slide on a design system's template; the build slide is the
545
- * same either way: it teaches the one concept every deck needs, on any theme.
577
+ * The starter slides, shared by the linked and the self-contained scaffold.
578
+ * `title` is already escaped. `titleSlide` (`titleSlideTemplate`) puts the
579
+ * title slide on a design system's template. `basic` is two slides: the
580
+ * title, and a build slide that teaches the one concept every deck needs, on
581
+ * any theme. `full` is the reference starter (cli/starter-full.mjs): one
582
+ * slide per thing a slide can hold, each naming the SPEC section to read.
546
583
  */
547
- function starterSlides(title, titleSlide = null) {
548
- const open = titleSlide
584
+ function starterSlides(title, titleSlide = null, { starter = 'basic' } = {}) {
585
+ const template = titleSlide
549
586
  ? `<section data-template="${titleSlide.ref}">\n${titleSlide.lines.map((l) => ` ${l}`).join('\n')}`
550
- : `<section>
587
+ : null;
588
+ if (starter === 'full') {
589
+ return fullStarterSlides(template ?? `<section>\n <h1>${title}</h1>`, { templated: Boolean(template) });
590
+ }
591
+ const open = template ?? `<section>
551
592
  <h1>${title}</h1>
552
593
  <p>Made with Decklight — press → to advance, ? for every key</p>`;
553
594
  return `
@@ -583,9 +624,9 @@ export async function initMain(argv = process.argv.slice(2), { hasBin = onPath,
583
624
 
584
625
  Usage:
585
626
  decklight init ["Deck Title"] [-o deck.html] [--dir path] [--inline [--themes …]]
586
- [--design-system <ref> | --no-design-system]
627
+ [--starter basic|full] [--design-system <ref> | --no-design-system]
587
628
  [--git | --no-git] [--remote <url> | --no-remote] [--no-open] [--force]
588
- [--no-skill | --global-skill]
629
+ [--no-skill | --global-skill] [--vscode | --no-vscode]
589
630
 
590
631
  Options:
591
632
  -o <file> deck output path (default: deck.html)
@@ -600,6 +641,15 @@ Options:
600
641
  all every shipped theme (default)
601
642
  name,name,… an explicit list (aurora stays active when
602
643
  included, else the first listed)
644
+ --starter <name>
645
+ which slides the deck starts with:
646
+ basic a title slide and a slide with a build (default)
647
+ full one slide per feature (builds, notes, two
648
+ columns, a table, code, math, a picture, a
649
+ chart, a diagram with connectors, chapters,
650
+ sources), each under a comment naming the
651
+ SPEC section to read: a reference to copy from
652
+ (no flag: init ASKS on a TTY, and off a terminal writes basic)
603
653
  --design-system <ref>
604
654
  start the deck on a design system a registered marketplace
605
655
  offers (name or name@marketplace, read from the cached
@@ -637,10 +687,21 @@ Options:
637
687
  agent's config home (~/.claude, ~/.codex, …), exactly what
638
688
  \`decklight skills --global\` installs — instead of into the
639
689
  project; suppresses the question
690
+ --vscode write .vscode/ beside the deck: completions for every
691
+ data-* attribute Decklight reads, with its values, and
692
+ dl- snippets (a slide, a build, notes, a diagram, a chart,
693
+ a comparison). An existing .vscode/settings.json is merged,
694
+ never overwritten. (VS Code on the PATH + no flag: init
695
+ ASKS on a TTY; decklight vscode adds it to a deck later)
696
+ --no-vscode never write .vscode/, and ask nothing about it
640
697
 
641
698
  Without a title argument, a terminal run asks for one (empty keeps "My Deck");
642
699
  non-interactive runs scaffold "My Deck" without asking.
643
700
 
701
+ A terminal run is then asked which starter ("starter: basic … or full …?
702
+ [B/f]"): Enter keeps the two-slide basic deck, f writes the full one.
703
+ --starter answers it; non-interactive runs write basic without asking.
704
+
644
705
  A terminal run is also asked where the skill should go ("where should the
645
706
  skill go? [P/g]"): project — .claude/skills/decklight/ + AGENTS.md next to
646
707
  the deck (Enter keeps it) — or global, each detected agent's config home.
@@ -664,11 +725,14 @@ unless --no-skill is given. The deck file is only touched with --force.
664
725
  else if (a === '--force') force = true;
665
726
  else if (a === '--open' || a === '--no-open') ; // the handoff, below (--open is the default)
666
727
  else if (a === '--no-skill' || a === '--global-skill') ; // consumed by planSkill below
728
+ else if (a === '--vscode' || a === '--no-vscode') ; // consumed by planVscode below
667
729
  else if (a === '--git' || a === '--no-git') ; // consumed by planGit below
668
730
  else if (a === '--remote') i++; // consumed by planRemote below
669
731
  else if (a === '--no-remote') ; // likewise
670
732
  else if (a === '--design-system') i++; // consumed by planDesignSystem below
671
733
  else if (a === '--no-design-system') ; // likewise
734
+ else if (a === '--starter') i++; // consumed by planStarter below
735
+ else if (a.startsWith('--starter=')) ; // likewise
672
736
  else if (!a.startsWith('-')) title = title ?? a;
673
737
  else fail(`unknown argument: ${a}`);
674
738
  }
@@ -680,6 +744,8 @@ unless --no-skill is given. The deck file is only touched with --force.
680
744
  const home = configHome(env);
681
745
  let ds = planDesignSystem({ args: argv, inline });
682
746
  if (ds.action === 'refuse') fail(ds.why);
747
+ const starterPlan = planStarter({ args: argv, tty: Boolean(process.stdin.isTTY && process.stdout.isTTY) });
748
+ if (starterPlan.action === 'refuse') fail(starterPlan.why);
683
749
  let dsRef = null;
684
750
  if (ds.action === 'use') {
685
751
  try { dsRef = await resolveDesignSystemFlag(ds.ref, home); } catch (e) { fail(e.message); }
@@ -723,6 +789,7 @@ unless --no-skill is given. The deck file is only touched with --force.
723
789
  };
724
790
 
725
791
  title = await resolveTitle(title, { isTTY: tty, ask: question });
792
+ const starter = starterPlan.action === 'ask' ? pickStarter(await question(STARTER_QUESTION)) : starterPlan.starter;
726
793
  const themeNames = resolveThemes(themesSel);
727
794
  const activeTheme = themeNames.includes(STARTER_THEME) ? STARTER_THEME : themeNames[0];
728
795
 
@@ -764,7 +831,7 @@ unless --no-skill is given. The deck file is only touched with --force.
764
831
  }
765
832
  }
766
833
  const plainNote = 'slides and a config block, no runtime in the file — decklight bundle embeds it to send';
767
- let body = starterDeck(title, themeNames, activeTheme, { inline });
834
+ let body = starterDeck(title, themeNames, activeTheme, { inline, starter });
768
835
  let themeNote = !inline ? `theme: ${activeTheme} · ${plainNote}`
769
836
  : themeNames.length === 1
770
837
  ? `theme: ${themeNames[0]}`
@@ -773,7 +840,7 @@ unless --no-skill is given. The deck file is only touched with --force.
773
840
  if (dsRef) {
774
841
  // a failure here costs a note and a plain deck, never the scaffold
775
842
  try {
776
- wired = await wireDesignSystem((titleSlide) => starterDeck(title, themeNames, activeTheme, { titleSlide }),
843
+ wired = await wireDesignSystem((titleSlide) => starterDeck(title, themeNames, activeTheme, { titleSlide, starter }),
777
844
  dsRef, { home, titleHtml: escapeHtml(title) });
778
845
  body = wired.html;
779
846
  themeNote = `${wired.label} · ${plainNote}`;
@@ -783,7 +850,7 @@ unless --no-skill is given. The deck file is only touched with --force.
783
850
  }
784
851
  }
785
852
  fs.writeFileSync(deckPath, body);
786
- note(`created ${deckRel} (${themeNote})`);
853
+ note(`created ${deckRel} (${starter === 'full' ? 'full starter: one slide per feature · ' : ''}${themeNote})`);
787
854
  if (dsNote) note(dsNote);
788
855
  if (ds.action === 'hint') note(designSystemHint(ds.systems));
789
856
  if (wired) {
@@ -844,6 +911,13 @@ unless --no-skill is given. The deck file is only touched with --force.
844
911
  }
845
912
  }
846
913
 
914
+ // ── VS Code's completions and snippets, before git so the commit has them ─
915
+ let vscode = planVscode({ args: argv, tty, hasCode: hasBin('code') }).action;
916
+ if (vscode === 'ask') {
917
+ vscode = (await askYes(' add VS Code completions and snippets for Decklight (.vscode/)? [Y/n] ')) ? 'write' : 'skip';
918
+ }
919
+ if (vscode === 'write') for (const line of writeEditorSupport(root)) note(line);
920
+
847
921
  // ── the git offer — dev's question, asked at the natural moment ──────────
848
922
  const plan = planGit({ args: argv, tty, inRepo: inGitRepo(root) });
849
923
  let { action } = plan;
@@ -0,0 +1,68 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { spawn } from 'node:child_process';
5
+
6
+ // The helper owns the assertion. Its stdin closes even if Decklight is killed.
7
+ // macOS also watches Decklight's PID directly.
8
+ const windows = (display) => `
9
+ Add-Type -Namespace Decklight -Name Power -MemberDefinition @'
10
+ [System.Runtime.InteropServices.DllImport("kernel32.dll")]
11
+ public static extern uint SetThreadExecutionState(uint flags);
12
+ '@
13
+ if (![Decklight.Power]::SetThreadExecutionState(${display ? 2147483651 : 2147483649})) { exit 1 }
14
+ try {
15
+ [Console]::WriteLine('ready')
16
+ [void][Console]::In.ReadToEnd()
17
+ } finally {
18
+ [void][Decklight.Power]::SetThreadExecutionState(2147483648)
19
+ }
20
+ `;
21
+
22
+ export async function keepAwake({ display = false, platform = process.platform, launch = spawn } = {}) {
23
+ const commands = {
24
+ darwin: ['caffeinate', [...(display ? ['-d'] : []), '-i', '-w', String(process.pid)]],
25
+ linux: ['systemd-inhibit', ['--what=idle:sleep', '--mode=block', '--who=Decklight',
26
+ '--why=Exporting a deck', process.execPath, '-e',
27
+ 'console.log("ready"); process.stdin.resume()']],
28
+ win32: ['powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', windows(display)]],
29
+ };
30
+ const command = commands[platform];
31
+ if (!command) return { active: false, release: async () => {} };
32
+ const [bin, args] = command;
33
+ const child = launch(bin, args, { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
34
+ child.stdin.on('error', () => {});
35
+ const closed = new Promise((resolve) => child.once('close', resolve));
36
+ const active = await new Promise((resolve) => {
37
+ const timer = setTimeout(() => {
38
+ child.stdin.end();
39
+ child.kill();
40
+ finish(false);
41
+ }, 5000);
42
+ function finish(ready) {
43
+ clearTimeout(timer);
44
+ resolve(ready);
45
+ }
46
+ child.once('error', () => finish(false));
47
+ child.once('close', () => finish(false));
48
+ if (platform === 'darwin') child.once('spawn', () => finish(true));
49
+ else {
50
+ let output = '';
51
+ child.stdout.on('data', (chunk) => {
52
+ output += chunk;
53
+ if (output.includes('ready')) finish(true);
54
+ });
55
+ }
56
+ });
57
+ return {
58
+ active,
59
+ // Linux requests the desktop's idle inhibitor. Whether the compositor
60
+ // also keeps the display on depends on the desktop session.
61
+ displayActive: active && display && (platform === 'darwin' || platform === 'win32'),
62
+ async release() {
63
+ child.stdin.end();
64
+ if (platform === 'darwin') child.kill();
65
+ await closed;
66
+ },
67
+ };
68
+ }
@@ -0,0 +1,214 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // LETTER_BY_LETTER. The accessible label is the one complete sentence in a
5
+ // legacy title, including in translations whose visible slots got scrambled.
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { basename, dirname, join } from 'node:path';
8
+ import { writeFileAtomic } from '../tools/atomic-write.mjs';
9
+ import { deckFamily } from '../tools/deck-family.mjs';
10
+ import { decodeNoteEntities, elementChildRanges, sectionCloseIndex, splitOpenTag } from '../tools/deck-html.mjs';
11
+ import { escapeHtml } from '../tools/escape.mjs';
12
+ import { attrList, attrOf, withAttr, withStyle } from './edit-address.mjs';
13
+ import { deckParts, formatRecord, parseRecord, slideParts, slideShape } from './translate-core.mjs';
14
+ import { recordOf, resolveSource } from './translate-files.mjs';
15
+
16
+ const irrelevant = new Set(['aside', 'code', 'pre', 'script', 'style', 'svg', 'template', 'textarea']);
17
+ const inline = new Set(['span', 'b', 'i', 'em', 'strong', 'small', 'mark', 'u', 's', 'sub', 'sup']);
18
+ const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
19
+ const oneGrapheme = (text) => !!text.trim() && graphemes.segment(text).containing(0)?.segment === text;
20
+ const timeIndex = /(?:^|;)\s*--i\s*:\s*\d+\s*(?=;|$)/;
21
+ const timeCount = /(?:^|;)\s*--n\s*:\s*\d+\s*(?=;|$)/;
22
+
23
+ function openParts(el) {
24
+ const { attrs, close, rest } = splitOpenTag(el);
25
+ return { attrs, open: attrs + close, rest };
26
+ }
27
+
28
+ function cleanChildren(el, open) {
29
+ const kids = elementChildRanges(el);
30
+ if (!kids.length) return null;
31
+ let at = open.length;
32
+ for (const { start, end, tag } of kids) {
33
+ if (decodeNoteEntities(el.slice(at, start)).trim() || irrelevant.has(tag)) return null;
34
+ at = end;
35
+ }
36
+ const close = el.lastIndexOf('</');
37
+ return close >= at && !el.slice(at, close).trim() ? { kids, close } : null;
38
+ }
39
+
40
+ function legacyTitle(el, start, sourceAt) {
41
+ const { attrs, open } = openParts(el);
42
+ const label = attrList(attrs).find((a) => a.name === 'aria-label');
43
+ const text = decodeNoteEntities(label?.value).trim();
44
+ if (!text) return null;
45
+ const parent = cleanChildren(el, open);
46
+ if (!parent) return null;
47
+ let total = 0;
48
+ const timed = timeCount.test(attrOf(attrs, 'style') ?? '');
49
+ const words = [];
50
+ for (const w of parent.kids) {
51
+ if (!inline.has(w.tag)) return null;
52
+ const word = el.slice(w.start, w.end);
53
+ const wrapped = cleanChildren(word, openParts(word).open);
54
+ if (!wrapped) return null;
55
+ let original = '';
56
+ for (const c of wrapped.kids) {
57
+ if (!inline.has(c.tag)) return null;
58
+ const { attrs: letterAttrs, open: letterOpen, rest } = openParts(word.slice(c.start, c.end));
59
+ const close = rest.indexOf('<');
60
+ if (close < 0 || !rest.startsWith('</', close)) return null;
61
+ const visible = decodeNoteEntities(rest.slice(0, close));
62
+ const source = sourceAt?.get(start + w.start + c.start + letterOpen.length) ?? visible;
63
+ if (!oneGrapheme(source) && !(timed && timeIndex.test(attrOf(letterAttrs, 'style') ?? ''))) return null;
64
+ original += source;
65
+ total++;
66
+ }
67
+ words.push(original);
68
+ }
69
+ if (total < 2 && !timed) return null;
70
+ return { start, end: start + el.length, contentStart: start + open.length, contentEnd: start + parent.close,
71
+ label, text, original: words.join(' '), attrs, close: el.slice(parent.close) };
72
+ }
73
+
74
+ function scan(body, sourceAt) {
75
+ const titles = [], followers = [];
76
+ if (!/aria-label\s*=/i.test(body)) return { titles, followers };
77
+ const { attrs, close } = splitOpenTag(body);
78
+ const from = attrs.length + close.length;
79
+ const end = sectionCloseIndex(body);
80
+ const section = `<section>${body.slice(from, end < 0 ? undefined : end)}</section>`;
81
+ function visit(el, at, tag) {
82
+ if (irrelevant.has(tag)) return;
83
+ const title = legacyTitle(el, at, sourceAt);
84
+ if (title) { titles.push(title); return; }
85
+ const { attrs: opening } = openParts(el);
86
+ if ((attrOf(opening, 'class') ?? '').split(/\s+/).includes('cf-after')) followers.push({ at, opening });
87
+ for (const c of elementChildRanges(el)) visit(el.slice(c.start, c.end), at + c.start, c.tag);
88
+ }
89
+ for (const c of elementChildRanges(section)) visit(section.slice(c.start, c.end), from - '<section>'.length + c.start, c.tag);
90
+ return { titles, followers };
91
+ }
92
+
93
+ export const legacyWriting = (body) => scan(body).titles.map((t) => t.text);
94
+
95
+ function classes(attrs, remove) {
96
+ return (attrOf(attrs, 'class') ?? '').split(/\s+/).filter((c) => c && !remove.includes(c)).join(' ') || null;
97
+ }
98
+
99
+ function replacement(title) {
100
+ const out = (attrOf(title.attrs, 'class') ?? '').split(/\s+/).includes('cf-write-out');
101
+ let attrs = withAttr(title.attrs, 'class', classes(title.attrs, ['cf-write', 'cf-write-out']));
102
+ attrs = withAttr(attrs, 'aria-label', null);
103
+ if (timeCount.test(attrOf(attrs, 'style') ?? '')) attrs = withStyle(attrs, '--n', null);
104
+ return `${withAttr(attrs, 'data-write', out ? 'out' : true)}>${escapeHtml(title.text)}${title.close}`;
105
+ }
106
+
107
+ function migrateSlide(body, record, hash) {
108
+ const old = record ? slideParts(body) : null;
109
+ const belongs = old && old.units.length === record.length && old.units.every((u, i) => u.kind === record[i].kind);
110
+ const runEdits = old?.edits.filter((e) => old.units[e.units?.[0]]?.kind === 'run') ?? [];
111
+ const sourceAt = belongs ? new Map(runEdits.map((e) => [e.start, record[e.units[0]].source])) : null;
112
+ const { titles, followers } = scan(body, sourceAt);
113
+ if (!titles.length) return { body, record, count: 0 };
114
+ if (record && (!belongs || (hash && slideShape(body) !== hash))) {
115
+ throw new Error('the slide differs structurally from its translation record');
116
+ }
117
+ const writes = titles.map((t) => ({ start: t.start, end: t.end, value: replacement(t) }));
118
+ for (const { at, opening } of followers) {
119
+ const attrs = withAttr(opening, 'class', classes(opening, ['cf-after']));
120
+ writes.push({ start: at, end: at + opening.length, value: withAttr(attrs, 'data-write-after', true) });
121
+ }
122
+ let migrated = body;
123
+ for (const { start, end, value } of writes.sort((a, b) => b.start - a.start)) {
124
+ migrated = migrated.slice(0, start) + value + migrated.slice(end);
125
+ }
126
+ if (!record) return { body: migrated, count: titles.length };
127
+
128
+ const removed = new Set();
129
+ const insertions = new Map();
130
+ for (const t of titles) {
131
+ let labelPair;
132
+ for (const e of old.edits) {
133
+ if (e.start >= t.contentStart && e.end <= t.contentEnd) {
134
+ for (const i of e.units ?? []) removed.add(i);
135
+ } else if (e.start >= t.start + t.label.start && e.end <= t.start + t.label.end) {
136
+ const i = e.units?.[0];
137
+ if (i !== undefined) { removed.add(i); labelPair = record[i]; }
138
+ }
139
+ }
140
+ const run = runEdits.find((e) => e.start >= t.contentStart)?.units[0] ?? runEdits.length;
141
+ const pair = labelPair ? { ...labelPair, kind: 'run', target: t.text } :
142
+ { kind: 'run', source: t.original, target: t.text, state: 'machine' };
143
+ if (labelPair && labelPair.target !== t.text) { pair.state = 'reviewed'; delete pair.was; }
144
+ const here = insertions.get(run) ?? [];
145
+ here.push(pair);
146
+ insertions.set(run, here);
147
+ }
148
+ const pairs = [...record, null].flatMap((pair, i) => [
149
+ ...(insertions.get(i) ?? []), ...(pair && !removed.has(i) ? [pair] : []),
150
+ ]);
151
+ const after = slideParts(migrated);
152
+ if (after.units.length !== pairs.length || after.units.some((u, i) => u.kind !== pairs[i].kind)) {
153
+ throw new Error('could not align the converted text with its translation record');
154
+ }
155
+ return { body: migrated, count: titles.length, record: pairs, hash: slideShape(migrated) };
156
+ }
157
+
158
+ function planDeck(path, html, record) {
159
+ const parts = deckParts(html);
160
+ const slides = record?.slides.slice();
161
+ const structure = record?.structure.slice();
162
+ let count = 0;
163
+ for (let at = 2; at < parts.length; at += 2) {
164
+ const index = at / 2 - 1;
165
+ let r;
166
+ try { r = migrateSlide(parts[at], slides?.[index], structure?.[index]); }
167
+ catch (e) { throw new Error(`${basename(path)}, slide ${index + 1}: ${e.message}`); }
168
+ if (!r.count) continue;
169
+ if (record && !slides[index]) throw new Error(`${basename(path)}, slide ${index + 1}: missing translation record`);
170
+ count += r.count;
171
+ parts[at] = r.body;
172
+ if (record) { slides[index] = r.record; structure[index] = r.hash; }
173
+ }
174
+ return { html: parts.join(''), count, record: record && { ...record, slides, structure } };
175
+ }
176
+
177
+ /** Plan the whole family before writing. Restore earlier files if a write fails. */
178
+ export function migrateWriting(deck) {
179
+ const { source } = resolveSource(deck);
180
+ const paths = [source, ...deckFamily(source).members.filter((m) => m.lang).map((m) => join(dirname(source), m.name))];
181
+ const writes = [];
182
+ let count = 0;
183
+ for (const path of paths) {
184
+ const html = readFileSync(path, 'utf8');
185
+ const recPath = recordOf(path);
186
+ const rec = path !== source && existsSync(recPath) ? readFileSync(recPath, 'utf8') : null;
187
+ const plan = planDeck(path, html, rec ? parseRecord(rec) : null);
188
+ if (!plan.count) continue;
189
+ count += plan.count;
190
+ writes.push({ path, before: html, after: plan.html });
191
+ if (rec) writes.push({ path: recPath, before: rec, after: formatRecord(plan.record) });
192
+ }
193
+ const done = [];
194
+ try {
195
+ for (const w of writes) {
196
+ const current = readFileSync(w.path, 'utf8');
197
+ if (current === w.after) continue;
198
+ if (current !== w.before) throw new Error(`${basename(w.path)} changed during migration`);
199
+ writeFileAtomic(w.path, w.after);
200
+ done.push(w);
201
+ }
202
+ } catch (e) {
203
+ const couldNotRestore = [];
204
+ for (const w of done.reverse()) {
205
+ try {
206
+ if (readFileSync(w.path, 'utf8') !== w.after) throw new Error('file changed');
207
+ writeFileAtomic(w.path, w.before);
208
+ } catch { couldNotRestore.push(basename(w.path)); }
209
+ }
210
+ if (couldNotRestore.length) throw new Error(`${e.message}. Could not restore ${couldNotRestore.join(', ')}`);
211
+ throw e;
212
+ }
213
+ return count;
214
+ }