Sync snapshot (2026-09-13) (#361)
This commit is contained in:
@@ -7,7 +7,13 @@
|
||||
"description": "Shared helpers for the Electron main processes (no Electron dependency, pure TS)",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./drop-open": "./src/drop-open.ts"
|
||||
"./drop-open": "./src/drop-open.ts",
|
||||
"./generated-images": "./src/generated-images.ts",
|
||||
"./headless-export": "./src/headless-export.ts",
|
||||
"./remote-image": "./src/remote-image.ts",
|
||||
"./renderer-protocol": "./src/renderer-protocol.ts",
|
||||
"./renderer-scheme": "./src/renderer-scheme.ts",
|
||||
"./safe-remote-url": "./src/safe-remote-url.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Argv parsing and the stdout envelope for the headless export entry:
|
||||
*
|
||||
* <app binary> --headless-export <input-file> --to <format> --out <path> [--json]
|
||||
*
|
||||
* Pure logic only — the Electron-side host that actually renders the file
|
||||
* lives in the shell main process (apps/shell/src/main/headless-export.ts).
|
||||
* Keeping the grammar and the exit codes here makes them unit-testable and
|
||||
* gives the external `genoffice` CLI one place to read the contract from.
|
||||
*
|
||||
* The renderer-side waiting helpers at the bottom live here too (imported as
|
||||
* `@genoffice/electron-utils/headless-export`, never through the package root,
|
||||
* which pulls in node: builtins) so every editor module reports the same way.
|
||||
*/
|
||||
|
||||
/** Editor module that owns a given input extension. */
|
||||
export type HeadlessExportModule = 'docs' | 'sheets' | 'slides' | 'markdown' | 'html'
|
||||
|
||||
/** Conversion targets the headless entry accepts; see HEADLESS_TARGETS for which module renders which. */
|
||||
export type HeadlessExportFormat = 'pdf' | 'docx' | 'html'
|
||||
|
||||
/** Targets each editor module can render without a dialog. */
|
||||
export const HEADLESS_TARGETS: Record<HeadlessExportModule, readonly HeadlessExportFormat[]> = {
|
||||
docs: ['pdf', 'html'],
|
||||
sheets: ['pdf'],
|
||||
slides: ['pdf'],
|
||||
markdown: ['pdf'],
|
||||
html: ['pdf', 'docx'],
|
||||
}
|
||||
|
||||
const ALL_TARGETS: readonly HeadlessExportFormat[] = ['pdf', 'docx', 'html']
|
||||
|
||||
/** What a hidden renderer window is asked to produce. */
|
||||
export interface HeadlessExportTarget {
|
||||
outPath: string
|
||||
format: HeadlessExportFormat
|
||||
}
|
||||
|
||||
export const HEADLESS_EXPORT_FLAG = '--headless-export'
|
||||
|
||||
/**
|
||||
* Process exit codes, matching the genoffice envelope convention.
|
||||
* 1 bad args / 2 input file error / 3 conversion failure.
|
||||
*/
|
||||
export const HEADLESS_EXIT = {
|
||||
success: 0,
|
||||
badArgs: 1,
|
||||
inputError: 2,
|
||||
conversionFailure: 3,
|
||||
} as const
|
||||
|
||||
export type HeadlessExitCode = (typeof HEADLESS_EXIT)[keyof typeof HEADLESS_EXIT]
|
||||
|
||||
export interface HeadlessExportRequest {
|
||||
/** absolute or cwd-relative path of the document to convert */
|
||||
input: string
|
||||
targetFormat: HeadlessExportFormat
|
||||
/** where the exported file is written */
|
||||
outPath: string
|
||||
/** print the machine-readable one-line envelope instead of a human sentence */
|
||||
json: boolean
|
||||
}
|
||||
|
||||
export type HeadlessArgvParse =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'ok'; request: HeadlessExportRequest }
|
||||
| { kind: 'error'; json: boolean; message: string }
|
||||
|
||||
/** Result of an export attempt, rendered by `formatHeadlessEnvelope`. */
|
||||
export type HeadlessExportOutcome =
|
||||
| { ok: true; input: string; outPath: string }
|
||||
| { ok: false; code: Exclude<HeadlessExitCode, 0>; message: string }
|
||||
|
||||
const MODULE_BY_EXTENSION: ReadonlyArray<readonly [RegExp, HeadlessExportModule]> = [
|
||||
[/\.docx$/i, 'docs'],
|
||||
[/\.(xlsx|xlsm|xls|csv)$/i, 'sheets'],
|
||||
[/\.pptx$/i, 'slides'],
|
||||
[/\.(md|markdown)$/i, 'markdown'],
|
||||
[/\.(html|htm)$/i, 'html'],
|
||||
]
|
||||
|
||||
/** Which editor module can render this input, or null when the extension is unsupported. */
|
||||
export function headlessModuleFor(inputPath: string): HeadlessExportModule | null {
|
||||
for (const [pattern, module] of MODULE_BY_EXTENSION) if (pattern.test(inputPath)) return module
|
||||
return null
|
||||
}
|
||||
|
||||
/** Extensions the headless entry accepts, for error messages. */
|
||||
export const HEADLESS_SUPPORTED_EXTENSIONS =
|
||||
'.docx, .xlsx, .xlsm, .xls, .csv, .pptx, .md, .markdown, .html, .htm'
|
||||
|
||||
/** `--flag value` and `--flag=value` both read the same. */
|
||||
function readOption(argv: readonly string[], index: number, flag: string): string | null {
|
||||
const arg = argv[index] ?? ''
|
||||
if (arg.startsWith(`${flag}=`)) return arg.slice(flag.length + 1)
|
||||
const next = argv[index + 1]
|
||||
// a following switch is never this flag's value (`--out --json` is a missing value)
|
||||
return next === undefined || next.startsWith('--') ? null : next
|
||||
}
|
||||
|
||||
function consumesNext(argv: readonly string[], index: number, flag: string): boolean {
|
||||
return !(argv[index] ?? '').startsWith(`${flag}=`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the headless-export switches out of an Electron `process.argv`.
|
||||
* Returns `{ kind: 'none' }` when the flag is absent, so the normal GUI
|
||||
* startup path stays untouched.
|
||||
*/
|
||||
export function parseHeadlessExportArgv(argv: readonly string[]): HeadlessArgvParse {
|
||||
const flagAt = argv.findIndex(
|
||||
(arg) => arg === HEADLESS_EXPORT_FLAG || arg.startsWith(`${HEADLESS_EXPORT_FLAG}=`),
|
||||
)
|
||||
if (flagAt === -1) return { kind: 'none' }
|
||||
const json = argv.includes('--json')
|
||||
const fail = (message: string): HeadlessArgvParse => ({ kind: 'error', json, message })
|
||||
|
||||
let input: string | null = null
|
||||
let to: string | null = null
|
||||
let outPath: string | null = null
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i] ?? ''
|
||||
if (arg === HEADLESS_EXPORT_FLAG || arg.startsWith(`${HEADLESS_EXPORT_FLAG}=`)) {
|
||||
input = readOption(argv, i, HEADLESS_EXPORT_FLAG)
|
||||
if (input === null) return fail(`${HEADLESS_EXPORT_FLAG} needs an input file`)
|
||||
if (consumesNext(argv, i, HEADLESS_EXPORT_FLAG)) i++
|
||||
continue
|
||||
}
|
||||
if (arg === '--to' || arg.startsWith('--to=')) {
|
||||
to = readOption(argv, i, '--to')
|
||||
if (to === null) return fail('--to needs a target format')
|
||||
if (consumesNext(argv, i, '--to')) i++
|
||||
continue
|
||||
}
|
||||
if (arg === '--out' || arg.startsWith('--out=')) {
|
||||
outPath = readOption(argv, i, '--out')
|
||||
if (outPath === null) return fail('--out needs an output path')
|
||||
if (consumesNext(argv, i, '--out')) i++
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if (!input) return fail(`${HEADLESS_EXPORT_FLAG} needs an input file`)
|
||||
if (!to) return fail(`--to is required (${ALL_TARGETS.join(', ')})`)
|
||||
const targetFormat = ALL_TARGETS.find((f) => f === to.toLowerCase())
|
||||
if (!targetFormat) {
|
||||
return fail(`unsupported target format "${to}" (${ALL_TARGETS.join(', ')})`)
|
||||
}
|
||||
if (!outPath) return fail('--out is required')
|
||||
|
||||
return { kind: 'ok', request: { input, targetFormat, outPath, json } }
|
||||
}
|
||||
|
||||
/** One-sentence description of an outcome, shared by the plain and JSON forms. */
|
||||
export function headlessSummary(outcome: HeadlessExportOutcome): string {
|
||||
return outcome.ok
|
||||
? `Exported ${outcome.input} to ${outcome.outPath}`
|
||||
: `Export failed: ${outcome.message}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The single stdout line. With `--json` it is exactly one JSON object;
|
||||
* otherwise a human-readable sentence. Newlines inside the message would
|
||||
* break the one-line contract, so they are folded to spaces.
|
||||
*/
|
||||
export function formatHeadlessEnvelope(outcome: HeadlessExportOutcome, json: boolean): string {
|
||||
const summary = headlessSummary(outcome).replace(/\s*[\r\n]+\s*/g, ' ')
|
||||
if (!json) return summary
|
||||
return JSON.stringify(
|
||||
outcome.ok
|
||||
? { status: 'ok', summary, output_path: outcome.outPath }
|
||||
: { status: 'error', summary, error: outcome.message.replace(/\s*[\r\n]+\s*/g, ' ') },
|
||||
)
|
||||
}
|
||||
|
||||
/** Exit code for an outcome. */
|
||||
export function headlessExitCode(outcome: HeadlessExportOutcome): HeadlessExitCode {
|
||||
return outcome.ok ? HEADLESS_EXIT.success : outcome.code
|
||||
}
|
||||
|
||||
// ---- renderer side ----
|
||||
|
||||
/** What a hidden renderer sends back when its export settles. */
|
||||
export interface HeadlessExportReport {
|
||||
ok: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface HeadlessWaitOptions {
|
||||
/** overall budget before the wait gives up */
|
||||
timeoutMs?: number
|
||||
pollMs?: number
|
||||
}
|
||||
|
||||
export const headlessSleep = (ms: number): Promise<void> =>
|
||||
new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
/**
|
||||
* Polls `ready` until it returns true. There is no user to notice a document
|
||||
* that never opens, so a stalled export must fail rather than hang forever;
|
||||
* `stallMessage` says what was still missing (a function is evaluated at
|
||||
* give-up time, so it can describe the state the wait actually died in).
|
||||
*/
|
||||
export async function pollUntilReady(
|
||||
ready: () => boolean,
|
||||
stallMessage: string | (() => string),
|
||||
{ timeoutMs = 180_000, pollMs = 250 }: HeadlessWaitOptions = {},
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (!ready()) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(typeof stallMessage === 'function' ? stallMessage() : stallMessage)
|
||||
}
|
||||
await headlessSleep(pollMs)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves when the document's @font-face loads have settled (they change
|
||||
* line-break points, so measuring before that is worthless), giving up after
|
||||
* `timeoutMs` rather than stranding the export. A DOM without FontFaceSet
|
||||
* (jsdom in unit tests) resolves immediately.
|
||||
*/
|
||||
export function documentFontsSettled(timeoutMs = 30_000): Promise<unknown> {
|
||||
if (typeof document === 'undefined' || !('fonts' in document)) return Promise.resolve()
|
||||
return Promise.race([document.fonts.ready, headlessSleep(timeoutMs)])
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderer half of a headless export: wait for the document, run the very
|
||||
* same export the File menu runs, and turn any failure into a report. Never
|
||||
* throws — the main process owns the process exit code.
|
||||
*/
|
||||
export async function runHeadlessRendererExport(
|
||||
outPath: string,
|
||||
waitUntilReady: () => Promise<void>,
|
||||
exportFile: (outPath: string) => Promise<boolean>,
|
||||
): Promise<HeadlessExportReport> {
|
||||
try {
|
||||
await waitUntilReady()
|
||||
const ok = await exportFile(outPath)
|
||||
return ok ? { ok: true } : { ok: false, error: 'export did not produce a file' }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Process-wide "no user is watching" flag, set once by the shell's
|
||||
* `--headless-export` entry before any editor module boots.
|
||||
*
|
||||
* The editor modules share one bundle inside the shell, so a single module
|
||||
* variable is enough. Everything that would steal focus or spawn UI after a
|
||||
* successful write (opening the exported PDF in a tab, revealing it in the
|
||||
* file manager) checks this first.
|
||||
*/
|
||||
let headless = false
|
||||
|
||||
export function setHeadlessMode(on: boolean): void {
|
||||
headless = on
|
||||
}
|
||||
|
||||
export function isHeadlessMode(): boolean {
|
||||
return headless
|
||||
}
|
||||
@@ -52,3 +52,30 @@ export {
|
||||
type PrintableHtml,
|
||||
type PrintWindow,
|
||||
} from './print-html-pdf'
|
||||
export { isHeadlessMode, setHeadlessMode } from './headless-mode'
|
||||
export {
|
||||
HEADLESS_EXIT,
|
||||
HEADLESS_EXPORT_FLAG,
|
||||
HEADLESS_SUPPORTED_EXTENSIONS,
|
||||
HEADLESS_TARGETS,
|
||||
formatHeadlessEnvelope,
|
||||
headlessExitCode,
|
||||
headlessModuleFor,
|
||||
headlessSummary,
|
||||
parseHeadlessExportArgv,
|
||||
type HeadlessArgvParse,
|
||||
type HeadlessExitCode,
|
||||
type HeadlessExportFormat,
|
||||
type HeadlessExportModule,
|
||||
type HeadlessExportOutcome,
|
||||
type HeadlessExportRequest,
|
||||
type HeadlessExportTarget,
|
||||
} from './headless-export'
|
||||
export {
|
||||
RENDERER_SCHEME,
|
||||
RENDERER_SCHEME_PRIVILEGE,
|
||||
rendererUrl,
|
||||
resolveRendererFile,
|
||||
type RendererHost,
|
||||
} from './renderer-scheme'
|
||||
export { installRendererProtocol, registerRendererScheme } from './renderer-protocol'
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { net, protocol } from 'electron'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { RENDERER_SCHEME, RENDERER_SCHEME_PRIVILEGE, resolveRendererFile } from './renderer-scheme'
|
||||
|
||||
/** Before app ready; a process may call registerSchemesAsPrivileged only once,
|
||||
* so hosts that register other schemes spread RENDERER_SCHEME_PRIVILEGE into
|
||||
* their own list instead. */
|
||||
export function registerRendererScheme(): void {
|
||||
protocol.registerSchemesAsPrivileged([RENDERER_SCHEME_PRIVILEGE])
|
||||
}
|
||||
|
||||
/** After app ready: serve each module's built renderer directory. */
|
||||
export function installRendererProtocol(roots: Record<string, string>): void {
|
||||
const table = new Map(Object.entries(roots))
|
||||
protocol.handle(RENDERER_SCHEME, (request) => {
|
||||
const file = resolveRendererFile(table, request.url)
|
||||
if (!file) return new Response(null, { status: 404 })
|
||||
return net
|
||||
.fetch(pathToFileURL(file).toString())
|
||||
.catch(() => new Response(null, { status: 404 }))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { CustomScheme } from 'electron'
|
||||
import { resolve, sep } from 'node:path'
|
||||
|
||||
/** Origin the built renderers are served from (`genoffice-app://<module>/index.html`). */
|
||||
export const RENDERER_SCHEME = 'genoffice-app'
|
||||
|
||||
/** Chromium persists V8 code caches only for http(s) and for privileged custom
|
||||
* schemes; a file:// renderer recompiled its whole bundle on every open. */
|
||||
export const RENDERER_SCHEME_PRIVILEGE: CustomScheme = {
|
||||
scheme: RENDERER_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
stream: true,
|
||||
codeCache: true,
|
||||
},
|
||||
}
|
||||
|
||||
export type RendererHost = 'docs' | 'sheets' | 'slides' | 'pdf' | 'markdown' | 'html'
|
||||
|
||||
/** Dev server URL when one is configured, otherwise the module's scheme URL; the
|
||||
* query is appended either way so a dev URL that already carries params stays valid. */
|
||||
export function rendererUrl(
|
||||
devUrl: string | undefined,
|
||||
host: RendererHost,
|
||||
query?: Record<string, string>,
|
||||
): string {
|
||||
const url = new URL(devUrl ?? `${RENDERER_SCHEME}://${host}/index.html`)
|
||||
for (const [key, value] of Object.entries(query ?? {})) url.searchParams.set(key, value)
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/** Map a scheme request onto a file under the host's renderer directory; null
|
||||
* for unknown hosts and for paths that escape the directory. */
|
||||
export function resolveRendererFile(
|
||||
roots: ReadonlyMap<string, string>,
|
||||
requestUrl: string,
|
||||
): string | null {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(requestUrl)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const root = roots.get(url.hostname)
|
||||
if (!root) return null
|
||||
let pathname: string
|
||||
try {
|
||||
pathname = decodeURIComponent(url.pathname)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const file = resolve(root, pathname.replace(/^\/+/, ''))
|
||||
return file === root || file.startsWith(root + sep) ? file : null
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
HEADLESS_EXIT,
|
||||
formatHeadlessEnvelope,
|
||||
headlessExitCode,
|
||||
headlessModuleFor,
|
||||
parseHeadlessExportArgv,
|
||||
pollUntilReady,
|
||||
runHeadlessRendererExport,
|
||||
} from '../src/headless-export'
|
||||
|
||||
/** argv as Electron delivers it: binary first, then the app's own switches. */
|
||||
const argv = (...rest: string[]): string[] => [
|
||||
'/Applications/GenOffice.app/Contents/MacOS/GenOffice',
|
||||
...rest,
|
||||
]
|
||||
|
||||
describe('parseHeadlessExportArgv', () => {
|
||||
it('reports no headless request when the flag is absent', () => {
|
||||
expect(parseHeadlessExportArgv(argv('/tmp/a.docx'))).toEqual({ kind: 'none' })
|
||||
})
|
||||
|
||||
it('parses the space-separated form', () => {
|
||||
const parsed = parseHeadlessExportArgv(
|
||||
argv('--headless-export', '/tmp/a.docx', '--to', 'pdf', '--out', '/tmp/a.pdf'),
|
||||
)
|
||||
expect(parsed).toEqual({
|
||||
kind: 'ok',
|
||||
request: { input: '/tmp/a.docx', targetFormat: 'pdf', outPath: '/tmp/a.pdf', json: false },
|
||||
})
|
||||
})
|
||||
|
||||
it('parses the --flag=value form and the --json switch', () => {
|
||||
const parsed = parseHeadlessExportArgv(
|
||||
argv('--headless-export=/tmp/a b.pptx', '--to=PDF', '--out=/tmp/out.pdf', '--json'),
|
||||
)
|
||||
expect(parsed).toEqual({
|
||||
kind: 'ok',
|
||||
request: { input: '/tmp/a b.pptx', targetFormat: 'pdf', outPath: '/tmp/out.pdf', json: true },
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a missing input, target or output', () => {
|
||||
expect(
|
||||
parseHeadlessExportArgv(argv('--headless-export', '--to', 'pdf', '--out', '/o.pdf')),
|
||||
).toMatchObject({
|
||||
kind: 'error',
|
||||
})
|
||||
expect(
|
||||
parseHeadlessExportArgv(argv('--headless-export', '/tmp/a.docx', '--out', '/o.pdf')),
|
||||
).toMatchObject({
|
||||
kind: 'error',
|
||||
})
|
||||
expect(
|
||||
parseHeadlessExportArgv(argv('--headless-export', '/tmp/a.docx', '--to', 'pdf')),
|
||||
).toMatchObject({
|
||||
kind: 'error',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a target format no module renders', () => {
|
||||
const parsed = parseHeadlessExportArgv(
|
||||
argv('--headless-export', '/tmp/a.docx', '--to', 'txt', '--out', '/o.txt'),
|
||||
)
|
||||
expect(parsed).toMatchObject({ kind: 'error', message: expect.stringContaining('txt') })
|
||||
})
|
||||
|
||||
it("accepts the non-pdf targets; input/target pairing is the host's job", () => {
|
||||
const parsed = parseHeadlessExportArgv(
|
||||
argv('--headless-export', '/tmp/a.html', '--to', 'DOCX', '--out', '/o.docx'),
|
||||
)
|
||||
expect(parsed).toMatchObject({ kind: 'ok', request: { targetFormat: 'docx' } })
|
||||
})
|
||||
|
||||
it('keeps the --json switch on the error branch so failures stay machine-readable', () => {
|
||||
const parsed = parseHeadlessExportArgv(argv('--headless-export', '--json'))
|
||||
expect(parsed).toEqual({ kind: 'error', json: true, message: expect.any(String) })
|
||||
})
|
||||
})
|
||||
|
||||
describe('headlessModuleFor', () => {
|
||||
it.each([
|
||||
['/x/a.docx', 'docs'],
|
||||
['/x/a.xlsx', 'sheets'],
|
||||
['/x/a.XLSM', 'sheets'],
|
||||
['/x/a.xls', 'sheets'],
|
||||
['/x/a.csv', 'sheets'],
|
||||
['/x/a.pptx', 'slides'],
|
||||
['/x/a.md', 'markdown'],
|
||||
['/x/a.markdown', 'markdown'],
|
||||
['/x/a.html', 'html'],
|
||||
['/x/a.htm', 'html'],
|
||||
])('routes %s to %s', (path, module) => {
|
||||
expect(headlessModuleFor(path)).toBe(module)
|
||||
})
|
||||
|
||||
it('returns null for an unsupported extension', () => {
|
||||
expect(headlessModuleFor('/x/a.pdf')).toBeNull()
|
||||
expect(headlessModuleFor('/x/a.doc')).toBeNull()
|
||||
expect(headlessModuleFor('/x/noext')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatHeadlessEnvelope', () => {
|
||||
it('prints one human sentence without --json', () => {
|
||||
const line = formatHeadlessEnvelope({ ok: true, input: '/a.docx', outPath: '/a.pdf' }, false)
|
||||
expect(line).toBe('Exported /a.docx to /a.pdf')
|
||||
expect(line).not.toContain('\n')
|
||||
})
|
||||
|
||||
it('prints exactly one JSON line with --json', () => {
|
||||
const line = formatHeadlessEnvelope({ ok: true, input: '/a.docx', outPath: '/a.pdf' }, true)
|
||||
expect(line.split('\n')).toHaveLength(1)
|
||||
expect(JSON.parse(line)).toEqual({
|
||||
status: 'ok',
|
||||
summary: 'Exported /a.docx to /a.pdf',
|
||||
output_path: '/a.pdf',
|
||||
})
|
||||
})
|
||||
|
||||
it('folds newlines out of a multi-line failure so the envelope stays one line', () => {
|
||||
const line = formatHeadlessEnvelope(
|
||||
{ ok: false, code: HEADLESS_EXIT.conversionFailure, message: 'boom\n at frame' },
|
||||
true,
|
||||
)
|
||||
expect(line.split('\n')).toHaveLength(1)
|
||||
expect(JSON.parse(line)).toEqual({
|
||||
status: 'error',
|
||||
summary: 'Export failed: boom at frame',
|
||||
error: 'boom at frame',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('headlessExitCode', () => {
|
||||
it('maps outcomes to the genoffice exit-code convention', () => {
|
||||
expect(headlessExitCode({ ok: true, input: '/a', outPath: '/b' })).toBe(0)
|
||||
expect(headlessExitCode({ ok: false, code: HEADLESS_EXIT.badArgs, message: 'x' })).toBe(1)
|
||||
expect(headlessExitCode({ ok: false, code: HEADLESS_EXIT.inputError, message: 'x' })).toBe(2)
|
||||
expect(
|
||||
headlessExitCode({ ok: false, code: HEADLESS_EXIT.conversionFailure, message: 'x' }),
|
||||
).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pollUntilReady', () => {
|
||||
it('returns as soon as the predicate is satisfied', async () => {
|
||||
let ticks = 0
|
||||
await pollUntilReady(() => ++ticks >= 3, 'never ready', { pollMs: 1, timeoutMs: 1000 })
|
||||
expect(ticks).toBe(3)
|
||||
})
|
||||
|
||||
it('gives up with the stall message rather than hanging forever', async () => {
|
||||
await expect(
|
||||
pollUntilReady(() => false, 'no document opened', { pollMs: 1, timeoutMs: 20 }),
|
||||
).rejects.toThrow('no document opened')
|
||||
})
|
||||
|
||||
it('evaluates a lazy stall message at give-up time', async () => {
|
||||
let state = 'loading'
|
||||
const failed = pollUntilReady(
|
||||
() => false,
|
||||
() => `stuck while ${state}`,
|
||||
{
|
||||
pollMs: 5,
|
||||
timeoutMs: 30,
|
||||
},
|
||||
)
|
||||
state = 'paginating'
|
||||
await expect(failed).rejects.toThrow('stuck while paginating')
|
||||
})
|
||||
})
|
||||
|
||||
describe('runHeadlessRendererExport', () => {
|
||||
it('reports ok when the export wrote a file', async () => {
|
||||
const exportPdf = vi.fn(() => Promise.resolve(true))
|
||||
await expect(
|
||||
runHeadlessRendererExport('/out.pdf', () => Promise.resolve(), exportPdf),
|
||||
).resolves.toEqual({ ok: true })
|
||||
expect(exportPdf).toHaveBeenCalledWith('/out.pdf')
|
||||
})
|
||||
|
||||
it('reports an error when the export produced nothing', async () => {
|
||||
await expect(
|
||||
runHeadlessRendererExport(
|
||||
'/out.pdf',
|
||||
() => Promise.resolve(),
|
||||
() => Promise.resolve(false),
|
||||
),
|
||||
).resolves.toEqual({ ok: false, error: 'export did not produce a file' })
|
||||
})
|
||||
|
||||
it('never throws: a failed wait becomes a report', async () => {
|
||||
const exportPdf = vi.fn(() => Promise.resolve(true))
|
||||
await expect(
|
||||
runHeadlessRendererExport(
|
||||
'/out.pdf',
|
||||
() => Promise.reject(new Error('no document opened')),
|
||||
exportPdf,
|
||||
),
|
||||
).resolves.toEqual({ ok: false, error: 'no document opened' })
|
||||
expect(exportPdf).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never throws: a failed export becomes a report', async () => {
|
||||
await expect(
|
||||
runHeadlessRendererExport(
|
||||
'/out.pdf',
|
||||
() => Promise.resolve(),
|
||||
() => Promise.reject(new Error('printToPDF failed')),
|
||||
),
|
||||
).resolves.toEqual({ ok: false, error: 'printToPDF failed' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { rendererUrl, resolveRendererFile } from '../src/renderer-scheme'
|
||||
|
||||
describe('rendererUrl', () => {
|
||||
it('builds the scheme URL with the query when no dev server is configured', () => {
|
||||
expect(rendererUrl(undefined, 'sheets', { mode: 'tab' })).toBe(
|
||||
'genoffice-app://sheets/index.html?mode=tab',
|
||||
)
|
||||
expect(rendererUrl(undefined, 'docs')).toBe('genoffice-app://docs/index.html')
|
||||
})
|
||||
|
||||
it('appends the query to a dev URL that already carries params', () => {
|
||||
expect(rendererUrl('http://localhost:5174/?x=1', 'sheets', { mode: 'tab' })).toBe(
|
||||
'http://localhost:5174/?x=1&mode=tab',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveRendererFile', () => {
|
||||
const roots = new Map([['sheets', '/out/sheets/renderer']])
|
||||
|
||||
it('maps the path under the host root', () => {
|
||||
expect(resolveRendererFile(roots, 'genoffice-app://sheets/index.html?mode=tab')).toBe(
|
||||
'/out/sheets/renderer/index.html',
|
||||
)
|
||||
expect(resolveRendererFile(roots, 'genoffice-app://sheets/assets/a%20b.js')).toBe(
|
||||
'/out/sheets/renderer/assets/a b.js',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps dot segments inside the root and rejects unknown hosts and unparsable URLs', () => {
|
||||
expect(resolveRendererFile(roots, 'genoffice-app://sheets/../../etc/passwd')).toBe(
|
||||
'/out/sheets/renderer/etc/passwd',
|
||||
)
|
||||
expect(resolveRendererFile(roots, 'genoffice-app://docs/index.html')).toBeNull()
|
||||
expect(resolveRendererFile(roots, 'not a url')).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user