-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
285 lines (258 loc) · 7.91 KB
/
index.js
File metadata and controls
285 lines (258 loc) · 7.91 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// index.js
// Main module entry point for oshea - API and Engine
require('module-alias')(__dirname);
const os = require('node:os');
const fs = require('node:fs');
const fsp = require('node:fs').promises;
const path = require('node:path');
const { spawn } = require('node:child_process');
const yaml = require('js-yaml');
const {
defaultHandlerPath,
markdownUtilsPath,
pdfGeneratorPath,
configResolverPath,
pluginManagerPath,
pluginRegistryBuilderPath,
loggerPath,
watchHandlerPath,
pluginDeterminerPath,
} = require('@paths');
const DefaultHandler = require(defaultHandlerPath);
const markdownUtils = require(markdownUtilsPath);
const pdfGenerator = require(pdfGeneratorPath);
const ConfigResolver = require(configResolverPath);
const PluginManager = require(pluginManagerPath);
const PluginRegistryBuilder = require(pluginRegistryBuilderPath);
const logger = require(loggerPath);
const { setupWatch } = require(watchHandlerPath);
const { determinePluginToUse } = require(pluginDeterminerPath);
// Business Logic Functions (moved from cli.js)
function openPdf(pdfPath, viewerCommand) {
if (!viewerCommand) {
logger.warn(`PDF viewer not configured. PDF generated at: ${pdfPath}`);
return;
}
logger.info(`Attempting to open PDF "${pdfPath}" with: ${viewerCommand}`);
try {
const [command, ...args] = viewerCommand.split(' ');
const viewerProcess = spawn(command, [...args, pdfPath], {
detached: true,
stdio: 'ignore',
});
viewerProcess.on('error', (err) => {
logger.warn(
`WARN: Failed to start PDF viewer '${viewerCommand}': ${err.message}.`,
);
logger.warn(`Please open "${pdfPath}" manually.`);
});
viewerProcess.unref();
} catch (e) {
logger.warn(
`WARN: Error trying to open PDF with '${viewerCommand}': ${e.message}.`,
);
logger.warn(`Please open "${pdfPath}" manually.`);
}
}
async function commonCommandHandler(args, executorFunction, commandType) {
try {
if (args.watch) {
await setupWatch(args, null, async (watchedArgs) => {
const currentConfigResolver = new ConfigResolver(
watchedArgs.config,
watchedArgs.factoryDefaults,
watchedArgs.isLazyLoad || false,
{
pluginsRoot: watchedArgs.manager.pluginsRoot,
pluginInstaller: watchedArgs.manager,
},
);
await executorFunction(watchedArgs, currentConfigResolver);
});
} else {
await executorFunction(args, args.configResolver);
}
} catch (error) {
const pluginNameForError =
args.pluginSpec || args.plugin || args.pluginName || 'N/A';
logger.error(
`ERROR in '${commandType}' command for plugin '${pluginNameForError}': ${error.message}`,
);
if (error.stack && !args.watch) logger.error(error.stack);
if (!args.watch) process.exit(1);
}
}
async function executeConversion(args, configResolver) {
const dependenciesForPluginDeterminer = {
fsPromises: fsp,
fsSync: fs,
path: path,
yaml: yaml,
markdownUtils: markdownUtils,
processCwd: process.cwd,
};
const {
pluginSpec,
source: pluginSource,
localConfigOverrides,
} = await determinePluginToUse(
args,
dependenciesForPluginDeterminer,
'default',
);
args.pluginSpec = pluginSpec;
logger.info(`Processing 'convert' for: ${args.markdownFile}`);
const resolvedMarkdownPath = path.resolve(args.markdownFile);
const effectiveConfig = await configResolver.getEffectiveConfig(
pluginSpec,
localConfigOverrides,
resolvedMarkdownPath,
);
const mainLoadedConfig = effectiveConfig.mainConfig;
let outputDir;
let outputFilename = args.filename;
let usedTemporaryOutputDir = false;
if (args.outdir) {
outputDir = path.resolve(args.outdir);
if (args.filename) {
outputFilename = path.basename(args.filename);
}
} else if (args.filename) {
const resolvedOutputPath = path.isAbsolute(args.filename)
? args.filename
: path.resolve(process.cwd(), args.filename);
outputDir = path.dirname(resolvedOutputPath);
outputFilename = path.basename(resolvedOutputPath);
} else {
outputDir = path.join(os.tmpdir(), 'oshea-output');
usedTemporaryOutputDir = true;
if (!(args.isLazyLoad && pluginSource !== 'CLI option')) {
logger.info(
`No output directory specified. Defaulting to temporary directory: ${outputDir}`,
);
}
}
if (!fs.existsSync(outputDir)) {
await fsp.mkdir(outputDir, { recursive: true });
if (!(args.isLazyLoad && pluginSource !== 'CLI option')) {
logger.info(`Created output directory: ${outputDir}`);
}
}
const dataForPlugin = { markdownFilePath: resolvedMarkdownPath };
const pluginManager = new PluginManager();
const generatedPdfPath = await pluginManager.invokeHandler(
pluginSpec,
effectiveConfig,
dataForPlugin,
outputDir,
outputFilename,
);
if (generatedPdfPath) {
logger.success(
`Successfully generated PDF with plugin '${pluginSpec}': ${generatedPdfPath}`,
);
const viewer = mainLoadedConfig.pdf_viewer;
if (args.open && viewer) {
openPdf(generatedPdfPath, viewer);
} else if (args.open && !viewer) {
logger.warn(`PDF viewer not configured. PDF is at: ${generatedPdfPath}`);
} else if (!args.open && usedTemporaryOutputDir) {
logger.info(`PDF saved to temporary directory: ${generatedPdfPath}`);
}
} else {
if (!args.watch)
throw new Error(
`PDF generation failed for plugin '${pluginSpec}' (determined via ${pluginSource}).`,
);
}
logger.detail('convert command finished.');
}
async function executeGeneration(args, configResolver) {
const pluginToUse = args.pluginName;
args.pluginSpec = pluginToUse;
logger.info(`Processing 'generate' command for plugin: ${pluginToUse}`);
const effectiveConfig = await configResolver.getEffectiveConfig(
pluginToUse,
null,
null,
);
const mainLoadedConfig = effectiveConfig.mainConfig;
const knownGenerateOptions = [
'pluginName',
'outdir',
'o',
'filename',
'f',
'open',
'watch',
'w',
'config',
'help',
'h',
'version',
'v',
'$0',
'_',
'factoryDefaults',
'pluginSpec',
'isLazyLoad',
'manager',
];
const cliArgsForPlugin = {};
for (const key in args) {
if (!knownGenerateOptions.includes(key) && Object.hasOwn(args, key)) {
cliArgsForPlugin[key] = args[key];
}
}
const dataForPlugin = { cliArgs: cliArgsForPlugin };
const outputFilename = args.filename;
let outputDir = args.outdir;
if (args.outdir) {
outputDir = path.resolve(args.outdir);
}
if (!fs.existsSync(outputDir)) {
await fsp.mkdir(outputDir, { recursive: true });
logger.info(`Created output directory: ${outputDir}`);
}
const pluginManager = new PluginManager();
const generatedPdfPath = await pluginManager.invokeHandler(
pluginToUse,
effectiveConfig,
dataForPlugin,
outputDir,
outputFilename,
);
if (generatedPdfPath) {
logger.success(
`Successfully generated PDF via plugin '${pluginToUse}': ${generatedPdfPath}`,
);
const viewer = mainLoadedConfig.pdf_viewer;
if (args.open && viewer) {
openPdf(generatedPdfPath, viewer);
} else if (args.open && !viewer) {
logger.warn(`PDF viewer not configured. PDF is at: ${generatedPdfPath}`);
} else if (!args.open && !args.outdir) {
logger.info(`PDF saved to temporary directory: ${generatedPdfPath}`);
}
} else {
if (!args.watch)
throw new Error(`PDF generation failed for plugin '${pluginToUse}'.`);
}
logger.detail('generate command finished.');
}
// API and Engine exports
module.exports = {
// Core handlers and utilities
DefaultHandler,
markdownUtils,
pdfGenerator,
// Core system components
ConfigResolver,
PluginManager,
PluginRegistryBuilder,
// Engine functions (moved from cli.js)
openPdf,
commonCommandHandler,
executeConversion,
executeGeneration,
};