@frcloudsolutions/agent-skills 0.1.0 → 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/README.md +1 -1
- package/package.json +4 -2
- package/plugins/docs-generator/skills/docs-generator/SKILL.md +68 -0
- package/plugins/docs-generator/skills/docs-generator/assets/README.md +8 -0
- package/plugins/docs-generator/skills/docs-generator/assets/fonts/OFL.txt +93 -0
- package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Bold.ttf +0 -0
- package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-BoldItalic.ttf +0 -0
- package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Italic.ttf +0 -0
- package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Regular.ttf +0 -0
- package/plugins/docs-generator/skills/docs-generator/assets/paged.polyfill.min.js +4 -0
- package/plugins/docs-generator/skills/docs-generator/locales/en.json +14 -0
- package/plugins/docs-generator/skills/docs-generator/locales/es.json +14 -0
- package/plugins/docs-generator/skills/docs-generator/locales/pt-BR.json +14 -0
- package/plugins/docs-generator/skills/docs-generator/package-lock.json +1697 -0
- package/plugins/docs-generator/skills/docs-generator/package.json +28 -0
- package/plugins/docs-generator/skills/docs-generator/references/from-design-system.md +48 -0
- package/plugins/docs-generator/skills/docs-generator/references/source-format.md +96 -0
- package/plugins/docs-generator/skills/docs-generator/references/theme-format.md +77 -0
- package/plugins/docs-generator/skills/docs-generator/references/writing-guide.md +39 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/docs.mjs +226 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/docx.mjs +377 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/html.mjs +273 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/images.mjs +25 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/office.mjs +184 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/pdf.mjs +70 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/source.mjs +270 -0
- package/plugins/docs-generator/skills/docs-generator/scripts/lib/theme.mjs +219 -0
- package/plugins/docs-generator/skills/docs-generator/themes/clean-modern.json +36 -0
- package/plugins/docs-generator/skills/docs-generator/themes/docs-theme.schema.json +119 -0
- package/src/lib/validate.mjs +6 -3
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Reads the pixel size of PNG and JPEG files from their headers.
|
|
2
|
+
|
|
3
|
+
/** @returns {{width: number, height: number, format: "png"|"jpg"}|null} */
|
|
4
|
+
export function imageSize(buf) {
|
|
5
|
+
// PNG: signature, then the IHDR chunk with width and height
|
|
6
|
+
if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47 && buf.toString("ascii", 12, 16) === "IHDR") {
|
|
7
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20), format: "png" };
|
|
8
|
+
}
|
|
9
|
+
// JPEG: walk the segments until a start-of-frame marker
|
|
10
|
+
if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
|
|
11
|
+
let i = 2;
|
|
12
|
+
while (i + 9 < buf.length) {
|
|
13
|
+
if (buf[i] !== 0xff) {
|
|
14
|
+
i++;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const marker = buf[i + 1];
|
|
18
|
+
const len = buf.readUInt16BE(i + 2);
|
|
19
|
+
const isSOF = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
|
|
20
|
+
if (isSOF) return { width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5), format: "jpg" };
|
|
21
|
+
i += 2 + len;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Writes an Office theme (.thmx) and an Excel template (.xltx) from a docs-generator theme, as OOXML parts
|
|
2
|
+
// zipped with fflate. No content: colors, fonts, named cell styles and a default table style only.
|
|
3
|
+
import { strToU8, zipSync } from "fflate";
|
|
4
|
+
import { officeAccents, officeFont } from "./theme.mjs";
|
|
5
|
+
|
|
6
|
+
const XML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
|
|
7
|
+
const NS = {
|
|
8
|
+
a: "http://schemas.openxmlformats.org/drawingml/2006/main",
|
|
9
|
+
ct: "http://schemas.openxmlformats.org/package/2006/content-types",
|
|
10
|
+
rel: "http://schemas.openxmlformats.org/package/2006/relationships",
|
|
11
|
+
r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
|
|
12
|
+
main: "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
|
|
13
|
+
};
|
|
14
|
+
const REL = {
|
|
15
|
+
officeDocument: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
|
|
16
|
+
theme: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
|
|
17
|
+
worksheet: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
|
|
18
|
+
styles: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
|
|
19
|
+
};
|
|
20
|
+
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
21
|
+
const rgb = (c) => c.replace("#", "").toUpperCase();
|
|
22
|
+
const argb = (c) => "FF" + rgb(c);
|
|
23
|
+
|
|
24
|
+
/** Office color slots for a theme: dk1, lt1, dk2, lt2, accent1–6, hlink, folHlink. */
|
|
25
|
+
export function colorSlots(theme) {
|
|
26
|
+
const c = theme.colors;
|
|
27
|
+
const [a2, a3, a4, a5, a6] = officeAccents(theme);
|
|
28
|
+
return {
|
|
29
|
+
dk1: c.text, lt1: c.background, dk2: c.textMuted, lt2: c.tableHeader,
|
|
30
|
+
accent1: c.accent, accent2: a2, accent3: a3, accent4: a4, accent5: a5, accent6: a6,
|
|
31
|
+
hlink: c.accent, folHlink: c.textMuted,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function themeXml(theme) {
|
|
36
|
+
const slots = colorSlots(theme);
|
|
37
|
+
const clr = Object.entries(slots).map(([k, v]) => `<a:${k}><a:srgbClr val="${rgb(v)}"/></a:${k}>`).join("");
|
|
38
|
+
const font = (name) => `<a:latin typeface="${esc(name)}"/><a:ea typeface=""/><a:cs typeface=""/>`;
|
|
39
|
+
const solid = (mod = "") => `<a:solidFill><a:schemeClr val="phClr">${mod}</a:schemeClr></a:solidFill>`;
|
|
40
|
+
const ln = (w) => `<a:ln w="${w}" cap="flat" cmpd="sng" algn="ctr">${solid()}<a:prstDash val="solid"/><a:miter lim="800000"/></a:ln>`;
|
|
41
|
+
return (
|
|
42
|
+
XML +
|
|
43
|
+
`<a:theme xmlns:a="${NS.a}" name="${esc(theme.name)}"><a:themeElements>` +
|
|
44
|
+
`<a:clrScheme name="${esc(theme.name)}">${clr}</a:clrScheme>` +
|
|
45
|
+
`<a:fontScheme name="${esc(theme.name)}"><a:majorFont>${font(officeFont(theme.fonts.heading))}</a:majorFont><a:minorFont>${font(officeFont(theme.fonts.body))}</a:minorFont></a:fontScheme>` +
|
|
46
|
+
`<a:fmtScheme name="${esc(theme.name)}">` +
|
|
47
|
+
`<a:fillStyleLst>${solid()}${solid('<a:tint val="50000"/>')}${solid('<a:shade val="80000"/>')}</a:fillStyleLst>` +
|
|
48
|
+
`<a:lnStyleLst>${ln(6350)}${ln(12700)}${ln(19050)}</a:lnStyleLst>` +
|
|
49
|
+
`<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst>` +
|
|
50
|
+
`<a:bgFillStyleLst>${solid()}${solid('<a:tint val="95000"/>')}${solid('<a:shade val="80000"/>')}</a:bgFillStyleLst>` +
|
|
51
|
+
`</a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/></a:theme>`
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const rels = (list) =>
|
|
56
|
+
XML + `<Relationships xmlns="${NS.rel}">` + list.map(([id, type, target]) => `<Relationship Id="${id}" Type="${type}" Target="${target}"/>`).join("") + `</Relationships>`;
|
|
57
|
+
|
|
58
|
+
const zip = (files) => zipSync(Object.fromEntries(Object.entries(files).map(([k, v]) => [k, strToU8(v)])), { level: 6 });
|
|
59
|
+
|
|
60
|
+
/** Office theme file: applies colors and fonts in Excel, Word and PowerPoint (Design/Page Layout → Themes → Browse). */
|
|
61
|
+
export function buildThmx(theme) {
|
|
62
|
+
return zip({
|
|
63
|
+
"[Content_Types].xml":
|
|
64
|
+
XML +
|
|
65
|
+
`<Types xmlns="${NS.ct}"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>` +
|
|
66
|
+
`<Override PartName="/theme/theme/themeManager.xml" ContentType="application/vnd.openxmlformats-officedocument.themeManager+xml"/>` +
|
|
67
|
+
`<Override PartName="/theme/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/></Types>`,
|
|
68
|
+
"_rels/.rels": rels([["rId1", REL.officeDocument, "theme/theme/themeManager.xml"]]),
|
|
69
|
+
"theme/theme/themeManager.xml": XML + `<a:themeManager xmlns:a="${NS.a}"/>`,
|
|
70
|
+
"theme/theme/_rels/themeManager.xml.rels": rels([["rId1", REL.theme, "theme1.xml"]]),
|
|
71
|
+
"theme/theme/theme1.xml": themeXml(theme),
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Number formats and sheet name per language. */
|
|
76
|
+
const LOCALE = {
|
|
77
|
+
"pt-BR": { currency: '"R$" #,##0.00', date: "dd/mm/yyyy", sheet: "Planilha1" },
|
|
78
|
+
en: { currency: '"$"#,##0.00', date: "mm/dd/yyyy", sheet: "Sheet1" },
|
|
79
|
+
es: { currency: '#,##0.00 "€"', date: "dd/mm/yyyy", sheet: "Hoja1" },
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Named cell styles of the template, in order. builtinId maps a style to Excel's built-in one of the same role. */
|
|
83
|
+
export const CELL_STYLES = ["Normal", "Title", "Heading 1", "Heading 2", "Body", "Number", "Currency", "Percent", "Date", "Note"];
|
|
84
|
+
|
|
85
|
+
export function stylesXml(theme, lang = "pt-BR") {
|
|
86
|
+
const t = theme, c = t.colors, ty = t.type, loc = LOCALE[lang] ?? LOCALE["pt-BR"];
|
|
87
|
+
const body = esc(officeFont(t.fonts.body)), head = esc(officeFont(t.fonts.heading));
|
|
88
|
+
// Theme color indexes in SpreadsheetML: 0 lt1, 1 dk1, 2 lt2, 3 dk2, 4 accent1
|
|
89
|
+
const fonts = [
|
|
90
|
+
`<font><sz val="${ty.body}"/><color theme="1"/><name val="${body}"/><family val="2"/><scheme val="minor"/></font>`,
|
|
91
|
+
`<font><b/><sz val="${Math.round(ty.h1 * 0.9)}"/><color theme="4"/><name val="${head}"/><family val="2"/><scheme val="major"/></font>`,
|
|
92
|
+
`<font><b/><sz val="${ty.h2}"/><color theme="1"/><name val="${head}"/><family val="2"/><scheme val="major"/></font>`,
|
|
93
|
+
`<font><b/><sz val="${ty.h3}"/><color theme="1"/><name val="${head}"/><family val="2"/><scheme val="major"/></font>`,
|
|
94
|
+
`<font><sz val="${ty.small}"/><color theme="3"/><name val="${body}"/><family val="2"/><scheme val="minor"/></font>`,
|
|
95
|
+
];
|
|
96
|
+
const fills = [
|
|
97
|
+
`<fill><patternFill patternType="none"/></fill>`,
|
|
98
|
+
`<fill><patternFill patternType="gray125"/></fill>`,
|
|
99
|
+
`<fill><patternFill patternType="solid"><fgColor theme="2"/><bgColor indexed="64"/></patternFill></fill>`,
|
|
100
|
+
];
|
|
101
|
+
const borders = [
|
|
102
|
+
`<border><left/><right/><top/><bottom/><diagonal/></border>`,
|
|
103
|
+
`<border><left/><right/><top/><bottom style="medium"><color theme="4"/></bottom><diagonal/></border>`,
|
|
104
|
+
`<border><left/><right/><top/><bottom style="thin"><color rgb="${argb(c.border)}"/></bottom><diagonal/></border>`,
|
|
105
|
+
];
|
|
106
|
+
const numFmts = [
|
|
107
|
+
[164, "#,##0.00"],
|
|
108
|
+
[165, loc.currency],
|
|
109
|
+
[166, loc.date],
|
|
110
|
+
];
|
|
111
|
+
// [name, builtinId, numFmtId, fontId, fillId, borderId, alignment]
|
|
112
|
+
const defs = [
|
|
113
|
+
["Normal", 0, 0, 0, 0, 0],
|
|
114
|
+
["Title", 15, 0, 1, 0, 0],
|
|
115
|
+
["Heading 1", 16, 0, 2, 0, 1],
|
|
116
|
+
["Heading 2", 17, 0, 3, 0, 2],
|
|
117
|
+
["Body", null, 0, 0, 0, 0, '<alignment vertical="top" wrapText="1"/>'],
|
|
118
|
+
["Number", null, 164, 0, 0, 0],
|
|
119
|
+
["Currency", 4, 165, 0, 0, 0],
|
|
120
|
+
["Percent", 5, 10, 0, 0, 0],
|
|
121
|
+
["Date", null, 166, 0, 0, 0, '<alignment horizontal="left"/>'],
|
|
122
|
+
["Note", 10, 0, 4, 2, 0, '<alignment vertical="top" wrapText="1"/>'],
|
|
123
|
+
];
|
|
124
|
+
const xf = ([, , numFmt, font, fill, border, align], xfId) => {
|
|
125
|
+
const apply = `applyNumberFormat="${numFmt ? 1 : 0}" applyFont="1" applyFill="${fill ? 1 : 0}" applyBorder="${border ? 1 : 0}" applyAlignment="${align ? 1 : 0}"`;
|
|
126
|
+
const attrs = `numFmtId="${numFmt}" fontId="${font}" fillId="${fill}" borderId="${border}"${xfId === undefined ? "" : ` xfId="${xfId}"`} ${apply}`;
|
|
127
|
+
return align ? `<xf ${attrs}>${align}</xf>` : `<xf ${attrs}/>`;
|
|
128
|
+
};
|
|
129
|
+
const dxfs = [
|
|
130
|
+
// wholeTable: thin horizontal rules only
|
|
131
|
+
`<dxf><border><left/><right/><top/><bottom style="thin"><color rgb="${argb(c.border)}"/></bottom><vertical/><horizontal style="thin"><color rgb="${argb(c.border)}"/></horizontal></border></dxf>`,
|
|
132
|
+
// headerRow: bold, header background, rule under it
|
|
133
|
+
`<dxf><font><b/><color theme="1"/></font><fill><patternFill patternType="solid"><bgColor rgb="${argb(c.tableHeader)}"/></patternFill></fill><border><bottom style="thin"><color theme="1"/></bottom></border></dxf>`,
|
|
134
|
+
];
|
|
135
|
+
const tableStyle = esc(t.name);
|
|
136
|
+
return (
|
|
137
|
+
XML +
|
|
138
|
+
`<styleSheet xmlns="${NS.main}">` +
|
|
139
|
+
`<numFmts count="${numFmts.length}">${numFmts.map(([id, code]) => `<numFmt numFmtId="${id}" formatCode="${esc(code)}"/>`).join("")}</numFmts>` +
|
|
140
|
+
`<fonts count="${fonts.length}">${fonts.join("")}</fonts>` +
|
|
141
|
+
`<fills count="${fills.length}">${fills.join("")}</fills>` +
|
|
142
|
+
`<borders count="${borders.length}">${borders.join("")}</borders>` +
|
|
143
|
+
`<cellStyleXfs count="${defs.length}">${defs.map((d) => xf(d)).join("")}</cellStyleXfs>` +
|
|
144
|
+
`<cellXfs count="${defs.length}">${defs.map((d, i) => xf(d, i)).join("")}</cellXfs>` +
|
|
145
|
+
`<cellStyles count="${defs.length}">${defs
|
|
146
|
+
.map(([name, builtin], i) => `<cellStyle name="${esc(name)}" xfId="${i}"${builtin === null ? "" : ` builtinId="${builtin}"`}/>`)
|
|
147
|
+
.join("")}</cellStyles>` +
|
|
148
|
+
`<dxfs count="${dxfs.length}">${dxfs.join("")}</dxfs>` +
|
|
149
|
+
`<tableStyles count="1" defaultTableStyle="${tableStyle}" defaultPivotStyle="PivotStyleLight16">` +
|
|
150
|
+
`<tableStyle name="${tableStyle}" pivot="0" count="2"><tableStyleElement type="wholeTable" dxfId="0"/><tableStyleElement type="headerRow" dxfId="1"/></tableStyle>` +
|
|
151
|
+
`</tableStyles></styleSheet>`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Excel template: the theme, the named cell styles, a default table style and one empty sheet. */
|
|
156
|
+
export function buildXltx(theme, lang = "pt-BR") {
|
|
157
|
+
const loc = LOCALE[lang] ?? LOCALE["pt-BR"];
|
|
158
|
+
const rowHeight = Math.round(theme.type.body * 1.36 * 4) / 4;
|
|
159
|
+
return zip({
|
|
160
|
+
"[Content_Types].xml":
|
|
161
|
+
XML +
|
|
162
|
+
`<Types xmlns="${NS.ct}"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/>` +
|
|
163
|
+
`<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"/>` +
|
|
164
|
+
`<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>` +
|
|
165
|
+
`<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>` +
|
|
166
|
+
`<Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/></Types>`,
|
|
167
|
+
"_rels/.rels": rels([["rId1", REL.officeDocument, "xl/workbook.xml"]]),
|
|
168
|
+
"xl/workbook.xml":
|
|
169
|
+
XML +
|
|
170
|
+
`<workbook xmlns="${NS.main}" xmlns:r="${NS.r}"><bookViews><workbookView/></bookViews>` +
|
|
171
|
+
`<sheets><sheet name="${loc.sheet}" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
|
172
|
+
"xl/_rels/workbook.xml.rels": rels([
|
|
173
|
+
["rId1", REL.worksheet, "worksheets/sheet1.xml"],
|
|
174
|
+
["rId2", REL.styles, "styles.xml"],
|
|
175
|
+
["rId3", REL.theme, "theme/theme1.xml"],
|
|
176
|
+
]),
|
|
177
|
+
"xl/worksheets/sheet1.xml":
|
|
178
|
+
XML +
|
|
179
|
+
`<worksheet xmlns="${NS.main}"><sheetViews><sheetView workbookViewId="0"/></sheetViews>` +
|
|
180
|
+
`<sheetFormatPr defaultRowHeight="${rowHeight}" customHeight="1"/><sheetData/></worksheet>`,
|
|
181
|
+
"xl/styles.xml": stylesXml(theme, lang),
|
|
182
|
+
"xl/theme/theme1.xml": themeXml(theme),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Prints the HTML rendering to PDF with a Chromium-based browser and Paged.js.
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { renderHtml } from "./html.mjs";
|
|
7
|
+
import { SKILL_ROOT } from "./theme.mjs";
|
|
8
|
+
|
|
9
|
+
const PAGED = join(SKILL_ROOT, "assets", "paged.polyfill.min.js");
|
|
10
|
+
|
|
11
|
+
export class BrowserNotFound extends Error {}
|
|
12
|
+
|
|
13
|
+
export const BROWSER_HINT =
|
|
14
|
+
"No Chrome, Edge or Chromium was found to print the PDF. Install Chrome, or run `npx playwright install chromium`, " +
|
|
15
|
+
"or set DOCS_GENERATOR_CHROMIUM to a browser executable. DOCX output (--format docx) does not need a browser.";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Uses DOCS_GENERATOR_CHROMIUM when it is set (and only it); otherwise tries installed Chrome, installed Edge,
|
|
19
|
+
* then Playwright's own Chromium.
|
|
20
|
+
*/
|
|
21
|
+
export async function launchBrowser() {
|
|
22
|
+
const { chromium } = await import("playwright-core");
|
|
23
|
+
const explicit = process.env.DOCS_GENERATOR_CHROMIUM;
|
|
24
|
+
const attempts = explicit ? [{ executablePath: explicit }] : [{ channel: "chrome" }, { channel: "msedge" }, {}];
|
|
25
|
+
for (const opts of attempts) {
|
|
26
|
+
try {
|
|
27
|
+
return await chromium.launch({ headless: true, ...opts });
|
|
28
|
+
} catch {
|
|
29
|
+
// try the next one
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
throw new BrowserNotFound(explicit ? `DOCS_GENERATOR_CHROMIUM=${explicit} could not be started. ${BROWSER_HINT}` : BROWSER_HINT);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Writes `outFile` and returns the number of pages. */
|
|
36
|
+
export async function renderPdf(model, theme, outFile, { browser, previewDir } = {}) {
|
|
37
|
+
const html = renderHtml(model, theme, { pagedScript: PAGED });
|
|
38
|
+
const dir = mkdtempSync(join(tmpdir(), "docs-generator-"));
|
|
39
|
+
const htmlFile = join(dir, "document.html");
|
|
40
|
+
writeFileSync(htmlFile, html);
|
|
41
|
+
const own = !browser;
|
|
42
|
+
browser ??= await launchBrowser();
|
|
43
|
+
try {
|
|
44
|
+
const page = await browser.newPage();
|
|
45
|
+
const pageErrors = [];
|
|
46
|
+
page.on("pageerror", (e) => pageErrors.push(e.message));
|
|
47
|
+
await page.goto(pathToFileURL(htmlFile).href, { waitUntil: "load" });
|
|
48
|
+
try {
|
|
49
|
+
await page.waitForFunction(() => window.__pagedDone === true, null, { timeout: 120_000 });
|
|
50
|
+
} catch {
|
|
51
|
+
throw new Error(`pagination did not finish${pageErrors.length ? `: ${pageErrors.join("; ")}` : ""}`);
|
|
52
|
+
}
|
|
53
|
+
await page.evaluate(() => document.fonts.ready);
|
|
54
|
+
const pages = await page.evaluate(() => document.querySelectorAll(".pagedjs_page").length);
|
|
55
|
+
if (previewDir) {
|
|
56
|
+
// One PNG per page, from the same paginated layout that is printed, for review by eye.
|
|
57
|
+
await page.emulateMedia({ media: "screen" });
|
|
58
|
+
const handles = await page.$$(".pagedjs_page");
|
|
59
|
+
for (let i = 0; i < handles.length; i++)
|
|
60
|
+
await handles[i].screenshot({ path: join(previewDir, `page-${String(i + 1).padStart(2, "0")}.png`) });
|
|
61
|
+
await page.emulateMedia({ media: "print" });
|
|
62
|
+
}
|
|
63
|
+
await page.pdf({ path: outFile, preferCSSPageSize: true, printBackground: true, tagged: true, outline: true });
|
|
64
|
+
await page.close();
|
|
65
|
+
return { pages };
|
|
66
|
+
} finally {
|
|
67
|
+
if (own) await browser.close();
|
|
68
|
+
rmSync(dir, { recursive: true, force: true });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Reads a source document (Markdown + YAML frontmatter), validates it and builds the document model
|
|
2
|
+
// that both renderers use.
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, extname, join, relative, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { parse as parseYaml } from "yaml";
|
|
7
|
+
import { unified } from "unified";
|
|
8
|
+
import remarkParse from "remark-parse";
|
|
9
|
+
import remarkGfm from "remark-gfm";
|
|
10
|
+
import { imageSize } from "./images.mjs";
|
|
11
|
+
|
|
12
|
+
export const LANGS = ["pt-BR", "en", "es"];
|
|
13
|
+
const LOCALES_DIR = fileURLToPath(new URL("../../locales", import.meta.url));
|
|
14
|
+
|
|
15
|
+
/** Markdown node types the renderers support. Anything else is reported by `check`. */
|
|
16
|
+
const SUPPORTED = new Set([
|
|
17
|
+
"root", "paragraph", "text", "heading", "strong", "emphasis", "link", "list", "listItem",
|
|
18
|
+
"table", "tableRow", "tableCell", "blockquote", "code", "inlineCode", "image", "break",
|
|
19
|
+
]);
|
|
20
|
+
const NODE_HINTS = {
|
|
21
|
+
html: "raw HTML is not supported; use Markdown",
|
|
22
|
+
footnoteReference: "footnotes are not supported; list references under `sources`",
|
|
23
|
+
footnoteDefinition: "footnotes are not supported; list references under `sources`",
|
|
24
|
+
linkReference: "reference-style links are not supported; use inline links [text](url)",
|
|
25
|
+
imageReference: "reference-style images are not supported; use ",
|
|
26
|
+
definition: "reference definitions are not supported; use inline links",
|
|
27
|
+
thematicBreak: "horizontal rules are not supported; use a heading to start a new part",
|
|
28
|
+
delete: "strikethrough is not supported",
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
32
|
+
const VAGUE_CHANGE = /^(document |documento )?(updated?|update|atualizado|atualização|actualizado|actualización|changes?|alterações|cambios)\.?$/i;
|
|
33
|
+
|
|
34
|
+
export function labels(lang) {
|
|
35
|
+
return JSON.parse(readFileSync(join(LOCALES_DIR, `${lang}.json`), "utf8"));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function formatDate(iso, lang) {
|
|
39
|
+
return new Intl.DateTimeFormat(lang, { dateStyle: "long", timeZone: "UTC" }).format(new Date(`${iso}T00:00:00Z`));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const parser = unified().use(remarkParse).use(remarkGfm);
|
|
43
|
+
|
|
44
|
+
export function textOf(node) {
|
|
45
|
+
if (!node) return "";
|
|
46
|
+
if (node.type === "text" || node.type === "inlineCode") return node.value;
|
|
47
|
+
if (node.type === "image") return node.alt ?? "";
|
|
48
|
+
if (node.type === "break") return " ";
|
|
49
|
+
return (node.children ?? []).map(textOf).join("");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function slugify(text) {
|
|
53
|
+
return (
|
|
54
|
+
text
|
|
55
|
+
.normalize("NFD")
|
|
56
|
+
.replace(/[̀-ͯ]/g, "")
|
|
57
|
+
.toLowerCase()
|
|
58
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
59
|
+
.replace(/^-|-$/g, "") || "section"
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function splitFrontmatter(text) {
|
|
64
|
+
const m = text.match(/^?---\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/);
|
|
65
|
+
if (!m) return null;
|
|
66
|
+
return { yaml: m[1], body: text.slice(m[0].length), bodyLine: m[0].split("\n").length };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const isValidDate = (s) => ISO_DATE.test(s) && !Number.isNaN(new Date(`${s}T00:00:00Z`).getTime()) && new Date(`${s}T00:00:00Z`).toISOString().startsWith(s);
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @returns {{ model: object|null, errors: {where: string, message: string}[], warnings: {where: string, message: string}[] }}
|
|
73
|
+
*/
|
|
74
|
+
export function loadSource(sourcePath) {
|
|
75
|
+
const errors = [];
|
|
76
|
+
const warnings = [];
|
|
77
|
+
const err = (where, message) => errors.push({ where, message });
|
|
78
|
+
const warn = (where, message) => warnings.push({ where, message });
|
|
79
|
+
const file = resolve(sourcePath);
|
|
80
|
+
const baseDir = dirname(file);
|
|
81
|
+
const rel = (p) => relative(baseDir, p) || p;
|
|
82
|
+
|
|
83
|
+
if (!existsSync(file)) return { model: null, errors: [{ where: sourcePath, message: "file not found" }], warnings };
|
|
84
|
+
const fm = splitFrontmatter(readFileSync(file, "utf8"));
|
|
85
|
+
if (!fm) return { model: null, errors: [{ where: "frontmatter", message: "the file must start with YAML frontmatter between --- lines" }], warnings };
|
|
86
|
+
|
|
87
|
+
let meta;
|
|
88
|
+
try {
|
|
89
|
+
// "failsafe" keeps every scalar as a string, so `version: 1.0` stays "1.0" and dates are not converted.
|
|
90
|
+
meta = parseYaml(fm.yaml, { schema: "failsafe" }) ?? {};
|
|
91
|
+
} catch (e) {
|
|
92
|
+
return { model: null, errors: [{ where: "frontmatter", message: `invalid YAML: ${e.message.split("\n")[0]}` }], warnings };
|
|
93
|
+
}
|
|
94
|
+
if (typeof meta !== "object" || Array.isArray(meta)) return { model: null, errors: [{ where: "frontmatter", message: "must be a set of key: value fields" }], warnings };
|
|
95
|
+
|
|
96
|
+
const str = (key, required) => {
|
|
97
|
+
const v = meta[key];
|
|
98
|
+
if (v === undefined || v === null || v === "") {
|
|
99
|
+
if (required) err(key, "is required");
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
if (typeof v !== "string") {
|
|
103
|
+
err(key, "must be text");
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
return v.trim();
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const known = new Set(["title", "subtitle", "author", "date", "version", "lang", "summary", "sources", "annexes", "changes"]);
|
|
110
|
+
for (const k of Object.keys(meta)) if (!known.has(k)) warn(k, "unknown field, ignored");
|
|
111
|
+
|
|
112
|
+
const title = str("title", true);
|
|
113
|
+
const subtitle = str("subtitle", false);
|
|
114
|
+
const version = str("version", true);
|
|
115
|
+
const date = str("date", true);
|
|
116
|
+
if (date && !isValidDate(date)) err("date", `"${date}" must be an ISO date like 2026-11-20`);
|
|
117
|
+
const lang = str("lang", false) ?? "pt-BR";
|
|
118
|
+
if (!LANGS.includes(lang)) err("lang", `"${lang}" is not supported; use one of: ${LANGS.join(", ")}`);
|
|
119
|
+
|
|
120
|
+
let authors = [];
|
|
121
|
+
if (meta.author === undefined || meta.author === "") err("author", "is required");
|
|
122
|
+
else if (typeof meta.author === "string") authors = [meta.author.trim()];
|
|
123
|
+
else if (Array.isArray(meta.author) && meta.author.every((a) => typeof a === "string" && a.trim())) authors = meta.author.map((a) => a.trim());
|
|
124
|
+
else err("author", "must be a name or a list of names");
|
|
125
|
+
|
|
126
|
+
// Markdown blocks ------------------------------------------------------------------------
|
|
127
|
+
const usedIds = new Set(["cover", "toc", "summary", "sources", "changes", "back-cover"]);
|
|
128
|
+
const uniqueId = (text) => {
|
|
129
|
+
const base = `s-${slugify(text)}`;
|
|
130
|
+
let id = base, n = 2;
|
|
131
|
+
while (usedIds.has(id)) id = `${base}-${n++}`;
|
|
132
|
+
usedIds.add(id);
|
|
133
|
+
return id;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Parses Markdown, checks supported nodes, heading depth and images.
|
|
138
|
+
* @param where label for errors; lineOffset converts node lines to file lines
|
|
139
|
+
*/
|
|
140
|
+
const parseBlocks = (markdown, { where, fileLabel, lineOffset = 0, maxDepth, depthShift = 0, allowHeadings = true, imageBase }) => {
|
|
141
|
+
const tree = parser.runSync(parser.parse(markdown));
|
|
142
|
+
const at = (node) => `${fileLabel}:${(node.position?.start.line ?? 1) + lineOffset}`;
|
|
143
|
+
const visit = (node) => {
|
|
144
|
+
if (!SUPPORTED.has(node.type)) {
|
|
145
|
+
err(at(node), NODE_HINTS[node.type] ?? `"${node.type}" is not supported`);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (node.type === "heading") {
|
|
149
|
+
if (!allowHeadings) err(at(node), `headings are not allowed in ${where}`);
|
|
150
|
+
else if (node.depth > maxDepth)
|
|
151
|
+
err(at(node), `heading level ${"#".repeat(node.depth)} is too deep: documents use at most 3 heading levels` +
|
|
152
|
+
(depthShift ? ` (an annex allows # and ##, because its title is the first level)` : ""));
|
|
153
|
+
node.depth += depthShift;
|
|
154
|
+
node.id = uniqueId(textOf(node));
|
|
155
|
+
}
|
|
156
|
+
if (node.type === "image") {
|
|
157
|
+
const path = resolve(imageBase, decodeURI(node.url));
|
|
158
|
+
if (/^[a-z]+:\/\//i.test(node.url)) err(at(node), `images must be local files, not URLs: ${node.url}`);
|
|
159
|
+
else if (!existsSync(path)) err(at(node), `image not found: ${rel(path)}`);
|
|
160
|
+
else if (!/\.(png|jpe?g)$/i.test(path)) err(at(node), `image must be PNG or JPEG: ${rel(path)}`);
|
|
161
|
+
else {
|
|
162
|
+
const size = imageSize(readFileSync(path));
|
|
163
|
+
if (!size) err(at(node), `could not read image size: ${rel(path)}`);
|
|
164
|
+
else Object.assign(node, { path, width: size.width, height: size.height, format: size.format });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
for (const child of node.children ?? []) visit(child);
|
|
168
|
+
};
|
|
169
|
+
visit(tree);
|
|
170
|
+
return tree.children;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const sourceName = relative(process.cwd(), file) || file;
|
|
174
|
+
const body = parseBlocks(fm.body, { where: "the body", fileLabel: sourceName, lineOffset: fm.bodyLine - 1, maxDepth: 3, imageBase: baseDir });
|
|
175
|
+
if (!body.length) err(sourceName, "the document body is empty");
|
|
176
|
+
|
|
177
|
+
let summary = [];
|
|
178
|
+
const summaryText = str("summary", true);
|
|
179
|
+
if (summaryText) summary = parseBlocks(summaryText, { where: "the summary", fileLabel: "summary", allowHeadings: false, maxDepth: 0, imageBase: baseDir });
|
|
180
|
+
|
|
181
|
+
// Sources --------------------------------------------------------------------------------
|
|
182
|
+
const sources = [];
|
|
183
|
+
if (meta.sources !== undefined && meta.sources !== "") {
|
|
184
|
+
if (!Array.isArray(meta.sources)) err("sources", "must be a list");
|
|
185
|
+
else
|
|
186
|
+
meta.sources.forEach((s, i) => {
|
|
187
|
+
const w = `sources[${i}]`;
|
|
188
|
+
if (typeof s !== "object" || Array.isArray(s) || !s) return err(w, "must have at least a title");
|
|
189
|
+
if (!s.title) err(`${w}.title`, "is required");
|
|
190
|
+
if (s.url && !/^https?:\/\//.test(s.url)) err(`${w}.url`, "must start with http:// or https://");
|
|
191
|
+
for (const k of ["date", "accessed"]) if (s[k] && !isValidDate(s[k])) err(`${w}.${k}`, `"${s[k]}" must be an ISO date like 2026-11-20`);
|
|
192
|
+
sources.push({ title: s.title, url: s.url, author: s.author, date: s.date, accessed: s.accessed });
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const sourceLang = LANGS.includes(meta.lang) ? meta.lang : "pt-BR";
|
|
196
|
+
for (const s of sources) {
|
|
197
|
+
if (s.date && isValidDate(s.date)) s.dateText = formatDate(s.date, sourceLang);
|
|
198
|
+
if (s.accessed && isValidDate(s.accessed)) s.accessedText = formatDate(s.accessed, sourceLang);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Annexes --------------------------------------------------------------------------------
|
|
202
|
+
const annexes = [];
|
|
203
|
+
if (meta.annexes !== undefined && meta.annexes !== "") {
|
|
204
|
+
if (!Array.isArray(meta.annexes)) err("annexes", "must be a list");
|
|
205
|
+
else
|
|
206
|
+
meta.annexes.forEach((a, i) => {
|
|
207
|
+
const w = `annexes[${i}]`;
|
|
208
|
+
if (typeof a !== "object" || Array.isArray(a) || !a) return err(w, "must have a title and a file");
|
|
209
|
+
if (!a.title) err(`${w}.title`, "is required");
|
|
210
|
+
if (!a.file) return err(`${w}.file`, "is required");
|
|
211
|
+
const path = resolve(baseDir, a.file);
|
|
212
|
+
if (!existsSync(path)) return err(`${w}.file`, `annex file not found: ${a.file}`);
|
|
213
|
+
if (extname(path).toLowerCase() !== ".md") return err(`${w}.file`, `annex must be a Markdown (.md) file: ${a.file}`);
|
|
214
|
+
let text = readFileSync(path, "utf8");
|
|
215
|
+
let offset = 0;
|
|
216
|
+
const afm = splitFrontmatter(text);
|
|
217
|
+
if (afm) {
|
|
218
|
+
text = afm.body;
|
|
219
|
+
offset = afm.bodyLine - 1;
|
|
220
|
+
}
|
|
221
|
+
const letter = String.fromCharCode(65 + i);
|
|
222
|
+
const blocks = parseBlocks(text, {
|
|
223
|
+
where: `annex ${letter}`, fileLabel: rel(path), lineOffset: offset, maxDepth: 2, depthShift: 1, imageBase: dirname(path),
|
|
224
|
+
});
|
|
225
|
+
annexes.push({ letter, title: a.title, id: `annex-${letter.toLowerCase()}`, blocks });
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Change log -----------------------------------------------------------------------------
|
|
230
|
+
const changes = [];
|
|
231
|
+
if (meta.changes === undefined || meta.changes === "") err("changes", "is required: list at least one change with version, date and description");
|
|
232
|
+
else if (!Array.isArray(meta.changes) || !meta.changes.length) err("changes", "must be a list with at least one entry");
|
|
233
|
+
else
|
|
234
|
+
meta.changes.forEach((c, i) => {
|
|
235
|
+
const w = `changes[${i}]`;
|
|
236
|
+
if (typeof c !== "object" || Array.isArray(c) || !c) return err(w, "must have version, date and description");
|
|
237
|
+
for (const k of ["version", "date", "description"]) if (!c[k]) err(`${w}.${k}`, "is required");
|
|
238
|
+
if (c.date && !isValidDate(c.date)) err(`${w}.date`, `"${c.date}" must be an ISO date like 2026-11-20`);
|
|
239
|
+
if (c.description && (VAGUE_CHANGE.test(c.description.trim()) || c.description.trim().length < 12))
|
|
240
|
+
warn(`${w}.description`, `"${c.description}" is vague: say what changed and where, for example "Added section 3.2 on data retention"`);
|
|
241
|
+
changes.push({ version: c.version, date: c.date, author: c.author, description: c.description, order: i });
|
|
242
|
+
});
|
|
243
|
+
changes.sort((a, b) => (b.date ?? "").localeCompare(a.date ?? "") || b.order - a.order);
|
|
244
|
+
|
|
245
|
+
if (errors.length) return { model: null, errors, warnings };
|
|
246
|
+
|
|
247
|
+
const L = labels(lang);
|
|
248
|
+
const toc = [{ id: "summary", text: L.summary, level: 1 }];
|
|
249
|
+
for (const b of body) if (b.type === "heading" && b.depth <= 2) toc.push({ id: b.id, text: textOf(b), level: b.depth });
|
|
250
|
+
if (sources.length) toc.push({ id: "sources", text: L.sources, level: 1 });
|
|
251
|
+
for (const a of annexes) toc.push({ id: a.id, text: `${L.annex} ${a.letter} — ${a.title}`, level: 1 });
|
|
252
|
+
toc.push({ id: "changes", text: L.changes, level: 1 });
|
|
253
|
+
|
|
254
|
+
return {
|
|
255
|
+
model: {
|
|
256
|
+
file,
|
|
257
|
+
baseDir,
|
|
258
|
+
meta: { title, subtitle, authors, date, dateText: formatDate(date, lang), version, lang },
|
|
259
|
+
labels: L,
|
|
260
|
+
summary,
|
|
261
|
+
body,
|
|
262
|
+
sources,
|
|
263
|
+
annexes,
|
|
264
|
+
changes: changes.map(({ order, ...c }) => ({ ...c, dateText: formatDate(c.date, lang) })),
|
|
265
|
+
toc,
|
|
266
|
+
},
|
|
267
|
+
errors,
|
|
268
|
+
warnings,
|
|
269
|
+
};
|
|
270
|
+
}
|