-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
210 lines (180 loc) · 6.22 KB
/
cli.js
File metadata and controls
210 lines (180 loc) · 6.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { renderDocument, registerPlugin, plugins } = require("./index");
const EXAMPLES_THEMES_DIR = path.join(__dirname, "examples", "themes");
function parseArgs(argv) {
const out = { source: null, theme: null, output: null, help: false, fonts: false, shapes: false };
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--source" || arg === "-s") {
out.source = argv[++i];
} else if (arg === "--theme" || arg === "-t") {
out.theme = argv[++i];
} else if (arg === "--output" || arg === "-o") {
out.output = argv[++i];
} else if (arg === "--help" || arg === "-h") {
out.help = true;
} else if (arg === "--fonts") {
out.fonts = true;
} else if (arg === "--shapes") {
out.shapes = true;
} else {
throw new Error(`Unknown argument: ${arg}`);
}
}
return out;
}
function resolveTheme(themePath) {
if (!themePath) {
throw new Error("Missing --theme. Provide a path to a theme .js file or a built-in name.");
}
// Try as a built-in name first (e.g., "newsprint" → examples/themes/theme-newsprint.js)
const builtIn = path.join(EXAMPLES_THEMES_DIR, `theme-${themePath}.js`);
if (fs.existsSync(builtIn)) {
return require(builtIn);
}
// Try as a direct path
const resolved = path.resolve(process.cwd(), themePath);
if (fs.existsSync(resolved)) {
return require(resolved);
}
// List available built-ins
const available = listBuiltInThemes();
throw new Error(
`Theme not found: "${themePath}"\n` +
` Built-in themes: ${available.join(", ")}\n` +
` Or provide a path to a .js theme file.`
);
}
function listBuiltInThemes() {
try {
return fs.readdirSync(EXAMPLES_THEMES_DIR)
.filter((f) => f.startsWith("theme-") && f.endsWith(".js"))
.map((f) => f.replace("theme-", "").replace(".js", ""));
} catch (e) {
return [];
}
}
function readSource(sourcePath) {
let raw = "";
if (sourcePath) {
raw = fs.readFileSync(path.resolve(process.cwd(), sourcePath), "utf8");
} else if (!process.stdin.isTTY) {
raw = fs.readFileSync(0, "utf8");
} else {
throw new Error("Missing --source. Provide a path to a .json file or pipe JSON via stdin.");
}
if (!raw || !raw.trim()) {
throw new Error("Empty source input.");
}
return JSON.parse(raw);
}
function listBuiltInFonts() {
const fontsDir = path.join(__dirname, "fonts");
try {
return fs.readdirSync(fontsDir)
.filter((f) => f.endsWith(".js"))
.map((f) => f.replace(".js", ""))
.sort();
} catch (e) {
return [];
}
}
function printFonts() {
const fonts = listBuiltInFonts();
if (fonts.length === 0) {
console.log("No built-in fonts found.");
return;
}
console.log(`Built-in fonts (${fonts.length}):\n`);
for (const font of fonts) {
console.log(` ${font.padEnd(22)} require("h17-sspdf/fonts/${font}.js")`);
}
console.log(`\nEach font exports { Regular, Bold } as base64 strings.`);
console.log(`See DOCUMENTATION.md "Built-in fonts" for usage.`);
}
function printShapes() {
const { shapeWidths } = require("./core/shapes");
const names = Object.keys(shapeWidths);
console.log(`Built-in shapes (${names.length}):\n`);
console.log(" Bullets: arrow, circle, square, diamond, triangle, dash, chevron");
console.log(" Decorators: doubleColon, commentSlash, hashComment, bracketChevron, treeBranch, terminalPrompt");
console.log(" Symbols: checkmark, cross, star, plus, minus, warning, infoCircle");
console.log(`\nUse as marker labels: { shape: "arrow", shapeColor: [0,0,0], shapeSize: 1 }`);
console.log(`See DOCUMENTATION.md "Vector shapes" for usage.`);
}
function printHelp() {
const themes = listBuiltInThemes();
console.log(`
sspdf CLI - Render a source JSON + theme into a PDF.
Usage:
node cli.js --source <file.json> --theme <theme> --output <file.pdf>
cat source.json | node cli.js --theme <theme> --output out.pdf
Options:
-s, --source <path> Path to source JSON file (or pipe via stdin)
-t, --theme <name|path> Built-in theme name or path to a .js theme file
-o, --output <path> Output PDF path (default: output/cli-output.pdf)
-h, --help Show this help
--fonts List built-in fonts
--shapes List built-in vector shapes
Built-in themes: ${themes.join(", ")}
Examples:
node cli.js -s examples/sources/source-article.json -t default -o output/article.pdf
node cli.js -s my-source.json -t ./my-theme.js -o my-doc.pdf
cat data.json | node cli.js -t newsprint -o output/newspaper.pdf
`.trim());
}
function collectChartOps(obj) {
const charts = [];
if (!obj || typeof obj !== "object") return charts;
if (Array.isArray(obj)) {
obj.forEach((item) => charts.push(...collectChartOps(item)));
} else {
if (obj.type === "chart") charts.push(obj);
for (const key of ["operations", "sections", "content", "items", "children"]) {
if (Array.isArray(obj[key])) charts.push(...collectChartOps(obj[key]));
}
if (obj.pageTemplates) {
if (Array.isArray(obj.pageTemplates.header)) charts.push(...collectChartOps(obj.pageTemplates.header));
if (Array.isArray(obj.pageTemplates.footer)) charts.push(...collectChartOps(obj.pageTemplates.footer));
}
}
return charts;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) {
printHelp();
return;
}
if (args.fonts) {
printFonts();
return;
}
if (args.shapes) {
printShapes();
return;
}
const source = readSource(args.source);
const theme = resolveTheme(args.theme);
const outputPath = path.resolve(
process.cwd(),
args.output || path.join("output", "cli-output.pdf")
);
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
const chartOps = collectChartOps(source);
if (chartOps.length > 0) {
registerPlugin("chart", plugins.chart);
for (const op of chartOps) {
await plugins.chart.preRender(op);
}
}
const result = renderDocument({ source, theme, outputPath });
console.log(`[OK] ${result.operationsCount} operations rendered`);
console.log(`[OK] ${outputPath}`);
}
main().catch((err) => {
console.error(`[ERROR] ${err.message}`);
process.exit(1);
});