-
Notifications
You must be signed in to change notification settings - Fork 331
/
render-files.ts
736 lines (670 loc) · 21.6 KB
/
render-files.ts
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/*
* render-files.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
// ensures cell handlers are installed
import "../../core/handlers/handlers.ts";
import {
kExecuteEnabled,
kFreeze,
kIncludeInHeader,
kKeepMd,
kLang,
kQuartoRequired,
} from "../../config/constants.ts";
import { isHtmlCompatible } from "../../config/format.ts";
import { mergeConfigs } from "../../core/config.ts";
import { initDayJsPlugins, setDateLocale } from "../../core/date.ts";
import { initDenoDom } from "../../core/deno-dom.ts";
import { HandlerContextResults } from "../../core/handlers/types.ts";
import {
handleLanguageCells,
languages,
resetFigureCounter,
} from "../../core/handlers/base.ts";
import { LanguageCellHandlerOptions } from "../../core/handlers/types.ts";
import { asMappedString, mappedDiff } from "../../core/mapped-text.ts";
import {
validateDocument,
validateDocumentFromSource,
} from "../../core/schema/validate-document.ts";
import { createTempContext, TempContext } from "../../core/temp.ts";
import {
executionEngineKeepMd,
fileExecutionEngineAndTarget,
} from "../../execute/engine.ts";
import { annotateOjsLineNumbers } from "../../execute/ojs/annotate-source.ts";
import { ojsExecuteResult } from "../../execute/ojs/compile.ts";
import {
ExecuteOptions,
ExecuteResult,
MappedExecuteResult,
} from "../../execute/types.ts";
import { kProjectLibDir, ProjectContext } from "../../project/types.ts";
import { outputRecipe } from "./output.ts";
import { renderPandoc } from "./render.ts";
import { PandocRenderCompletion, RenderServices } from "./types.ts";
import { renderContexts } from "./render-contexts.ts";
import { renderProgress } from "./render-info.ts";
import {
ExecutedFile,
PandocRenderer,
RenderContext,
RenderedFile,
RenderedFormat,
RenderExecuteOptions,
RenderFile,
RenderFilesResult,
RenderFlags,
RenderOptions,
} from "./types.ts";
import { error, info } from "../../deno_ral/log.ts";
import * as ld from "../../core/lodash.ts";
import { basename, dirname, join, relative } from "../../deno_ral/path.ts";
import { Format } from "../../config/types.ts";
import {
figuresDir,
inputFilesDir,
isServerShiny,
isServerShinyKnitr,
} from "../../core/render.ts";
import {
normalizePath,
removeIfEmptyDir,
removeIfExists,
} from "../../core/path.ts";
import { resourcePath } from "../../core/resources.ts";
import { YAMLValidationError } from "../../core/yaml.ts";
import { resolveParams } from "./flags.ts";
import {
copyFromProjectFreezer,
copyToProjectFreezer,
defrostExecuteResult,
freezeExecuteResult,
freezerFigsDir,
freezerFreezeFile,
kProjectFreezeDir,
removeFreezeResults,
} from "./freeze.ts";
import { isJupyterNotebook } from "../../core/jupyter/jupyter.ts";
import { MappedString } from "../../core/lib/text-types.ts";
import {
createNamedLifetime,
Lifetime,
waitUntilNamedLifetime,
} from "../../core/lifetimes.ts";
import { resolveDependencies } from "./pandoc-dependencies-html.ts";
import {
getData as getTimingData,
pop as popTiming,
push as pushTiming,
withTiming,
withTimingAsync,
} from "../../core/timing.ts";
import { satisfies } from "semver/mod.ts";
import { quartoConfig } from "../../core/quarto.ts";
import { ensureNotebookContext } from "../../core/jupyter/jupyter-embed.ts";
import {
projectIsWebsite,
projectOutputDir,
} from "../../project/project-shared.ts";
import { NotebookContext } from "../../render/notebook/notebook-types.ts";
import { setExecuteEnvironment } from "../../execute/environment.ts";
export async function renderExecute(
context: RenderContext,
output: string,
options: RenderExecuteOptions,
): Promise<ExecuteResult> {
// are we running a compatible quarto version for this file?
const versionConstraint = context
.format.metadata[kQuartoRequired] as (string | undefined);
if (versionConstraint) {
const ourVersion = quartoConfig.version();
let result: boolean;
try {
result = satisfies(ourVersion, versionConstraint);
} catch (_e) {
throw new Error(
`In file ${context.target.source}:\nVersion constraint is invalid: ${versionConstraint}.`,
);
}
if (!result) {
throw new Error(
`in file ${context.target.source}:\nQuarto version ${ourVersion} does not satisfy version constraint ${versionConstraint}.`,
);
}
}
// alias options
const { resolveDependencies = true, alwaysExecute = false } = options;
// alias flags
const flags = context.options.flags || {};
// compute filesDir
const filesDir = inputFilesDir(context.target.source);
// compute project relative files dir (if we are in a project)
let projRelativeFilesDir: string | undefined;
if (context.project) {
const inputDir = relative(
context.project.dir,
dirname(context.target.source),
);
projRelativeFilesDir = join(inputDir, filesDir);
}
// are we eligible to freeze?
const canFreeze = context.engine.canFreeze &&
(context.format.execute[kExecuteEnabled] !== false);
// use previous frozen results if they are available
if (context.project && !alwaysExecute) {
// check if we are using the freezer
const thaw = canFreeze &&
(context.format.execute[kFreeze] ||
(context.options.useFreezer ? "auto" : false));
if (thaw) {
// copy from project freezer
const hidden = context.format.execute[kFreeze] === false;
copyFromProjectFreezer(
context.project,
projRelativeFilesDir!,
hidden,
);
const thawedResult = defrostExecuteResult(
context.target.source,
output,
context.options.services.temp,
thaw === true,
);
if (thawedResult) {
// copy the site_libs dir from the freezer
const libDir = context.project?.config?.project[kProjectLibDir];
if (libDir) {
copyFromProjectFreezer(context.project, libDir, hidden);
}
// remove the results dir
removeFreezeResults(join(context.project.dir, projRelativeFilesDir!));
// notify engine that we skipped execute
if (context.engine.executeTargetSkipped) {
context.engine.executeTargetSkipped(context.target, context.format);
}
// return results
return thawedResult;
}
}
}
// calculate figsDir
const figsDir = join(filesDir, figuresDir(context.format.pandoc.to));
pushTiming("render-execute");
const executeOptions: ExecuteOptions = {
target: context.target,
resourceDir: resourcePath(),
tempDir: context.options.services.temp.createDir(),
dependencies: resolveDependencies,
libDir: context.libDir,
format: context.format,
projectDir: context.project?.dir,
cwd: flags.executeDir || dirname(normalizePath(context.target.source)),
params: resolveParams(flags.params, flags.paramsFile),
quiet: flags.quiet,
previewServer: context.options.previewServer,
handledLanguages: languages(),
project: context.project,
};
// execute computations
setExecuteEnvironment(executeOptions);
const executeResult = await context.engine.execute(executeOptions);
popTiming();
// write the freeze file if we are in a project
if (context.project && !context.project.isSingleFile && canFreeze) {
// write the freezer file
const freezeFile = freezeExecuteResult(
context.target.source,
output,
executeResult,
);
// always copy to the hidden freezer
copyToProjectFreezer(context.project, projRelativeFilesDir!, true, true);
// copy to the _freeze dir if explicit _freeze is requested
if (context.format.execute[kFreeze] !== false) {
copyToProjectFreezer(context.project, projRelativeFilesDir!, false, true);
} else {
// otherwise cleanup the _freeze subdir b/c we aren't explicitly freezing anymore
// figs dir for this target format
const freezeFigsDir = freezerFigsDir(
context.project,
projRelativeFilesDir!,
basename(figsDir),
);
removeIfExists(freezeFigsDir);
// freezer file
const projRelativeFreezeFile = relative(context.project.dir, freezeFile);
const freezerFile = freezerFreezeFile(
context.project,
projRelativeFreezeFile,
);
removeIfExists(freezerFile);
// remove empty directories
removeIfEmptyDir(dirname(freezerFile));
removeIfEmptyDir(dirname(freezeFigsDir));
removeIfEmptyDir(join(context.project.dir, kProjectFreezeDir));
}
// remove the freeze results file (now that it's safely in the freezer)
removeFreezeResults(join(context.project.dir, projRelativeFilesDir!));
}
// return result
return executeResult;
}
export async function renderFiles(
files: RenderFile[],
options: RenderOptions,
notebookContext: NotebookContext,
alwaysExecuteFiles: string[] | undefined,
pandocRenderer: PandocRenderer | undefined,
project: ProjectContext,
): Promise<RenderFilesResult> {
// provide default renderer
pandocRenderer = pandocRenderer || defaultPandocRenderer(options, project);
// create temp context
const tempContext = createTempContext();
try {
// make a copy of options so we don't mutate caller context
options = ld.cloneDeep(options);
// see if we should be using file-by-file progress
const progress = options.progress ||
(project && (files.length > 1) && !options.flags?.quiet);
// quiet pandoc output if we are doing file by file progress
const pandocQuiet = !!progress || !!options.quietPandoc;
// calculate num width
const numWidth = String(files.length).length;
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (progress) {
renderProgress(
`\r[${String(i + 1).padStart(numWidth)}/${files.length}] ${
relative(project!.dir, file.path)
}`,
);
}
// get contexts
const fileLifetime = await waitUntilNamedLifetime("render-file");
try {
await renderFileInternal(
fileLifetime,
file,
options,
project,
pandocRenderer,
files,
tempContext,
alwaysExecuteFiles,
pandocQuiet,
notebookContext,
);
} finally {
fileLifetime.cleanup();
}
}
if (progress) {
info("");
}
return await pandocRenderer.onComplete(false, options.flags?.quiet);
} catch (error) {
return {
files: (await pandocRenderer.onComplete(true)).files,
error: error || new Error(),
};
} finally {
tempContext.cleanup();
if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
Deno.writeTextFileSync(
Deno.env.get("QUARTO_PROFILER_OUTPUT")!,
JSON.stringify(getTimingData()),
);
}
}
}
export async function renderFile(
file: RenderFile,
options: RenderOptions,
services: RenderServices,
project: ProjectContext,
enforceProjectFormats: boolean = true,
): Promise<RenderFilesResult> {
// provide default renderer
const pandocRenderer = defaultPandocRenderer(options, project);
try {
// make a copy of options so we don't mutate caller context
options = ld.cloneDeep(options);
// quiet pandoc output if we are doing file by file progress
const pandocQuiet = !!options.quietPandoc;
// get contexts
const fileLifetime = createNamedLifetime("render-single-file");
try {
await renderFileInternal(
fileLifetime,
file,
options,
project,
pandocRenderer,
[file],
services.temp,
[],
pandocQuiet,
services.notebook,
enforceProjectFormats,
);
} finally {
fileLifetime.cleanup();
}
return await pandocRenderer.onComplete(false, options.flags?.quiet);
} catch (error) {
return {
files: (await pandocRenderer.onComplete(true)).files,
error: error || new Error(),
};
} finally {
if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
Deno.writeTextFileSync(
Deno.env.get("QUARTO_PROFILER_OUTPUT")!,
JSON.stringify(getTimingData()),
);
}
}
}
async function renderFileInternal(
lifetime: Lifetime,
file: RenderFile,
options: RenderOptions,
project: ProjectContext,
pandocRenderer: PandocRenderer,
files: RenderFile[],
tempContext: TempContext,
alwaysExecuteFiles: string[] | undefined,
pandocQuiet: boolean,
notebookContext: NotebookContext,
enforceProjectFormats: boolean = true,
) {
const outputs: Array<RenderedFormat> = [];
let contexts: Record<string, RenderContext> | undefined;
try {
contexts = await renderContexts(
file,
options,
true,
notebookContext,
project,
false,
enforceProjectFormats,
);
// Allow renderers to filter the contexts
contexts = pandocRenderer.onFilterContexts(
file.path,
contexts,
files,
options,
);
} catch (e) {
// bad YAML can cause failure before validation. We
// reconstruct the context as best we can and try to validate.
// note that this ignores "validate-yaml: false"
const { engine, target } = await fileExecutionEngineAndTarget(
file.path,
options.flags,
project,
);
const validationResult = await validateDocumentFromSource(
target.markdown,
engine.name,
error,
);
if (validationResult.length) {
throw new RenderInvalidYAMLError();
} else {
// rethrow if no validation error happened.
throw e;
}
}
const mergeHandlerResults = (
results: HandlerContextResults | undefined,
executeResult: MappedExecuteResult,
context: RenderContext,
) => {
if (results === undefined) {
return;
}
if (executeResult.includes) {
executeResult.includes = mergeConfigs(
executeResult.includes,
results.includes,
);
} else {
executeResult.includes = results.includes;
}
const extras = resolveDependencies(
results.extras,
dirname(context.target.source),
context.libDir,
tempContext,
project,
);
if (extras[kIncludeInHeader]) {
// note that we merge engine execute results back into cell handler
// execute results so that jupyter widget dependencies appear at the
// end (so that they don't mess w/ other libs using require/define)
executeResult.includes[kIncludeInHeader] = [
...(extras[kIncludeInHeader] || []),
...(executeResult.includes[kIncludeInHeader] || []),
];
}
executeResult.supporting.push(...results.supporting);
};
for (const format of Object.keys(contexts)) {
pushTiming("render-context");
const context = ld.cloneDeep(contexts[format]) as RenderContext; // since we're going to mutate it...
// disquality some documents from server: shiny
if (isServerShiny(context.format) && context.project) {
const src = relative(context.project?.dir!, context.target.source);
if (projectIsWebsite(context.project)) {
error(
`${src} uses server: shiny so cannot be included in a website project ` +
`(shiny documents require a backend server and so can't be published as static web content).`,
);
throw new Error();
} else if (
(projectOutputDir(context.project) !==
normalizePath(context.project.dir)) &&
isServerShinyKnitr(context.format, context.engine.name)
) {
error(
`${src} is a knitr engine document that uses server: shiny so cannot be included in a project with an output-dir ` +
`(shiny document output must be rendered alongside its source document).`,
);
throw new Error();
}
}
// get output recipe
const recipe = outputRecipe(context);
outputs.push({
path: recipe.finalOutput || recipe.output,
isTransient: recipe.isOutputTransient,
format: context.format,
});
if (context.active) {
// Set the date locale for this render
// Used for date formatting
initDayJsPlugins();
const resolveLang = () => {
const lang = context.format.metadata[kLang] ||
options.flags?.pandocMetadata?.[kLang];
if (typeof lang === "string") {
return lang;
} else {
return undefined;
}
};
const dateFormatLang = resolveLang();
if (dateFormatLang) {
await setDateLocale(
dateFormatLang,
);
}
lifetime.attach({
cleanup() {
resetFigureCounter();
},
});
try {
// one time denoDom init for html compatible formats
if (isHtmlCompatible(context.format)) {
await initDenoDom();
}
// determine execute options
const executeOptions = mergeConfigs(
{
alwaysExecute: alwaysExecuteFiles?.includes(file.path),
},
pandocRenderer.onBeforeExecute(recipe.format),
);
const validate = context.format.render?.["validate-yaml"];
if (validate !== false) {
const validationResult = await validateDocument(context);
if (validationResult.length) {
throw new RenderInvalidYAMLError();
}
}
// FIXME it should be possible to infer this directly now
// based on the information in the mapped strings.
//
// collect line numbers to facilitate runtime error reporting
const { ojsBlockLineNumbers } = annotateOjsLineNumbers(context);
// execute
const baseExecuteResult = await renderExecute(
context,
recipe.output,
executeOptions,
);
// recover source map from diff and create a mappedExecuteResult
// for markdown processing pre-pandoc with mapped strings
let mappedMarkdown: MappedString;
withTiming("diff-execute-result", () => {
if (!isJupyterNotebook(context.target.source)) {
mappedMarkdown = mappedDiff(
context.target.markdown,
baseExecuteResult.markdown,
);
} else {
mappedMarkdown = asMappedString(baseExecuteResult.markdown);
}
});
const resourceFiles: string[] = [];
if (baseExecuteResult.resourceFiles) {
resourceFiles.push(...baseExecuteResult.resourceFiles);
}
const languageCellHandlerOptions: LanguageCellHandlerOptions = {
name: "",
temp: tempContext,
format: recipe.format,
markdown: mappedMarkdown!,
context,
flags: options.flags || {} as RenderFlags,
stage: "post-engine",
};
let unmappedExecuteResult: ExecuteResult;
await withTimingAsync("handle-language-cells", async () => {
// handle language cells
const { markdown, results } = await handleLanguageCells(
languageCellHandlerOptions,
);
const mappedExecuteResult: MappedExecuteResult = {
...baseExecuteResult,
markdown,
};
mergeHandlerResults(
context.target.preEngineExecuteResults,
mappedExecuteResult,
context,
);
mergeHandlerResults(results, mappedExecuteResult, context);
// process ojs
const { executeResult, resourceFiles: ojsResourceFiles } =
await ojsExecuteResult(
context,
mappedExecuteResult,
ojsBlockLineNumbers,
);
resourceFiles.push(...ojsResourceFiles);
// keep md if requested
const keepMd = executionEngineKeepMd(context);
if (keepMd && context.format.execute[kKeepMd]) {
Deno.writeTextFileSync(keepMd, executeResult.markdown.value);
}
// now get "unmapped" execute result back to send to pandoc
unmappedExecuteResult = {
...executeResult,
markdown: executeResult.markdown.value,
};
});
// Ensure that we have rendered any notebooks
await ensureNotebookContext(
unmappedExecuteResult!.markdown,
context.options.services,
project,
);
// callback
pushTiming("render-pandoc");
await pandocRenderer.onRender(format, {
context,
recipe,
executeResult: unmappedExecuteResult!,
resourceFiles,
}, pandocQuiet);
popTiming();
} finally {
popTiming();
}
}
}
await pandocRenderer.onPostProcess(outputs, project);
}
// default pandoc renderer immediately renders each execute result
function defaultPandocRenderer(
_options: RenderOptions,
_project: ProjectContext,
): PandocRenderer {
const renderCompletions: PandocRenderCompletion[] = [];
const renderedFiles: RenderedFile[] = [];
return {
onFilterContexts: (
_file: string,
contexts: Record<string, RenderContext>,
_files: RenderFile[],
_options: RenderOptions,
) => {
return contexts;
},
onBeforeExecute: (_format: Format) => ({}),
onRender: async (
_format: string,
executedFile: ExecutedFile,
quiet: boolean,
) => {
renderCompletions.push(await renderPandoc(executedFile, quiet));
},
onPostProcess: async (renderedFormats: RenderedFormat[]) => {
let completion = renderCompletions.pop();
while (completion) {
renderedFiles.push(await completion.complete(renderedFormats));
completion = renderCompletions.pop();
}
renderedFiles.reverse();
},
onComplete: async () => {
return {
files: await Promise.resolve(renderedFiles),
};
},
};
}
class RenderInvalidYAMLError extends YAMLValidationError {
constructor() {
super("Render failed due to invalid YAML.");
}
}