/** Export presets and exporting a project. */ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { basename, dirname, extname, join } from 'node:path'; import { answerJson, type ToolResponse } from '../answer-json.js'; import { docCacheCrash, docCachesWritten, editorCacheDirectory } from '../doc-cache.js'; import { type EngineRun, exitCodeText, howItEnded, runEngine } from '../engine-run.js'; import { errorMessage } from '../errors.js'; import { engineExtras, type HeadlessOutcome, librariesNotCopied, runOperation } from '../headless.js'; import { freeLibraryCopiesAsync } from '../library-copies.js'; import { statOf } from '../listed-reads.js'; import { resolveWithinProject } from '../paths.js'; import { settingKeys } from '../resources.js'; import { discard, scratchDirectory } from '../scratch.js'; import type { GodotServer } from '../server.js'; import { DEBUG_MODE } from '../server-version.js'; import { type OperationParams, readBoolean, readNonEmptyString, readString } from '../tool-args.js'; import { EXPORT_PLATFORMS } from '../tool-definitions.js'; import { editorHasOpen } from './editor-connection.js'; import { headlessOperation, headlessOutcomeAnswer } from './headless-ops.js'; import { importWhatChanged } from './import-scan.js'; import { checkedProject, chosenEngine, type EngineChoice } from './project-checks.js'; import { foldedEntriesAnswer } from './run-output.js'; import { importedFirstAnswer } from './scan-wait.js'; /** The export options read once per engine and platform. */ export class ExportState { /** The options of each platform's presets, by engine and platform, read once in an editor. */ readonly exportOptionsRead = new Map(); } /** * The name and platform of each preset in the project's export_presets.cfg, in the file's order, or * null when it has none. */ function presetsIn(projectPath: string): { name: string; platform: string; bakes: boolean }[] | null { let text: string; try { text = readFileSync(join(projectPath, 'export_presets.cfg'), 'utf8'); } catch { return null; } const presets: { name: string; platform: string; bakes: boolean }[] = []; const byNumber = new Map(); let held: { name: string; platform: string; bakes: boolean } | null = null; let options: string | null = null; for (const line of text.split(/\r?\n/)) { const section = /^\s*\[([^\]]+)\]/.exec(line)?.[1]?.trim(); if (section !== undefined) { held = openedPreset(section, presets, byNumber); options = /^preset\.(\d+)\.options$/.exec(section)?.[1] ?? null; continue; } if (held !== null) { held.name = quotedPresetValue(line, 'name') ?? held.name; held.platform = quotedPresetValue(line, 'platform') ?? held.platform; } const owner = options === null ? undefined : byNumber.get(options); if (owner !== undefined && /^\s*shader_baker\/enabled\s*=\s*true\s*$/.test(line)) { owner.bakes = true; } } return presets; } /** The preset a `[preset.N]` section starts, recorded in both collections, or null for any other section. */ function openedPreset( section: string, presets: { name: string; platform: string; bakes: boolean }[], byNumber: Map, ): { name: string; platform: string; bakes: boolean } | null { const number = /^preset\.(\d+)$/.exec(section)?.[1]; if (number === undefined) { return null; } const held = { name: '', platform: '', bakes: false }; presets.push(held); byNumber.set(number, held); return held; } /** The string [param key] is set to on [param line] of export_presets.cfg, unescaped, if it is set there. */ function quotedPresetValue(line: string, key: string): string | undefined { return new RegExp(`^\\s*${key}\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(line)?.[1]?.replace(/\\(.)/g, '$1'); } /** * The feature tags of each platform that a renderer override in project.godot may name, the most * particular first, and the renderer the engine itself gives a tag the project leaves unset. */ const RENDERER_FEATURES: Readonly> = { 'Windows Desktop': ['windows', 'pc'], Linux: ['linuxbsd', 'linux', 'pc'], macOS: ['macos', 'pc'], Android: ['android', 'mobile'], iOS: ['ios', 'mobile'], Web: ['web'], }; const ENGINE_RENDERERS: Readonly> = { mobile: 'mobile', web: 'gl_compatibility' }; /** The renderers Godot's shader baker bakes for. Compatibility has no RenderingDevice to bake with. */ const BAKED_RENDERERS = new Set(['forward_plus', 'mobile']); /** * The renderer whose shaders [param preset] bakes into its export, or null when it bakes none: its * shader baker is off, or its platform draws with Compatibility. */ export function bakingRenderer(projectPath: string, preset: string): string | null { const held = presetsIn(projectPath)?.find((one) => one.name === preset); if (held?.bakes !== true) { return null; } let settings = new Map(); try { settings = settingKeys(readFileSync(join(projectPath, 'project.godot'), 'utf8')); } catch { // A project with no readable project.godot draws with the engine's defaults. } const method = 'rendering/renderer/rendering_method'; let drawn: string | undefined; for (const feature of RENDERER_FEATURES[held.platform] ?? []) { const set = settings.get(`${method}.${feature}`); drawn = typeof set === 'string' ? set : ENGINE_RENDERERS[feature]; if (drawn !== undefined) { break; } } const base = settings.get(method); drawn ??= typeof base === 'string' ? base : 'forward_plus'; return BAKED_RENDERERS.has(drawn) ? drawn : null; } /** * The options a preset of one platform lists, as the engine's exporter describes them, and for an * option asked for that the preset has but would not list, what would list it. */ interface ExportOptions { readonly options: unknown[]; readonly hidden: unknown; } /** The platform of the preset called [param preset], or null when the project has none by that name. */ function presetPlatform(projectPath: string, preset: string): string | null { return presetsIn(projectPath)?.find((held) => held.name === preset)?.platform ?? null; } /** How [param ending] ended, for after "as", where it did not end cleanly. */ function engineEndSaid(ending: EngineRun): string { if (ending.failure === null && ending.exitSignal === null) { return `the engine ended with ${exitCodeText(ending.exitCode)}`; } const how = howItEnded(ending); return how.startsWith('ended by') ? `the engine was ${how}` : how; } /** * Why [param preset] cannot be exported with, read off the project's export_presets.cfg, or null * when it is one of the presets there. * * Asked before the engine is started: the engine refused a missing file with "doesn't have an * export_presets.cfg file at its root" and never named the preset, and starting it cost an import * of the whole project to learn that. */ export function exportPresetRefusal(projectPath: string, preset: string): string | null { const presets = presetsIn(projectPath); if (presets === null) { return `This project has no export_presets.cfg, so it has no preset '${preset}' to export with. project_export add_preset writes one, as the editor's Project > Export does.`; } const names = presets.map((held) => held.name); if (names.includes(preset)) { return null; } return names.length === 0 ? `export_presets.cfg names no preset, so there is no '${preset}' to export with. project_export add_preset adds one.` : `This project has no export preset named '${preset}'. Its presets are ${names.map((name) => `'${name}'`).join(', ')}.`; } /** * What project_export answers for [param ending], given when its output file was last written * before the export and after it, null where there was none. * * Exported means this run wrote the file. A file an earlier export left there read as this one's, so * an export that exited cleanly having written nothing was answered as having exported. * * [param beside] is what else the run wrote into the output's directory. A Windows or Linux export * writes the game's pack beside the executable unless the preset embeds it, and the build does not * start without it, so an answer naming only the executable sent the caller to ship half a game. * [param bytes] is the output's size after the run. */ export function exportAnswer( ending: EngineRun, asked: { readonly preset: string; readonly outputPath: string; readonly debug: boolean; readonly pack?: boolean; readonly bakedWith?: string; }, before: number | null, after: number | null, beside: readonly string[] = [], docCacheNote: string | null = null, bytes: number | null = null, imports: ReturnType = {}, engineNote: string | null = null, ): ToolResponse { const { log } = ending; const written = after !== null && after !== before; const notCopied = librariesNotCopied(log.all); const verdict = { exported: ending.exitCode === 0 && ending.failure === null && log.count('error') === 0 && written, ...asked, exitCode: ending.exitCode, exitSignal: ending.exitSignal ?? undefined, failure: ending.failure ?? undefined, errors: log.count('error'), warnings: log.count('warning'), // Exported says the file was written, not what it holds: a filter that leaves nearly // everything out still writes a pack, and only its size shows it. ...(written && bytes !== null ? { bytes } : {}), ...exportNotes({ beside, imports, notCopied, docCacheNote, engineNote }), ...foldedEntriesAnswer(log), }; return exportResponse(ending, asked, verdict, after, written); } /** The export's answer fields that say what else happened around it, each absent when nothing did. */ function exportNotes(notes: { readonly beside: readonly string[]; readonly imports: ReturnType; readonly notCopied: readonly string[]; readonly docCacheNote: string | null; readonly engineNote: string | null; }): { alsoWritten?: readonly string[]; librariesNotLoaded?: readonly string[]; extensionNote?: string; docCacheNote?: string; engineNote?: string; } { return { ...(notes.beside.length === 0 ? {} : { alsoWritten: notes.beside }), ...notes.imports, ...librariesNotLoadedAnswer(notes.notCopied), ...(notes.docCacheNote === null ? {} : { docCacheNote: notes.docCacheNote }), ...(notes.engineNote === null ? {} : { engineNote: notes.engineNote }), }; } /** The fields an export answers with for libraries it could not load, none when it loaded them all. */ function librariesNotLoadedAnswer(notCopied: readonly string[]): { librariesNotLoaded?: readonly string[]; extensionNote?: string; } { if (notCopied.length === 0) { return {}; } return { librariesNotLoaded: notCopied, extensionNote: `The export could not load ${notCopied.join(' and ')}: on Windows an engine running as the editor, which an export is, loads a GDExtension from a ~ copy beside the library, and another engine on this project held that copy: it could not be moved aside before the export, or another engine made a new one in between. Export again once that engine has loaded or exited.`, }; } /** The export's answer for its verdict:the verdict alone when exported, else a line saying why not. */ function exportResponse( ending: EngineRun, asked: { readonly preset: string; readonly outputPath: string }, verdict: { readonly exported: boolean }, after: number | null, written: boolean, ): ToolResponse { const { log } = ending; if (verdict.exported) { return { content: [{ type: 'text', text: answerJson(verdict) }] }; } if (written) { const errors = log.count('error'); const because = [ ...(ending.exitCode === 0 && ending.failure === null && ending.exitSignal === null ? [] : [engineEndSaid(ending)]), ...(errors === 0 ? [] : [`it printed ${String(errors)} ${errors === 1 ? 'error' : 'errors'}, under entries`]), ]; return { content: [ { type: 'text', text: `Export with preset '${asked.preset}' wrote ${asked.outputPath}, but it is not counted as exported, as ${because.join(' and ')}.`, }, { type: 'text', text: answerJson(verdict) }, ], isError: true, }; } const stale = after === null ? '' : ` The ${asked.outputPath} there is from before this export, which did not write it.`; const why = ending.exitSignal === null ? stale : ` The engine was ${howItEnded(ending)}, so it has no exit code.${stale}`; return { content: [ { type: 'text', text: `Export with preset '${asked.preset}' did not produce ${asked.outputPath}.${why}`, }, { type: 'text', text: answerJson(verdict) }, ], isError: true, }; } /** * What an export wrote beside [param output] in the folder it wrote into, as project paths: every * file in [param after] that [param before] did not hold, or held written at another time. * [param within] is the folder's own project path, `.` for the project's root. */ export function writtenBeside( before: ReadonlyMap, after: ReadonlyMap, output: string, within: string, ): string[] { return [...after] .filter(([name, at]) => name !== output && before.get(name) !== at) .map(([name]) => (within === '.' ? name : `${within}/${name}`)) .toSorted(); } /** The files directly inside [param folder], each with when it was last written. */ function filesIn(folder: string): Map { const found = new Map(); try { for (const entry of readdirSync(folder, { withFileTypes: true })) { const stat = entry.isFile() ? statOf(join(folder, entry.name)) : undefined; if (stat !== undefined) { found.set(entry.name, stat.mtimeMs); } } } catch { // A folder that cannot be listed holds nothing this answer can name. } return found; } /** The same for an export's output, which is a file to write rather than one the project holds. */ const OUTPUT_PATH_SOLUTIONS = [ 'Give outputPath inside the project, relative to it, such as "build/game.exe" or "res://build/game.exe". Copy the build elsewhere once it is exported', ]; /** What a project_export run is working on once its checks pass, passed from step to step. */ interface ExportCall { readonly project: { readonly value: { readonly path: string } }; readonly preset: string; readonly output: { readonly relativePath: string; readonly absolutePath: string }; readonly baking: string | null; readonly engine: Extract; readonly debug: boolean; readonly pack: boolean; readonly folder: string; } /** * project_export add_preset, written by a headless engine, with outputPath judged against the * project as run judges it. * * An editor open on the project read export_presets.cfg when it started and reads it again only * when an export platform comes or goes (Godot's EditorExport), so it lists none of this, and the * next save of its own presets writes its list over the file. */ export async function handleAddExportPreset( server: GodotServer, args: OperationParams, ): Promise { const project = checkedProject(server, args); if (!project.ok) { return project.response; } const given = readNonEmptyString(args, 'outputPath'); const output = given === undefined ? null : resolveWithinProject(project.value.path, given, { forTheEngine: true }); if (output !== null && !output.ok) { return server.createErrorResponse(output.reason, OUTPUT_PATH_SOLUTIONS); } const platform = readString(args, 'platform') ?? ''; // The operation refuses a platform the exporters do not know and names the ones they do. let knownOptions: unknown[] = []; if (EXPORT_PLATFORMS.includes(platform)) { const known = await exportOptions(server, project.value.path, platform); if (typeof known === 'string') { return server.createErrorResponse(known); } knownOptions = known.options; } const outcome = await headlessOperation( server, 'add_export_preset', { preset: readString(args, 'preset') ?? '', platform, outputPath: output?.relativePath ?? '', knownOptions, }, project.value.path, ); return presetsAnswer(server, outcome, project.value.path, 'does not list this preset'); } /** * [param outcome] of a write to export_presets.cfg, with a note when an editor is open on the * project, which holds the presets it read as it started and saves its own list over the file. * [param unseen] says what that editor does not know of the write. */ function presetsAnswer( server: GodotServer, outcome: HeadlessOutcome, projectPath: string, unseen: string, ): ToolResponse { if (!outcome.ok || !editorHasOpen(server, projectPath)) { return headlessOutcomeAnswer(server, outcome); } return server.jsonTextResponse({ ...outcome.payload, editorNote: `The editor open on this project read export_presets.cfg when it started and ${unseen}, and saving presets in its Export dialog writes its own list over the file. editor_launch restart loads the file. An export through project_export run reads the file and needs no restart.`, ...engineExtras(outcome), }); } /** * project_export set_preset. The option names are checked against what the preset's platform's * exporter gives a new preset, which only an engine started as an editor can make, so that list is * read in one on an empty project of its own, once for each platform, rather than on this project, * where an editor would scan and import it. */ export async function handleSetExportPreset( server: GodotServer, args: OperationParams, ): Promise { const project = checkedProject(server, args); if (!project.ok) { return project.response; } const preset = readString(args, 'preset') ?? ''; const given = readString(args, 'outputPath'); const output = given === undefined || given === '' ? null : resolveWithinProject(project.value.path, given, { forTheEngine: true }); if (output !== null && !output.ok) { return server.createErrorResponse(output.reason, OUTPUT_PATH_SOLUTIONS); } const asked = await optionsAskedFor(server, project.value.path, preset, args['options']); if (typeof asked === 'string') { return server.createErrorResponse(asked); } const { knownOptions, hiddenOptions } = asked; const params: OperationParams = { preset, knownOptions, hiddenOptions }; if (given !== undefined) { params['outputPath'] = output?.relativePath ?? ''; } for (const key of [ 'exportFilter', 'files', 'includeFilter', 'excludeFilter', 'customFeatures', 'options', ]) { if (args[key] !== undefined) { params[key] = args[key]; } } const outcome = await headlessOperation(server, 'set_export_preset', params, project.value.path); return presetsAnswer(server, outcome, project.value.path, 'does not have this change'); } /** * The options the preset's exporter lists for the options a set_preset call gives, with the ones it * hides, or why they could not be read. None are read when no options were given. */ async function optionsAskedFor( server: GodotServer, projectPath: string, preset: string, options: unknown, ): Promise<{ knownOptions: unknown[]; hiddenOptions: unknown } | string> { if (options === undefined || options === null || Object.keys(options).length === 0) { return { knownOptions: [], hiddenOptions: {} }; } const platform = presetPlatform(projectPath, preset); if (platform === null) { return { knownOptions: [], hiddenOptions: {} }; } const known = await exportOptions(server, projectPath, platform, { presetsFile: join(projectPath, 'export_presets.cfg'), preset, asked: options, }); return typeof known === 'string' ? known : { knownOptions: known.options, hiddenOptions: known.hidden }; } /** project_export remove_preset. */ export async function handleRemoveExportPreset( server: GodotServer, args: OperationParams, ): Promise { const project = checkedProject(server, args); if (!project.ok) { return project.response; } const outcome = await headlessOperation( server, 'remove_export_preset', { preset: readString(args, 'preset') ?? '' }, project.value.path, ); return presetsAnswer(server, outcome, project.value.path, 'still lists this preset'); } /** * The options a preset of [param platform] lists, from an editor-mode engine on an empty project, * or why they could not be read. The engine is [param projectPath]'s, whose exporters are the * ones its export runs. With no [param standing], a new preset's, kept for the server's life * since the list is the engine's and changes only with it. With it, the preset's as it would * stand with its own options and the ones asked applied, since an exporter lists some options only * while others are on. */ async function exportOptions( server: GodotServer, projectPath: string, platform: string, standing?: { presetsFile: string; preset: string; asked: unknown }, ): Promise { const engine = await chosenEngine(server, projectPath); if (!engine.ok) { return engine.response.content.map((block) => block.text).join(' '); } const key = `${engine.value}\n${platform}`; const kept = standing === undefined ? server.exports.exportOptionsRead.get(key) : undefined; if (kept !== undefined) { return kept; } const empty = scratchDirectory('export'); try { writeFileSync(join(empty, 'project.godot'), 'config_version=5\n'); // On an empty folder, for the project's sake: its slot is taken for the project. const exporting = { godotPath: engine.value, script: server.operationsScript, debug: DEBUG_MODE, editor: true, project: projectPath, }; const outcome = await runOperation(exporting, 'export_options', { platform, ...standing }, empty); const options: unknown = outcome.ok ? outcome.payload['options'] : undefined; if (!Array.isArray(options)) { return `The ${platform} export options could not be read from the engine: ${outcome.ok ? 'it named none' : outcome.message}`; } const read: ExportOptions = { options, hidden: outcome.ok ? outcome.payload['hidden'] : undefined }; if (standing === undefined) { server.exports.exportOptionsRead.set(key, read); } return read; } finally { discard(empty); } } /** * project_export run: the engine's own export, which is not an operation of the script. The * destination is documented as inside the project and is contained like every other path. */ export async function handleExportProject(server: GodotServer, args: OperationParams): Promise { const project = checkedProject(server, args); if (!project.ok) { return project.response; } const preset = readNonEmptyString(args, 'preset') ?? ''; const output = resolveWithinProject(project.value.path, readString(args, 'outputPath') ?? '', { forTheEngine: true, }); if (!output.ok) { return server.createErrorResponse(output.reason, OUTPUT_PATH_SOLUTIONS); } const noPreset = exportPresetRefusal(project.value.path, preset); if (noPreset !== null) { return server.createErrorResponse(noPreset, [ 'project_export list reads the presets the project has', 'project_export add_preset adds one', ]); } // Godot's shader baker runs only in an editor drawing with the preset's renderer. A headless // one exports every shader unbaked without a word, and the game then compiles them at its first // start: a game's export stalled 219 s there. Only Windows has a desktop out of sight to draw on, // so elsewhere the editor's window shows, which the caller allows with showWindow. const baking = bakingRenderer(project.value.path, preset); const outOfSight = process.platform === 'win32'; if (baking !== null && !outOfSight && readBoolean(args, 'showWindow') !== true) { return server.createErrorResponse( `${preset} bakes its shaders (shader_baker/enabled), which needs an editor drawing with ${baking} rather than a headless one. On this system that editor shows its window while it exports. Give showWindow true to allow the window.`, ['Or turn shader_baker/enabled off with project_export set_preset to export without baked shaders'], ); } return await exportAfterTheChecks(server, args, project, preset, output, baking); } /** The export once the project, preset and output are judged: the engine found and the flags checked. */ async function exportAfterTheChecks( server: GodotServer, args: OperationParams, project: { readonly value: { readonly path: string } }, preset: string, output: { readonly relativePath: string; readonly absolutePath: string }, baking: string | null, ): Promise { const engine = await chosenEngine(server, project.value.path); if (!engine.ok) { return engine.response; } const debug = readBoolean(args, 'debug') ?? false; const pack = readBoolean(args, 'pack') ?? false; // Godot's command line exports a pack as a release whatever else it is told. if (pack && debug) { return server.createErrorResponse( 'A pack is exported as a release: the command-line exporter has no debug pack, so debug and pack cannot both be true.', ['Leave debug out for a pack', 'Or leave pack out for a debug build'], ); } const extension = extname(output.relativePath).toLowerCase(); if (pack && extension !== '.pck' && extension !== '.zip') { return server.createErrorResponse( `A pack is written as a .pck or a .zip, and ${output.relativePath} is neither: the exporter picks the format by the extension.`, ['Give outputPath ending in .pck, or .zip for a zip of the resources'], ); } // Godot's command-line exporter does not create the directory it is told to write into, where // the editor's own export dialog does, and what it says when it is missing is "The given export // path doesn't exist", which reads as a wrong path in the preset and sends the caller to check // the preset. The tool was handed the path and has already contained it inside the project, so // it knows exactly which directory it is about to need. Made only once nothing else refuses the // call, so a refused call leaves no folder behind. const folder = dirname(output.absolutePath); try { mkdirSync(folder, { recursive: true }); } catch (error) { return server.createErrorResponse( `Cannot create ${dirname(output.relativePath)} to export into: ${errorMessage(error)}`, ); } return await exportWithImportedFiles(server, { project, preset, output, baking, engine, debug, pack, folder, }); } /** The export run once the files that changed are imported, with the engine's log kept apart. */ async function exportWithImportedFiles(server: GodotServer, call: ExportCall): Promise { const { project, preset, output, baking, engine, debug, pack } = call; // The export's own scan imports what changed only by the editor's cache, so in a checkout // without it a sidecar a tool wrote, naming no output, went into the build as an asset that // fails to load. const imported = await importWhatChanged(server, project.value.path); // Away from the project's own user://logs/, for the reason the operations are: the engine // renames that file when a process starts, so an export beside a running game rotated the // game's log out from under it. What this run printed is read off its streams just below and // answered with, so the file it writes is of no use to anybody either. const exportLogs = scratchDirectory('export'); const exportArgs = [ // Vulkan whatever driver the project names, since the baker writes each driver's shaders // either way, and Vulkan is the one proved drawing on the hidden desktop. ...(baking === null ? ['--headless'] : ['--rendering-method', baking, '--rendering-driver', 'vulkan', '--audio-driver', 'Dummy']), '--log-file', join(exportLogs, 'engine.log'), '--path', project.value.path, pack ? '--export-pack' : debug ? '--export-debug' : '--export-release', preset, output.absolutePath, ]; server.logDebug(`Exporting: ${engine.value} ${exportArgs.join(' ')}`); return await runExportEngine(server, call, { imported, exportLogs, exportArgs }); } /** The engine's export, run again once when it crashed writing its doc cache, and the answer built from it. */ async function runExportEngine( server: GodotServer, call: ExportCall, prepared: { readonly imported: Parameters[0]; readonly exportLogs: string; readonly exportArgs: readonly string[]; }, ): Promise { const { project, preset, output, baking, engine, debug, pack, folder } = call; const { imported, exportLogs, exportArgs } = prepared; const outOfSight = process.platform === 'win32'; // The file this run writes, told from one an earlier export left there: an export that exited // cleanly and wrote nothing read as exported from the last one's file. const writtenAt = (): number | null => existsSync(output.absolutePath) ? statSync(output.absolutePath).mtimeMs : null; const caches = editorCacheDirectory(engine.value); const exportOnce = async () => { const before = writtenAt(); const listedBefore = filesIn(folder); const cachesBefore = docCachesWritten(caches); const freed = await freeLibraryCopiesAsync(project.value.path); if (freed.setAside.length > 0 || freed.swept.length > 0) { server.logDebug( `Before the export: set aside ${freed.setAside.join(', ')}, and swept ${freed.swept.join(', ')}`, ); } // An export of a real project is slow, so it gets five minutes rather than no limit. const ending = await runEngine(engine.value, exportArgs, { timeout: { ms: 300000, said: 'five minutes' }, project: project.value.path, ...(baking === null || !outOfSight ? {} : { desktop: { directory: project.value.path, scratch: exportLogs } }), }); const crash = docCacheCrash(ending, cachesBefore, docCachesWritten(caches), 'export'); return { ending, before, listedBefore, crash }; }; let run: Awaited>; let docCacheNote: string | null; try { const first = await exportOnce(); docCacheNote = first.crash; run = first.crash === null ? first : await exportOnce(); } finally { discard(exportLogs); } const { ending, before, listedBefore } = run; if (ending.exitSignal === null && ending.exitCode === null) { return server.createErrorResponse( `Export could not be run: ${ending.failure ?? 'the engine gave no exit status'}`, ); } const beside = writtenBeside( listedBefore, filesIn(folder), basename(output.absolutePath), dirname(output.relativePath).replaceAll('\\', '/'), ); return exportAnswer( ending, { preset, outputPath: output.relativePath, debug, ...(pack ? { pack } : {}), ...(baking === null ? {} : { bakedWith: baking }), }, before, writtenAt(), beside, docCacheNote, existsSync(output.absolutePath) ? statSync(output.absolutePath).size : null, importedFirstAnswer(imported), engine.note, ); }