@lifeaitools/rdc-skills 0.24.38 → 0.24.39

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 (191) hide show
  1. package/.claude/settings.json +15 -15
  2. package/.claude-plugin/marketplace.json +21 -21
  3. package/.claude-plugin/plugin.json +1371 -1371
  4. package/.github/workflows/publish.yml +34 -34
  5. package/.github/workflows/self-test.yml +58 -58
  6. package/CHANGELOG.md +310 -310
  7. package/LICENSE +21 -21
  8. package/MANIFEST.md +221 -221
  9. package/README.md +377 -377
  10. package/README.sandbox.md +3 -3
  11. package/assets/watcher/viewer.html +164 -164
  12. package/bin/rdc-skills-mcp.mjs +316 -316
  13. package/commands/build.md +183 -183
  14. package/commands/collab.md +180 -180
  15. package/commands/deploy.md +152 -152
  16. package/commands/design.md +31 -31
  17. package/commands/edit.md +28 -28
  18. package/commands/fixit.md +124 -124
  19. package/commands/handoff.md +173 -173
  20. package/commands/help.md +95 -95
  21. package/commands/overnight.md +220 -220
  22. package/commands/plan.md +158 -158
  23. package/commands/preplan.md +131 -131
  24. package/commands/prototype.md +145 -145
  25. package/commands/release.md +49 -49
  26. package/commands/report.md +99 -99
  27. package/commands/review.md +120 -120
  28. package/commands/self-test.md +113 -113
  29. package/commands/status.md +86 -86
  30. package/commands/watch.md +98 -98
  31. package/commands/workitems.md +137 -137
  32. package/git-sha.json +1 -1
  33. package/guides/agent-bootstrap.md +295 -295
  34. package/guides/agents/backend.md +104 -104
  35. package/guides/agents/content.md +94 -94
  36. package/guides/agents/cs2.md +56 -56
  37. package/guides/agents/data.md +87 -87
  38. package/guides/agents/design.md +77 -77
  39. package/guides/agents/frontend.md +92 -92
  40. package/guides/agents/infrastructure.md +81 -81
  41. package/guides/agents/setup.md +281 -281
  42. package/guides/agents/verify.md +151 -151
  43. package/guides/agents/viz.md +106 -106
  44. package/guides/backend.md +146 -146
  45. package/guides/content.md +147 -147
  46. package/guides/cs2.md +190 -190
  47. package/guides/data.md +123 -123
  48. package/guides/design.md +116 -116
  49. package/guides/engineering-behavior.md +43 -43
  50. package/guides/escalation-protocol.md +125 -125
  51. package/guides/frontend.md +151 -151
  52. package/guides/history-md-spec.md +297 -297
  53. package/guides/infrastructure.md +179 -179
  54. package/guides/lessons-learned-spec.md +153 -153
  55. package/guides/output-contract.md +108 -108
  56. package/guides/publish-md-spec.md +289 -289
  57. package/guides/rdc-skills-startup.md +30 -30
  58. package/guides/verify.md +11 -11
  59. package/hooks/check-cwd.js +31 -31
  60. package/hooks/check-rdc-environment.js +164 -164
  61. package/hooks/check-services.js +6 -6
  62. package/hooks/check-stale-work-items.js +19 -19
  63. package/hooks/foreground-process-gate.js +128 -128
  64. package/hooks/gate-watchdog-selfcheck.js +257 -257
  65. package/hooks/hook-logger.js +25 -25
  66. package/hooks/lib/run-evidence-gate.mjs +241 -241
  67. package/hooks/no-stop-open-epics.js +127 -127
  68. package/hooks/post-tool-batch-gate.js +203 -203
  69. package/hooks/post-work-check.js +21 -21
  70. package/hooks/postcompact-log.js +13 -13
  71. package/hooks/precompact-log.js +13 -13
  72. package/hooks/rate-limit-retry.js +46 -46
  73. package/hooks/rdc-invocation-marker.js +157 -157
  74. package/hooks/rdc-output-contract-gate.js +94 -94
  75. package/hooks/require-work-item-on-commit.js +294 -294
  76. package/hooks/restart-brief.js +19 -19
  77. package/hooks/run-hidden-hook.ps1 +47 -47
  78. package/hooks/task-completed-gate.js +274 -274
  79. package/hooks/work-item-exit-gate.js +944 -944
  80. package/lib/catalog.mjs +236 -236
  81. package/lib/cloud-rewrite.mjs +155 -155
  82. package/package.json +56 -56
  83. package/rules/work-items-rpc.md +520 -520
  84. package/scaffold/templates/HISTORY.md.template +39 -39
  85. package/scaffold/templates/PUBLISH.md.template +21 -21
  86. package/scaffold/templates/brochure-studio-default.html +70 -70
  87. package/scripts/acceptance.mjs +502 -502
  88. package/scripts/fixtures/guides/bad-guide.md +15 -15
  89. package/scripts/fixtures/guides-clean/good-guide.md +16 -16
  90. package/scripts/install-rdc-skills.js +1289 -1289
  91. package/scripts/install.ps1 +202 -202
  92. package/scripts/install.sh +132 -132
  93. package/scripts/lib/assertions.mjs +287 -287
  94. package/scripts/lib/manifest-schema.mjs +754 -754
  95. package/scripts/lib/runner.mjs +465 -465
  96. package/scripts/lib/sandbox.mjs +435 -435
  97. package/scripts/prepack.mjs +32 -32
  98. package/scripts/rdc-brochure.mjs +464 -464
  99. package/scripts/rdc-design-cli.mjs +134 -134
  100. package/scripts/rebuild-mcp.mjs +107 -107
  101. package/scripts/self-test.mjs +1460 -1460
  102. package/scripts/stamp-git-sha.mjs +29 -29
  103. package/scripts/test-guide-validator.mjs +196 -196
  104. package/scripts/test-rdc-hooks.mjs +145 -145
  105. package/scripts/uninstall.ps1 +77 -77
  106. package/scripts/uninstall.sh +69 -69
  107. package/scripts/update.ps1 +43 -43
  108. package/scripts/update.sh +43 -43
  109. package/scripts/validate-place-histories.js +461 -461
  110. package/scripts/validate-publish-manifests.js +424 -424
  111. package/scripts/watch-init.mjs +100 -100
  112. package/skills/brochure/SKILL.md +107 -107
  113. package/skills/build/SKILL.md +563 -563
  114. package/skills/channel-formatter/SKILL.md +533 -533
  115. package/skills/co-develop/SKILL.md +196 -196
  116. package/skills/collab/SKILL.md +239 -239
  117. package/skills/convert/SKILL.md +140 -140
  118. package/skills/deploy/SKILL.md +541 -541
  119. package/skills/design/SKILL.md +211 -211
  120. package/skills/design/reference/ownership.md +16 -16
  121. package/skills/design/reference/rampa.md +92 -92
  122. package/skills/design/reference/studio-model.md +153 -153
  123. package/skills/edit/SKILL.md +98 -98
  124. package/skills/fixit/SKILL.md +165 -165
  125. package/skills/fs-mcp/SKILL.md +148 -148
  126. package/skills/handoff/SKILL.md +236 -200
  127. package/skills/help/SKILL.md +143 -143
  128. package/skills/housekeeping/SKILL.md +189 -189
  129. package/skills/lifeai-brochure-author/SKILL.md +340 -340
  130. package/skills/overnight/SKILL.md +251 -251
  131. package/skills/plan/SKILL.md +345 -345
  132. package/skills/preplan/SKILL.md +90 -90
  133. package/skills/prototype/SKILL.md +150 -150
  134. package/skills/rdc-brochurify/SKILL.md +245 -245
  135. package/skills/rdc-extract-verifier-rules/SKILL.md +191 -191
  136. package/skills/release/SKILL.md +140 -140
  137. package/skills/report/SKILL.md +100 -100
  138. package/skills/review/SKILL.md +152 -152
  139. package/skills/rpms-filemap/SKILL.cloud.md +111 -111
  140. package/skills/rpms-filemap/SKILL.md +111 -111
  141. package/skills/self-test/SKILL.md +132 -132
  142. package/skills/status/SKILL.md +99 -99
  143. package/skills/terminal-config/SKILL.md +62 -62
  144. package/skills/tests/MATRIX.md +54 -54
  145. package/skills/tests/README.md +47 -47
  146. package/skills/tests/rdc-brochure.test.json +34 -34
  147. package/skills/tests/rdc-build.test.json +36 -36
  148. package/skills/tests/rdc-channel-formatter.test.json +45 -45
  149. package/skills/tests/rdc-co-develop.test.json +29 -29
  150. package/skills/tests/rdc-collab.test.json +29 -29
  151. package/skills/tests/rdc-convert.test.json +35 -35
  152. package/skills/tests/rdc-deploy.test.json +30 -30
  153. package/skills/tests/rdc-design.test.json +27 -27
  154. package/skills/tests/rdc-edit.test.json +29 -29
  155. package/skills/tests/rdc-fixit.test.json +36 -36
  156. package/skills/tests/rdc-fs-mcp.test.json +36 -36
  157. package/skills/tests/rdc-handoff.test.json +28 -28
  158. package/skills/tests/rdc-help.test.json +29 -29
  159. package/skills/tests/rdc-housekeeping.test.json +31 -31
  160. package/skills/tests/rdc-lifeai-brochure-author.test.json +35 -35
  161. package/skills/tests/rdc-overnight.test.json +37 -37
  162. package/skills/tests/rdc-plan.test.json +27 -27
  163. package/skills/tests/rdc-preplan.test.json +31 -31
  164. package/skills/tests/rdc-prototype.test.json +28 -28
  165. package/skills/tests/rdc-rdc-brochurify.test.json +23 -23
  166. package/skills/tests/rdc-rdc-extract-verifier-rules.test.json +34 -34
  167. package/skills/tests/rdc-release.test.json +29 -29
  168. package/skills/tests/rdc-report.test.json +28 -28
  169. package/skills/tests/rdc-review.test.json +29 -29
  170. package/skills/tests/rdc-rpms-filemap.test.json +28 -28
  171. package/skills/tests/rdc-self-test.test.json +24 -24
  172. package/skills/tests/rdc-status.test.json +29 -29
  173. package/skills/tests/rdc-terminal-config.test.json +29 -29
  174. package/skills/tests/rdc-watch.test.json +24 -24
  175. package/skills/tests/rdc-workitems.test.json +27 -27
  176. package/skills/watch/SKILL.md +97 -97
  177. package/skills/workitems/SKILL.md +151 -151
  178. package/tests/acceptance.test.mjs +59 -59
  179. package/tests/channel-formatter.contract.test.mjs +251 -251
  180. package/tests/curl-surface.test.mjs +289 -289
  181. package/tests/harness-gates.test.mjs +325 -325
  182. package/tests/help-surface.test.mjs +61 -61
  183. package/tests/install-rdc-skills.test.mjs +49 -49
  184. package/tests/manifest-contract-fields.test.mjs +78 -78
  185. package/tests/mcp.test.mjs +271 -271
  186. package/tests/require-work-item-on-commit.test.mjs +162 -162
  187. package/tests/run-evidence-gate.test.mjs +82 -82
  188. package/tests/skill-test-matrix.test.mjs +66 -66
  189. package/tests/validate-skills.js +27 -27
  190. package/tests/work-item-exit-gate-l2.test.mjs +368 -368
  191. package/tests/work-item-exit-gate-l3.test.mjs +197 -197
@@ -1,464 +1,464 @@
1
- #!/usr/bin/env node
2
- /**
3
- * rdc:brochure — zip/folder/html/url/markdown → PDF via Puppeteer.
4
- * See skills/brochure/SKILL.md for the contract.
5
- */
6
- import { execSync, spawnSync } from 'node:child_process';
7
- import { createHash } from 'node:crypto';
8
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
9
- import { homedir, tmpdir } from 'node:os';
10
- import { dirname, basename, extname, join, resolve, relative, sep } from 'node:path';
11
- import { pathToFileURL, fileURLToPath } from 'node:url';
12
- import { createRequire } from 'node:module';
13
-
14
- const AUTO_FIT_CSS = `
15
- /* rdc:brochure --auto-fit corrective stylesheet
16
- Generic print-overflow safety net. Applied AFTER document stylesheets. */
17
- @media print, screen {
18
- html, body { overflow: visible !important; }
19
- body { max-width: 100% !important; }
20
- *, *::before, *::after { box-sizing: border-box; }
21
-
22
- img, svg, video, canvas, iframe, object, embed {
23
- max-width: 100% !important;
24
- height: auto !important;
25
- object-fit: contain;
26
- }
27
- figure, .figure, picture { break-inside: avoid; page-break-inside: avoid; max-width: 100%; }
28
-
29
- table {
30
- table-layout: fixed !important;
31
- width: 100% !important;
32
- max-width: 100% !important;
33
- word-wrap: break-word;
34
- overflow-wrap: anywhere;
35
- border-collapse: collapse;
36
- }
37
- th, td { word-wrap: break-word; overflow-wrap: anywhere; max-width: 100%; }
38
- thead { display: table-header-group; }
39
- tr, td, th { break-inside: avoid; page-break-inside: avoid; }
40
-
41
- pre, code, kbd, samp { white-space: pre-wrap !important; word-break: break-word; overflow-wrap: anywhere; max-width: 100%; }
42
- pre { break-inside: avoid; page-break-inside: avoid; }
43
-
44
- h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
45
- h1 + *, h2 + *, h3 + *, h4 + * { break-before: avoid; }
46
- p, li { orphans: 3; widows: 3; }
47
-
48
- /* Generic wide-content sentinels */
49
- .wide, .full-bleed, .panorama { max-width: 100% !important; }
50
-
51
- /* Avoid blank-page artifacts from oversized flex/grid containers */
52
- [style*="position: fixed"], [style*="position:fixed"] { position: static !important; }
53
- }
54
- `;
55
-
56
- const HERE = dirname(fileURLToPath(import.meta.url));
57
- const REPO_ROOT = resolve(HERE, '..');
58
- const TEMPLATES_DIR = join(REPO_ROOT, 'scaffold', 'templates');
59
-
60
- // --- args ------------------------------------------------------------------
61
- const argv = process.argv.slice(2);
62
- const opts = { template: 'studio-default', format: 'Letter', printEmulate: true, keepWorkdir: false, autoFit: false, scale: 1 };
63
- let input;
64
- for (let i = 0; i < argv.length; i++) {
65
- const a = argv[i];
66
- if (a === '--out') opts.out = argv[++i];
67
- else if (a === '--template') opts.template = argv[++i];
68
- else if (a === '--format') opts.format = argv[++i];
69
- else if (a === '--margin') opts.margin = argv[++i];
70
- else if (a === '--no-print-emulate') opts.printEmulate = false;
71
- else if (a === '--keep-workdir') opts.keepWorkdir = true;
72
- else if (a === '--auto-fit') opts.autoFit = true;
73
- else if (a === '--scale') opts.scale = parseFloat(argv[++i]);
74
- else if (!input) input = a;
75
- }
76
- if (!input) {
77
- console.error('usage: rdc-brochure.mjs <zip|folder|html|md|url> [--out path] [--template name] [--format Letter|A4]');
78
- process.exit(2);
79
- }
80
-
81
- // --- helpers ---------------------------------------------------------------
82
- const isUrl = /^https?:\/\//i.test(input);
83
- const hash = createHash('sha1').update(input).digest('hex').slice(0, 10);
84
- const workRoot = join(tmpdir(), 'rdc-brochure', hash);
85
- mkdirSync(workRoot, { recursive: true });
86
-
87
- const log = (...a) => console.log('[brochure]', ...a);
88
-
89
- function human(n) {
90
- const u = ['B', 'KB', 'MB', 'GB'];
91
- let i = 0;
92
- while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
93
- return `${n.toFixed(1)} ${u[i]}`;
94
- }
95
-
96
- function walk(dir) {
97
- const out = [];
98
- for (const e of readdirSync(dir, { withFileTypes: true })) {
99
- const p = join(dir, e.name);
100
- if (e.isDirectory()) out.push(...walk(p));
101
- else out.push(p);
102
- }
103
- return out;
104
- }
105
-
106
- // --- ensure puppeteer ------------------------------------------------------
107
- async function loadPuppeteer() {
108
- try { return (await import('puppeteer')).default; } catch {}
109
- // Try a local cache install.
110
- const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
111
- mkdirSync(cacheDir, { recursive: true });
112
- if (!existsSync(join(cacheDir, 'package.json'))) {
113
- writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
114
- }
115
- if (!existsSync(join(cacheDir, 'node_modules', 'puppeteer'))) {
116
- log('installing puppeteer into', cacheDir);
117
- execSync('npm install puppeteer --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
118
- }
119
- const req = createRequire(join(cacheDir, 'package.json'));
120
- const mod = req('puppeteer');
121
- return mod.default || mod;
122
- }
123
-
124
- // --- cross-platform unzip --------------------------------------------------
125
- // Pure-Node first (adm-zip — works on every platform, no external binary).
126
- // If the lib cannot be resolved or installed, fall back to a platform-native
127
- // extractor: `unzip` on POSIX, PowerShell `Expand-Archive` on win32.
128
- function loadAdmZip() {
129
- try { return createRequire(import.meta.url)('adm-zip'); } catch {}
130
- // Reuse the puppeteer on-demand cache dir for an isolated local install.
131
- const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
132
- mkdirSync(cacheDir, { recursive: true });
133
- if (!existsSync(join(cacheDir, 'package.json'))) {
134
- writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
135
- }
136
- if (!existsSync(join(cacheDir, 'node_modules', 'adm-zip'))) {
137
- try {
138
- log('installing adm-zip into', cacheDir);
139
- execSync('npm install adm-zip --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
140
- } catch { return null; }
141
- }
142
- try { return createRequire(join(cacheDir, 'package.json'))('adm-zip'); } catch { return null; }
143
- }
144
-
145
- // Reject any archive member that resolves outside destDir (zip-slip / path
146
- // traversal). Returns the validated absolute destination path. Throws on escape.
147
- function safeJoinOrThrow(destDir, entryName) {
148
- const root = resolve(destDir);
149
- const dest = resolve(root, entryName);
150
- if (dest !== root && !dest.startsWith(root + sep)) {
151
- throw new Error(`zip-slip: entry "${entryName}" escapes destination directory`);
152
- }
153
- return dest;
154
- }
155
-
156
- function extractZip(zipPath, destDir) {
157
- mkdirSync(destDir, { recursive: true });
158
- const root = resolve(destDir);
159
- const AdmZip = loadAdmZip();
160
- if (AdmZip) {
161
- const zip = new AdmZip(zipPath);
162
- const entries = zip.getEntries();
163
- // First pass: validate every entry resolves inside destDir. A brochure
164
- // source zip must never contain `..` or absolute members — reject the whole
165
- // archive rather than silently skipping (fail-closed).
166
- for (const entry of entries) {
167
- safeJoinOrThrow(root, entry.entryName);
168
- }
169
- // Second pass: extract validated entries individually. Do NOT use the
170
- // blanket extractAllTo — adm-zip does not sanitize entry paths.
171
- for (const entry of entries) {
172
- if (entry.isDirectory) {
173
- mkdirSync(safeJoinOrThrow(root, entry.entryName), { recursive: true });
174
- continue;
175
- }
176
- const dest = safeJoinOrThrow(root, entry.entryName);
177
- mkdirSync(dirname(dest), { recursive: true });
178
- zip.extractEntryTo(entry, root, /* maintainEntryPath */ true, /* overwrite */ true);
179
- }
180
- return;
181
- }
182
- // Fallback: platform-native extractor. Validate members via a listing pass
183
- // BEFORE extracting, since the bulk extract commands cannot apply per-entry
184
- // guards. Reject any `..` segment or absolute/leading-slash member.
185
- log('adm-zip unavailable — falling back to platform unzip');
186
- assertNativeZipSafe(zipPath);
187
- let r;
188
- if (process.platform === 'win32') {
189
- r = spawnSync('powershell', ['-NoProfile', '-Command',
190
- `Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force`], { stdio: 'inherit' });
191
- } else {
192
- r = spawnSync('unzip', ['-o', '-q', zipPath, '-d', destDir], { stdio: 'inherit' });
193
- }
194
- if (!r || r.status !== 0) throw new Error('unzip failed (no pure-Node lib and platform extractor failed)');
195
- }
196
-
197
- // List archive members with a native tool and reject any traversal/absolute
198
- // entry. Throws if a member is unsafe or the listing cannot be produced.
199
- function assertNativeZipSafe(zipPath) {
200
- let names = [];
201
- if (process.platform === 'win32') {
202
- const ps = spawnSync('powershell', ['-NoProfile', '-Command',
203
- `Add-Type -AssemblyName System.IO.Compression.FileSystem; ` +
204
- `[System.IO.Compression.ZipFile]::OpenRead('${zipPath}').Entries | ForEach-Object { $_.FullName }`],
205
- { encoding: 'utf8' });
206
- if (ps.status !== 0) throw new Error('cannot list zip members for traversal check (PowerShell)');
207
- names = String(ps.stdout || '').split(/\r?\n/);
208
- } else {
209
- const zi = spawnSync('zipinfo', ['-1', zipPath], { encoding: 'utf8' });
210
- if (zi.status === 0) {
211
- names = String(zi.stdout || '').split(/\r?\n/);
212
- } else {
213
- const ul = spawnSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' });
214
- if (ul.status !== 0) throw new Error('cannot list zip members for traversal check (unzip -Z1)');
215
- names = String(ul.stdout || '').split(/\r?\n/);
216
- }
217
- }
218
- for (const raw of names) {
219
- const name = raw.trim();
220
- if (!name) continue;
221
- const norm = name.replace(/\\/g, '/');
222
- if (norm.startsWith('/') || /^[A-Za-z]:/.test(norm) || norm.split('/').some((seg) => seg === '..')) {
223
- throw new Error(`zip-slip: entry "${name}" escapes destination directory`);
224
- }
225
- }
226
- }
227
-
228
- // --- stage input -----------------------------------------------------------
229
- function stageInput() {
230
- const stageDir = join(workRoot, 'src');
231
- mkdirSync(stageDir, { recursive: true });
232
- if (isUrl) return { kind: 'url', url: input, stageDir };
233
- const abs = resolve(input);
234
- if (!existsSync(abs)) throw new Error(`not found: ${abs}`);
235
- const st = statSync(abs);
236
- if (st.isDirectory()) return { kind: 'folder', root: abs, stageDir: abs };
237
- const ext = extname(abs).toLowerCase();
238
- if (ext === '.zip') {
239
- log('extracting zip to', stageDir);
240
- extractZip(abs, stageDir);
241
- return { kind: 'folder', root: stageDir, stageDir };
242
- }
243
- if (ext === '.html' || ext === '.htm') return { kind: 'html', file: abs, stageDir: dirname(abs) };
244
- if (ext === '.md' || ext === '.markdown') return { kind: 'md', file: abs, stageDir: dirname(abs) };
245
- throw new Error(`unsupported input: ${ext || '(no extension)'}`);
246
- }
247
-
248
- // --- pick HTML in render mode ----------------------------------------------
249
- function pickHtml(rootDir) {
250
- const htmls = walk(rootDir).filter((p) => /\.html?$/i.test(p));
251
- if (!htmls.length) return null;
252
- const scored = htmls.map((p) => {
253
- const text = readFileSync(p, 'utf8');
254
- const size = statSync(p).size;
255
- let score = 0;
256
- if (/@page\b/.test(text)) score += 1000;
257
- if (/@media\s+print/i.test(text)) score += 500;
258
- if (/-print\.html?$/i.test(p)) score += 300;
259
- if (/brochure\.html?$/i.test(p)) score += 250;
260
- if (/(^|[\\/])print\.html?$/i.test(p)) score += 250;
261
- if (/standalone/i.test(basename(p))) score -= 50; // usually huge embedded duplicate
262
- score += Math.min(size / 1024, 200); // size as tiebreaker, capped
263
- return { p, score, size };
264
- }).sort((a, b) => b.score - a.score);
265
- return scored[0].p;
266
- }
267
-
268
- // --- compose mode ----------------------------------------------------------
269
- function listTemplates() {
270
- if (!existsSync(TEMPLATES_DIR)) return [];
271
- return readdirSync(TEMPLATES_DIR)
272
- .map((f) => /^brochure-(.+)\.html$/i.exec(f))
273
- .filter(Boolean)
274
- .map((m) => m[1])
275
- .sort();
276
- }
277
-
278
- async function composeFromFolder(root, file) {
279
- const tpl = join(TEMPLATES_DIR, `brochure-${opts.template}.html`);
280
- if (!existsSync(tpl)) {
281
- const available = listTemplates();
282
- const list = available.length ? available.join(', ') : '(none found)';
283
- throw new Error(`unknown template "${opts.template}". Available template(s): ${list}`);
284
- }
285
- let html = readFileSync(tpl, 'utf8');
286
-
287
- let mdFiles = [];
288
- if (file) mdFiles = [file];
289
- else mdFiles = walk(root).filter((p) => /\.(md|markdown)$/i.test(p)).sort();
290
-
291
- const title = (() => {
292
- for (const p of mdFiles) {
293
- const m = readFileSync(p, 'utf8').match(/^#\s+(.+)$/m);
294
- if (m) return m[1].trim();
295
- }
296
- return basename(file || root);
297
- })();
298
-
299
- const sections = mdFiles.map((p) => {
300
- const md = readFileSync(p, 'utf8');
301
- // Only prepend the filename heading when the markdown has no leading ATX heading
302
- // of its own. Avoids a redundant <h2>filename</h2> stacked above a "# Title".
303
- const firstNonEmpty = md.replace(/\r\n/g, '\n').split('\n').find((l) => l.trim() !== '') || '';
304
- const hasLeadingHeading = /^#{1,6}\s+\S/.test(firstNonEmpty.trim());
305
- const heading = hasLeadingHeading ? '' : `<h2>${escapeHtml(basename(p, extname(p)))}</h2>`;
306
- return `<section class="brochure-section">${heading}${mdToHtml(md, dirname(p))}</section>`;
307
- }).join('\n');
308
-
309
- html = html.replace(/\{\{TITLE\}\}/g, escapeHtml(title)).replace(/\{\{SECTIONS\}\}/g, sections);
310
-
311
- const tokensCss = findSibling(root || dirname(file), 'tokens.css');
312
- if (tokensCss) html = html.replace('/* TOKENS_INJECT */', readFileSync(tokensCss, 'utf8'));
313
-
314
- const outHtml = join(workRoot, 'composed.html');
315
- writeFileSync(outHtml, html);
316
- return outHtml;
317
- }
318
-
319
- function findSibling(dir, name) {
320
- if (!dir) return null;
321
- const p = join(dir, name);
322
- return existsSync(p) ? p : null;
323
- }
324
-
325
- function escapeHtml(s) {
326
- return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
327
- }
328
-
329
- // Minimal markdown — headings, paragraphs, lists, bold/italic, inline code, fenced code, images.
330
- function mdToHtml(md, baseDir) {
331
- let out = md.replace(/\r\n/g, '\n');
332
- out = out.replace(/```([a-z]*)\n([\s\S]*?)```/g, (_, lang, body) => `<pre><code class="lang-${escapeHtml(lang)}">${escapeHtml(body)}</code></pre>`);
333
- out = out.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src) => `<img alt="${escapeHtml(alt)}" src="${resolveImg(src, baseDir)}"/>`);
334
- out = out.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>')
335
- .replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>')
336
- .replace(/^####\s+(.+)$/gm, '<h4>$1</h4>')
337
- .replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
338
- .replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
339
- .replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
340
- out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>').replace(/`([^`]+)`/g, '<code>$1</code>');
341
- out = out.replace(/(?:^|\n)((?:[-*]\s+.+\n?)+)/g, (_, block) => `\n<ul>${block.trim().split(/\n/).map((l) => `<li>${l.replace(/^[-*]\s+/, '')}</li>`).join('')}</ul>\n`);
342
- out = out.split(/\n{2,}/).map((b) => /^<(h\d|ul|ol|pre|img|section|div)/.test(b.trim()) ? b : `<p>${b.trim()}</p>`).join('\n');
343
- return out;
344
- }
345
-
346
- function resolveImg(src, baseDir) {
347
- if (/^https?:|^data:/.test(src)) return src;
348
- const p = resolve(baseDir, src);
349
- if (!existsSync(p)) return src;
350
- return pathToFileURL(p).href;
351
- }
352
-
353
- // --- render ----------------------------------------------------------------
354
- async function render(htmlSource) {
355
- const puppeteer = await loadPuppeteer();
356
- const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox', '--font-render-hinting=none'] });
357
- try {
358
- const page = await browser.newPage();
359
- page.on('pageerror', (e) => log('pageerror:', e.message));
360
- const url = htmlSource.startsWith('http') ? htmlSource : pathToFileURL(htmlSource).href;
361
- log('loading', url);
362
- await page.goto(url, { waitUntil: 'networkidle0', timeout: 180_000 });
363
- await page.evaluateHandle('document.fonts.ready');
364
- await new Promise((r) => setTimeout(r, 1500));
365
- if (opts.printEmulate) await page.emulateMediaType('print');
366
-
367
- if (opts.autoFit) {
368
- await page.addStyleTag({ content: AUTO_FIT_CSS });
369
- const report = await page.evaluate(() => {
370
- const issues = [];
371
- const all = document.body.querySelectorAll('*');
372
- const pageWidthPx = document.documentElement.clientWidth;
373
- for (const el of all) {
374
- const r = el.getBoundingClientRect();
375
- if (r.width > pageWidthPx + 4) {
376
- issues.push({ tag: el.tagName, cls: el.className?.toString().slice(0, 60) || '', width: Math.round(r.width), pageWidth: pageWidthPx });
377
- if (issues.length >= 25) break;
378
- }
379
- }
380
- return issues;
381
- });
382
- if (report.length) {
383
- log(`auto-fit: ${report.length} overflow element(s) detected — corrective CSS applied`);
384
- for (const r of report.slice(0, 8)) log(` · ${r.tag}${r.cls ? '.' + r.cls : ''} width=${r.width}px (page=${r.pageWidth}px)`);
385
- } else {
386
- log('auto-fit: no overflow detected after corrective CSS');
387
- }
388
- await new Promise((r) => setTimeout(r, 400));
389
- }
390
-
391
- const outPath = resolve(opts.out || defaultOutPath());
392
- mkdirSync(dirname(outPath), { recursive: true });
393
-
394
- const pdfOpts = {
395
- path: outPath,
396
- format: opts.format,
397
- printBackground: true,
398
- preferCSSPageSize: true,
399
- displayHeaderFooter: false,
400
- scale: opts.scale && opts.scale !== 1 ? opts.scale : undefined,
401
- };
402
- if (opts.margin) {
403
- const m = opts.margin;
404
- pdfOpts.margin = { top: m, bottom: m, left: m, right: m };
405
- pdfOpts.preferCSSPageSize = false;
406
- } else if (!htmlSource.startsWith('http')) {
407
- const text = readFileSync(htmlSource, 'utf8');
408
- if (!/@page\b/.test(text)) {
409
- pdfOpts.margin = { top: '0.6in', bottom: '0.6in', left: '0.7in', right: '0.7in' };
410
- pdfOpts.preferCSSPageSize = false;
411
- }
412
- }
413
-
414
- await page.pdf(pdfOpts);
415
- return outPath;
416
- } finally {
417
- await browser.close();
418
- }
419
- }
420
-
421
- function defaultOutPath() {
422
- if (isUrl) return resolve('brochure.pdf');
423
- const abs = resolve(input);
424
- const base = basename(abs, extname(abs));
425
- return resolve(dirname(abs), `${base}.pdf`);
426
- }
427
-
428
- // --- main ------------------------------------------------------------------
429
- (async () => {
430
- const staged = stageInput();
431
- let htmlSource;
432
-
433
- if (staged.kind === 'url') {
434
- htmlSource = staged.url;
435
- } else if (staged.kind === 'html') {
436
- htmlSource = staged.file;
437
- } else if (staged.kind === 'md') {
438
- htmlSource = await composeFromFolder(null, staged.file);
439
- } else { // folder
440
- const picked = pickHtml(staged.stageDir);
441
- if (picked) {
442
- log('picked html:', relative(staged.stageDir, picked));
443
- htmlSource = picked;
444
- } else {
445
- log('no html found — composing from markdown');
446
- htmlSource = await composeFromFolder(staged.stageDir);
447
- }
448
- }
449
-
450
- const outPath = await render(htmlSource);
451
- const size = statSync(outPath).size;
452
- let pages = '?';
453
- try {
454
- const buf = readFileSync(outPath);
455
- const m = buf.toString('latin1').match(/\/Type\s*\/Page[^s]/g);
456
- if (m) pages = String(m.length);
457
- } catch {}
458
-
459
- console.log('');
460
- console.log(`PDF: ${outPath}`);
461
- console.log(`Pages: ${pages}`);
462
- console.log(`Size: ${human(size)}`);
463
- console.log(`Source: ${input} → ${htmlSource.startsWith('http') ? htmlSource : relative(process.cwd(), htmlSource)}`);
464
- })().catch((err) => { console.error('[brochure] error:', err.message); process.exit(1); });
1
+ #!/usr/bin/env node
2
+ /**
3
+ * rdc:brochure — zip/folder/html/url/markdown → PDF via Puppeteer.
4
+ * See skills/brochure/SKILL.md for the contract.
5
+ */
6
+ import { execSync, spawnSync } from 'node:child_process';
7
+ import { createHash } from 'node:crypto';
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, copyFileSync } from 'node:fs';
9
+ import { homedir, tmpdir } from 'node:os';
10
+ import { dirname, basename, extname, join, resolve, relative, sep } from 'node:path';
11
+ import { pathToFileURL, fileURLToPath } from 'node:url';
12
+ import { createRequire } from 'node:module';
13
+
14
+ const AUTO_FIT_CSS = `
15
+ /* rdc:brochure --auto-fit corrective stylesheet
16
+ Generic print-overflow safety net. Applied AFTER document stylesheets. */
17
+ @media print, screen {
18
+ html, body { overflow: visible !important; }
19
+ body { max-width: 100% !important; }
20
+ *, *::before, *::after { box-sizing: border-box; }
21
+
22
+ img, svg, video, canvas, iframe, object, embed {
23
+ max-width: 100% !important;
24
+ height: auto !important;
25
+ object-fit: contain;
26
+ }
27
+ figure, .figure, picture { break-inside: avoid; page-break-inside: avoid; max-width: 100%; }
28
+
29
+ table {
30
+ table-layout: fixed !important;
31
+ width: 100% !important;
32
+ max-width: 100% !important;
33
+ word-wrap: break-word;
34
+ overflow-wrap: anywhere;
35
+ border-collapse: collapse;
36
+ }
37
+ th, td { word-wrap: break-word; overflow-wrap: anywhere; max-width: 100%; }
38
+ thead { display: table-header-group; }
39
+ tr, td, th { break-inside: avoid; page-break-inside: avoid; }
40
+
41
+ pre, code, kbd, samp { white-space: pre-wrap !important; word-break: break-word; overflow-wrap: anywhere; max-width: 100%; }
42
+ pre { break-inside: avoid; page-break-inside: avoid; }
43
+
44
+ h1, h2, h3, h4, h5, h6 { break-after: avoid; page-break-after: avoid; }
45
+ h1 + *, h2 + *, h3 + *, h4 + * { break-before: avoid; }
46
+ p, li { orphans: 3; widows: 3; }
47
+
48
+ /* Generic wide-content sentinels */
49
+ .wide, .full-bleed, .panorama { max-width: 100% !important; }
50
+
51
+ /* Avoid blank-page artifacts from oversized flex/grid containers */
52
+ [style*="position: fixed"], [style*="position:fixed"] { position: static !important; }
53
+ }
54
+ `;
55
+
56
+ const HERE = dirname(fileURLToPath(import.meta.url));
57
+ const REPO_ROOT = resolve(HERE, '..');
58
+ const TEMPLATES_DIR = join(REPO_ROOT, 'scaffold', 'templates');
59
+
60
+ // --- args ------------------------------------------------------------------
61
+ const argv = process.argv.slice(2);
62
+ const opts = { template: 'studio-default', format: 'Letter', printEmulate: true, keepWorkdir: false, autoFit: false, scale: 1 };
63
+ let input;
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ if (a === '--out') opts.out = argv[++i];
67
+ else if (a === '--template') opts.template = argv[++i];
68
+ else if (a === '--format') opts.format = argv[++i];
69
+ else if (a === '--margin') opts.margin = argv[++i];
70
+ else if (a === '--no-print-emulate') opts.printEmulate = false;
71
+ else if (a === '--keep-workdir') opts.keepWorkdir = true;
72
+ else if (a === '--auto-fit') opts.autoFit = true;
73
+ else if (a === '--scale') opts.scale = parseFloat(argv[++i]);
74
+ else if (!input) input = a;
75
+ }
76
+ if (!input) {
77
+ console.error('usage: rdc-brochure.mjs <zip|folder|html|md|url> [--out path] [--template name] [--format Letter|A4]');
78
+ process.exit(2);
79
+ }
80
+
81
+ // --- helpers ---------------------------------------------------------------
82
+ const isUrl = /^https?:\/\//i.test(input);
83
+ const hash = createHash('sha1').update(input).digest('hex').slice(0, 10);
84
+ const workRoot = join(tmpdir(), 'rdc-brochure', hash);
85
+ mkdirSync(workRoot, { recursive: true });
86
+
87
+ const log = (...a) => console.log('[brochure]', ...a);
88
+
89
+ function human(n) {
90
+ const u = ['B', 'KB', 'MB', 'GB'];
91
+ let i = 0;
92
+ while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
93
+ return `${n.toFixed(1)} ${u[i]}`;
94
+ }
95
+
96
+ function walk(dir) {
97
+ const out = [];
98
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
99
+ const p = join(dir, e.name);
100
+ if (e.isDirectory()) out.push(...walk(p));
101
+ else out.push(p);
102
+ }
103
+ return out;
104
+ }
105
+
106
+ // --- ensure puppeteer ------------------------------------------------------
107
+ async function loadPuppeteer() {
108
+ try { return (await import('puppeteer')).default; } catch {}
109
+ // Try a local cache install.
110
+ const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
111
+ mkdirSync(cacheDir, { recursive: true });
112
+ if (!existsSync(join(cacheDir, 'package.json'))) {
113
+ writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
114
+ }
115
+ if (!existsSync(join(cacheDir, 'node_modules', 'puppeteer'))) {
116
+ log('installing puppeteer into', cacheDir);
117
+ execSync('npm install puppeteer --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
118
+ }
119
+ const req = createRequire(join(cacheDir, 'package.json'));
120
+ const mod = req('puppeteer');
121
+ return mod.default || mod;
122
+ }
123
+
124
+ // --- cross-platform unzip --------------------------------------------------
125
+ // Pure-Node first (adm-zip — works on every platform, no external binary).
126
+ // If the lib cannot be resolved or installed, fall back to a platform-native
127
+ // extractor: `unzip` on POSIX, PowerShell `Expand-Archive` on win32.
128
+ function loadAdmZip() {
129
+ try { return createRequire(import.meta.url)('adm-zip'); } catch {}
130
+ // Reuse the puppeteer on-demand cache dir for an isolated local install.
131
+ const cacheDir = join(homedir(), '.cache', 'rdc-brochure');
132
+ mkdirSync(cacheDir, { recursive: true });
133
+ if (!existsSync(join(cacheDir, 'package.json'))) {
134
+ writeFileSync(join(cacheDir, 'package.json'), JSON.stringify({ name: 'rdc-brochure-cache', private: true }, null, 2));
135
+ }
136
+ if (!existsSync(join(cacheDir, 'node_modules', 'adm-zip'))) {
137
+ try {
138
+ log('installing adm-zip into', cacheDir);
139
+ execSync('npm install adm-zip --no-audit --no-fund --loglevel=error', { cwd: cacheDir, stdio: 'inherit' });
140
+ } catch { return null; }
141
+ }
142
+ try { return createRequire(join(cacheDir, 'package.json'))('adm-zip'); } catch { return null; }
143
+ }
144
+
145
+ // Reject any archive member that resolves outside destDir (zip-slip / path
146
+ // traversal). Returns the validated absolute destination path. Throws on escape.
147
+ function safeJoinOrThrow(destDir, entryName) {
148
+ const root = resolve(destDir);
149
+ const dest = resolve(root, entryName);
150
+ if (dest !== root && !dest.startsWith(root + sep)) {
151
+ throw new Error(`zip-slip: entry "${entryName}" escapes destination directory`);
152
+ }
153
+ return dest;
154
+ }
155
+
156
+ function extractZip(zipPath, destDir) {
157
+ mkdirSync(destDir, { recursive: true });
158
+ const root = resolve(destDir);
159
+ const AdmZip = loadAdmZip();
160
+ if (AdmZip) {
161
+ const zip = new AdmZip(zipPath);
162
+ const entries = zip.getEntries();
163
+ // First pass: validate every entry resolves inside destDir. A brochure
164
+ // source zip must never contain `..` or absolute members — reject the whole
165
+ // archive rather than silently skipping (fail-closed).
166
+ for (const entry of entries) {
167
+ safeJoinOrThrow(root, entry.entryName);
168
+ }
169
+ // Second pass: extract validated entries individually. Do NOT use the
170
+ // blanket extractAllTo — adm-zip does not sanitize entry paths.
171
+ for (const entry of entries) {
172
+ if (entry.isDirectory) {
173
+ mkdirSync(safeJoinOrThrow(root, entry.entryName), { recursive: true });
174
+ continue;
175
+ }
176
+ const dest = safeJoinOrThrow(root, entry.entryName);
177
+ mkdirSync(dirname(dest), { recursive: true });
178
+ zip.extractEntryTo(entry, root, /* maintainEntryPath */ true, /* overwrite */ true);
179
+ }
180
+ return;
181
+ }
182
+ // Fallback: platform-native extractor. Validate members via a listing pass
183
+ // BEFORE extracting, since the bulk extract commands cannot apply per-entry
184
+ // guards. Reject any `..` segment or absolute/leading-slash member.
185
+ log('adm-zip unavailable — falling back to platform unzip');
186
+ assertNativeZipSafe(zipPath);
187
+ let r;
188
+ if (process.platform === 'win32') {
189
+ r = spawnSync('powershell', ['-NoProfile', '-Command',
190
+ `Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force`], { stdio: 'inherit' });
191
+ } else {
192
+ r = spawnSync('unzip', ['-o', '-q', zipPath, '-d', destDir], { stdio: 'inherit' });
193
+ }
194
+ if (!r || r.status !== 0) throw new Error('unzip failed (no pure-Node lib and platform extractor failed)');
195
+ }
196
+
197
+ // List archive members with a native tool and reject any traversal/absolute
198
+ // entry. Throws if a member is unsafe or the listing cannot be produced.
199
+ function assertNativeZipSafe(zipPath) {
200
+ let names = [];
201
+ if (process.platform === 'win32') {
202
+ const ps = spawnSync('powershell', ['-NoProfile', '-Command',
203
+ `Add-Type -AssemblyName System.IO.Compression.FileSystem; ` +
204
+ `[System.IO.Compression.ZipFile]::OpenRead('${zipPath}').Entries | ForEach-Object { $_.FullName }`],
205
+ { encoding: 'utf8' });
206
+ if (ps.status !== 0) throw new Error('cannot list zip members for traversal check (PowerShell)');
207
+ names = String(ps.stdout || '').split(/\r?\n/);
208
+ } else {
209
+ const zi = spawnSync('zipinfo', ['-1', zipPath], { encoding: 'utf8' });
210
+ if (zi.status === 0) {
211
+ names = String(zi.stdout || '').split(/\r?\n/);
212
+ } else {
213
+ const ul = spawnSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' });
214
+ if (ul.status !== 0) throw new Error('cannot list zip members for traversal check (unzip -Z1)');
215
+ names = String(ul.stdout || '').split(/\r?\n/);
216
+ }
217
+ }
218
+ for (const raw of names) {
219
+ const name = raw.trim();
220
+ if (!name) continue;
221
+ const norm = name.replace(/\\/g, '/');
222
+ if (norm.startsWith('/') || /^[A-Za-z]:/.test(norm) || norm.split('/').some((seg) => seg === '..')) {
223
+ throw new Error(`zip-slip: entry "${name}" escapes destination directory`);
224
+ }
225
+ }
226
+ }
227
+
228
+ // --- stage input -----------------------------------------------------------
229
+ function stageInput() {
230
+ const stageDir = join(workRoot, 'src');
231
+ mkdirSync(stageDir, { recursive: true });
232
+ if (isUrl) return { kind: 'url', url: input, stageDir };
233
+ const abs = resolve(input);
234
+ if (!existsSync(abs)) throw new Error(`not found: ${abs}`);
235
+ const st = statSync(abs);
236
+ if (st.isDirectory()) return { kind: 'folder', root: abs, stageDir: abs };
237
+ const ext = extname(abs).toLowerCase();
238
+ if (ext === '.zip') {
239
+ log('extracting zip to', stageDir);
240
+ extractZip(abs, stageDir);
241
+ return { kind: 'folder', root: stageDir, stageDir };
242
+ }
243
+ if (ext === '.html' || ext === '.htm') return { kind: 'html', file: abs, stageDir: dirname(abs) };
244
+ if (ext === '.md' || ext === '.markdown') return { kind: 'md', file: abs, stageDir: dirname(abs) };
245
+ throw new Error(`unsupported input: ${ext || '(no extension)'}`);
246
+ }
247
+
248
+ // --- pick HTML in render mode ----------------------------------------------
249
+ function pickHtml(rootDir) {
250
+ const htmls = walk(rootDir).filter((p) => /\.html?$/i.test(p));
251
+ if (!htmls.length) return null;
252
+ const scored = htmls.map((p) => {
253
+ const text = readFileSync(p, 'utf8');
254
+ const size = statSync(p).size;
255
+ let score = 0;
256
+ if (/@page\b/.test(text)) score += 1000;
257
+ if (/@media\s+print/i.test(text)) score += 500;
258
+ if (/-print\.html?$/i.test(p)) score += 300;
259
+ if (/brochure\.html?$/i.test(p)) score += 250;
260
+ if (/(^|[\\/])print\.html?$/i.test(p)) score += 250;
261
+ if (/standalone/i.test(basename(p))) score -= 50; // usually huge embedded duplicate
262
+ score += Math.min(size / 1024, 200); // size as tiebreaker, capped
263
+ return { p, score, size };
264
+ }).sort((a, b) => b.score - a.score);
265
+ return scored[0].p;
266
+ }
267
+
268
+ // --- compose mode ----------------------------------------------------------
269
+ function listTemplates() {
270
+ if (!existsSync(TEMPLATES_DIR)) return [];
271
+ return readdirSync(TEMPLATES_DIR)
272
+ .map((f) => /^brochure-(.+)\.html$/i.exec(f))
273
+ .filter(Boolean)
274
+ .map((m) => m[1])
275
+ .sort();
276
+ }
277
+
278
+ async function composeFromFolder(root, file) {
279
+ const tpl = join(TEMPLATES_DIR, `brochure-${opts.template}.html`);
280
+ if (!existsSync(tpl)) {
281
+ const available = listTemplates();
282
+ const list = available.length ? available.join(', ') : '(none found)';
283
+ throw new Error(`unknown template "${opts.template}". Available template(s): ${list}`);
284
+ }
285
+ let html = readFileSync(tpl, 'utf8');
286
+
287
+ let mdFiles = [];
288
+ if (file) mdFiles = [file];
289
+ else mdFiles = walk(root).filter((p) => /\.(md|markdown)$/i.test(p)).sort();
290
+
291
+ const title = (() => {
292
+ for (const p of mdFiles) {
293
+ const m = readFileSync(p, 'utf8').match(/^#\s+(.+)$/m);
294
+ if (m) return m[1].trim();
295
+ }
296
+ return basename(file || root);
297
+ })();
298
+
299
+ const sections = mdFiles.map((p) => {
300
+ const md = readFileSync(p, 'utf8');
301
+ // Only prepend the filename heading when the markdown has no leading ATX heading
302
+ // of its own. Avoids a redundant <h2>filename</h2> stacked above a "# Title".
303
+ const firstNonEmpty = md.replace(/\r\n/g, '\n').split('\n').find((l) => l.trim() !== '') || '';
304
+ const hasLeadingHeading = /^#{1,6}\s+\S/.test(firstNonEmpty.trim());
305
+ const heading = hasLeadingHeading ? '' : `<h2>${escapeHtml(basename(p, extname(p)))}</h2>`;
306
+ return `<section class="brochure-section">${heading}${mdToHtml(md, dirname(p))}</section>`;
307
+ }).join('\n');
308
+
309
+ html = html.replace(/\{\{TITLE\}\}/g, escapeHtml(title)).replace(/\{\{SECTIONS\}\}/g, sections);
310
+
311
+ const tokensCss = findSibling(root || dirname(file), 'tokens.css');
312
+ if (tokensCss) html = html.replace('/* TOKENS_INJECT */', readFileSync(tokensCss, 'utf8'));
313
+
314
+ const outHtml = join(workRoot, 'composed.html');
315
+ writeFileSync(outHtml, html);
316
+ return outHtml;
317
+ }
318
+
319
+ function findSibling(dir, name) {
320
+ if (!dir) return null;
321
+ const p = join(dir, name);
322
+ return existsSync(p) ? p : null;
323
+ }
324
+
325
+ function escapeHtml(s) {
326
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
327
+ }
328
+
329
+ // Minimal markdown — headings, paragraphs, lists, bold/italic, inline code, fenced code, images.
330
+ function mdToHtml(md, baseDir) {
331
+ let out = md.replace(/\r\n/g, '\n');
332
+ out = out.replace(/```([a-z]*)\n([\s\S]*?)```/g, (_, lang, body) => `<pre><code class="lang-${escapeHtml(lang)}">${escapeHtml(body)}</code></pre>`);
333
+ out = out.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_, alt, src) => `<img alt="${escapeHtml(alt)}" src="${resolveImg(src, baseDir)}"/>`);
334
+ out = out.replace(/^######\s+(.+)$/gm, '<h6>$1</h6>')
335
+ .replace(/^#####\s+(.+)$/gm, '<h5>$1</h5>')
336
+ .replace(/^####\s+(.+)$/gm, '<h4>$1</h4>')
337
+ .replace(/^###\s+(.+)$/gm, '<h3>$1</h3>')
338
+ .replace(/^##\s+(.+)$/gm, '<h2>$1</h2>')
339
+ .replace(/^#\s+(.+)$/gm, '<h1>$1</h1>');
340
+ out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/\*([^*]+)\*/g, '<em>$1</em>').replace(/`([^`]+)`/g, '<code>$1</code>');
341
+ out = out.replace(/(?:^|\n)((?:[-*]\s+.+\n?)+)/g, (_, block) => `\n<ul>${block.trim().split(/\n/).map((l) => `<li>${l.replace(/^[-*]\s+/, '')}</li>`).join('')}</ul>\n`);
342
+ out = out.split(/\n{2,}/).map((b) => /^<(h\d|ul|ol|pre|img|section|div)/.test(b.trim()) ? b : `<p>${b.trim()}</p>`).join('\n');
343
+ return out;
344
+ }
345
+
346
+ function resolveImg(src, baseDir) {
347
+ if (/^https?:|^data:/.test(src)) return src;
348
+ const p = resolve(baseDir, src);
349
+ if (!existsSync(p)) return src;
350
+ return pathToFileURL(p).href;
351
+ }
352
+
353
+ // --- render ----------------------------------------------------------------
354
+ async function render(htmlSource) {
355
+ const puppeteer = await loadPuppeteer();
356
+ const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox', '--disable-setuid-sandbox', '--font-render-hinting=none'] });
357
+ try {
358
+ const page = await browser.newPage();
359
+ page.on('pageerror', (e) => log('pageerror:', e.message));
360
+ const url = htmlSource.startsWith('http') ? htmlSource : pathToFileURL(htmlSource).href;
361
+ log('loading', url);
362
+ await page.goto(url, { waitUntil: 'networkidle0', timeout: 180_000 });
363
+ await page.evaluateHandle('document.fonts.ready');
364
+ await new Promise((r) => setTimeout(r, 1500));
365
+ if (opts.printEmulate) await page.emulateMediaType('print');
366
+
367
+ if (opts.autoFit) {
368
+ await page.addStyleTag({ content: AUTO_FIT_CSS });
369
+ const report = await page.evaluate(() => {
370
+ const issues = [];
371
+ const all = document.body.querySelectorAll('*');
372
+ const pageWidthPx = document.documentElement.clientWidth;
373
+ for (const el of all) {
374
+ const r = el.getBoundingClientRect();
375
+ if (r.width > pageWidthPx + 4) {
376
+ issues.push({ tag: el.tagName, cls: el.className?.toString().slice(0, 60) || '', width: Math.round(r.width), pageWidth: pageWidthPx });
377
+ if (issues.length >= 25) break;
378
+ }
379
+ }
380
+ return issues;
381
+ });
382
+ if (report.length) {
383
+ log(`auto-fit: ${report.length} overflow element(s) detected — corrective CSS applied`);
384
+ for (const r of report.slice(0, 8)) log(` · ${r.tag}${r.cls ? '.' + r.cls : ''} width=${r.width}px (page=${r.pageWidth}px)`);
385
+ } else {
386
+ log('auto-fit: no overflow detected after corrective CSS');
387
+ }
388
+ await new Promise((r) => setTimeout(r, 400));
389
+ }
390
+
391
+ const outPath = resolve(opts.out || defaultOutPath());
392
+ mkdirSync(dirname(outPath), { recursive: true });
393
+
394
+ const pdfOpts = {
395
+ path: outPath,
396
+ format: opts.format,
397
+ printBackground: true,
398
+ preferCSSPageSize: true,
399
+ displayHeaderFooter: false,
400
+ scale: opts.scale && opts.scale !== 1 ? opts.scale : undefined,
401
+ };
402
+ if (opts.margin) {
403
+ const m = opts.margin;
404
+ pdfOpts.margin = { top: m, bottom: m, left: m, right: m };
405
+ pdfOpts.preferCSSPageSize = false;
406
+ } else if (!htmlSource.startsWith('http')) {
407
+ const text = readFileSync(htmlSource, 'utf8');
408
+ if (!/@page\b/.test(text)) {
409
+ pdfOpts.margin = { top: '0.6in', bottom: '0.6in', left: '0.7in', right: '0.7in' };
410
+ pdfOpts.preferCSSPageSize = false;
411
+ }
412
+ }
413
+
414
+ await page.pdf(pdfOpts);
415
+ return outPath;
416
+ } finally {
417
+ await browser.close();
418
+ }
419
+ }
420
+
421
+ function defaultOutPath() {
422
+ if (isUrl) return resolve('brochure.pdf');
423
+ const abs = resolve(input);
424
+ const base = basename(abs, extname(abs));
425
+ return resolve(dirname(abs), `${base}.pdf`);
426
+ }
427
+
428
+ // --- main ------------------------------------------------------------------
429
+ (async () => {
430
+ const staged = stageInput();
431
+ let htmlSource;
432
+
433
+ if (staged.kind === 'url') {
434
+ htmlSource = staged.url;
435
+ } else if (staged.kind === 'html') {
436
+ htmlSource = staged.file;
437
+ } else if (staged.kind === 'md') {
438
+ htmlSource = await composeFromFolder(null, staged.file);
439
+ } else { // folder
440
+ const picked = pickHtml(staged.stageDir);
441
+ if (picked) {
442
+ log('picked html:', relative(staged.stageDir, picked));
443
+ htmlSource = picked;
444
+ } else {
445
+ log('no html found — composing from markdown');
446
+ htmlSource = await composeFromFolder(staged.stageDir);
447
+ }
448
+ }
449
+
450
+ const outPath = await render(htmlSource);
451
+ const size = statSync(outPath).size;
452
+ let pages = '?';
453
+ try {
454
+ const buf = readFileSync(outPath);
455
+ const m = buf.toString('latin1').match(/\/Type\s*\/Page[^s]/g);
456
+ if (m) pages = String(m.length);
457
+ } catch {}
458
+
459
+ console.log('');
460
+ console.log(`PDF: ${outPath}`);
461
+ console.log(`Pages: ${pages}`);
462
+ console.log(`Size: ${human(size)}`);
463
+ console.log(`Source: ${input} → ${htmlSource.startsWith('http') ? htmlSource : relative(process.cwd(), htmlSource)}`);
464
+ })().catch((err) => { console.error('[brochure] error:', err.message); process.exit(1); });