@sparkelf/dsh-plus 0.2.9-alpha.83 → 0.2.9-alpha.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.i18n.yaml +2 -2
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/cordis.patch.yml +18 -0
- package/lib/apply-c_7SZFSh.js +1193 -0
- package/lib/apply.js +1 -1
- package/lib/bin.js +16 -317
- package/lib/types/apply.js +16 -0
- package/lib/types/capabilities.js +25 -36
- package/lib/types/manifest.d.ts +24 -0
- package/lib/types/manifest.js +51 -0
- package/lib/types/profile.d.ts +1 -0
- package/lib/types/profile.js +5 -1
- package/package.json +23 -5
- package/patches/office-system-soffice.patch +492 -0
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
diff --git a/packages/document/office-kit/src/index.ts b/packages/document/office-kit/src/index.ts
|
|
2
|
+
index e86a49f..0b93f01 100644
|
|
3
|
+
--- a/packages/document/office-kit/src/index.ts
|
|
4
|
+
+++ b/packages/document/office-kit/src/index.ts
|
|
5
|
+
@@ -12,6 +12,7 @@ import type {} from '@deepseek-ai/dsh-session'
|
|
6
|
+
import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
|
|
7
|
+
import { brandString } from '@deepseek-ai/dsh-brand'
|
|
8
|
+
import { resolveKitModule } from './locate.ts'
|
|
9
|
+
+import { resolveSystemSoffice, withSystemSoffice } from './system-soffice.ts'
|
|
10
|
+
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
|
11
|
+
import { OfficeKitError } from './errors.ts'
|
|
12
|
+
import { OfficeKitGeneration, type OfficeSourceKey } from './identity.ts'
|
|
13
|
+
@@ -80,6 +81,12 @@ export interface Config {
|
|
14
|
+
maxFontFileBytes: number
|
|
15
|
+
/** Maximum original font bytes loaded for a conversion. */
|
|
16
|
+
maxLoadedFontBytes: number
|
|
17
|
+
+ /** PDF conversion backend; `auto` prefers system LibreOffice on Linux, `kit` forces LibreOfficeKit. */
|
|
18
|
+
+ backend: 'auto' | 'kit' | 'system'
|
|
19
|
+
+ /** Explicit system LibreOffice executable; omission searches PATH and conventional locations. */
|
|
20
|
+
+ sofficePath?: string
|
|
21
|
+
+ /** Absolute profile directory shared by serialized system LibreOffice runs. */
|
|
22
|
+
+ systemProfileDirectory: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Deployment defaults resolved before provider construction. */
|
|
26
|
+
@@ -106,6 +113,9 @@ export const Config: z<Partial<Config>, Config> = z.object({
|
|
27
|
+
maxFontFiles: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(20_000),
|
|
28
|
+
maxFontFileBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(256 * 1024 * 1024),
|
|
29
|
+
maxLoadedFontBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024),
|
|
30
|
+
+ backend: z.union(['auto', 'kit', 'system']).default('auto'),
|
|
31
|
+
+ sofficePath: z.string().min(1).extra('default', undefined),
|
|
32
|
+
+ systemProfileDirectory: z.string().min(1).default(dshHomePath('office-kit', 'system-soffice-profile')),
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
/** Kit operations loaded from the provider's Kit entry. */
|
|
36
|
+
@@ -138,6 +148,7 @@ export class OfficeKit extends TypertRemoteService {
|
|
37
|
+
private readonly options: Omit<ConverterOptions, 'resolveEnginePackage'>
|
|
38
|
+
private loadedKit?: Promise<LoadedKit>
|
|
39
|
+
private readonly reportedKitFailures = new Set<string>()
|
|
40
|
+
+ private reportedSystemBackend = false
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param ctx - owning Host context.
|
|
44
|
+
@@ -148,6 +159,7 @@ export class OfficeKit extends TypertRemoteService {
|
|
45
|
+
if (config.fontDirectories?.some(path => !isAbsolute(path))) throw new Error('fontDirectories must contain absolute paths.')
|
|
46
|
+
if (config.maxSourceBytes < config.maxInputBytes) throw new Error('maxSourceBytes must be at least maxInputBytes.')
|
|
47
|
+
if (!isAbsolute(config.outputDirectory)) throw new Error('outputDirectory must be an absolute path.')
|
|
48
|
+
+ if (!isAbsolute(config.systemProfileDirectory)) throw new Error('systemProfileDirectory must be an absolute path.')
|
|
49
|
+
const { fontDirectories, fontFallbacks, timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution,
|
|
50
|
+
maxArchiveEntries, maxUncompressedBytes, maxFontFiles, maxFontFileBytes, maxLoadedFontBytes } = config
|
|
51
|
+
this.options = { timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution,
|
|
52
|
+
@@ -331,6 +343,38 @@ export class OfficeKit extends TypertRemoteService {
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
+ /**
|
|
57
|
+
+ * Prefer the system LibreOffice executable on Linux so PDF previews avoid the WASM engine's per-render startup.
|
|
58
|
+
+ * A missing executable keeps the Kit backend unless configuration requires the system backend.
|
|
59
|
+
+ * @param converter - Kit-backed converter for every non-PDF operation.
|
|
60
|
+
+ * @returns the original converter, or a wrapper whose PDF render uses system LibreOffice.
|
|
61
|
+
+ */
|
|
62
|
+
+ private async selectBackend(converter: Converter): Promise<Converter> {
|
|
63
|
+
+ if (this.config.backend === 'kit') return converter
|
|
64
|
+
+ if (process.platform !== 'linux') {
|
|
65
|
+
+ if (this.config.backend === 'system') {
|
|
66
|
+
+ throw new OfficeKitError('unavailable', 'The system LibreOffice backend is only supported on Linux.')
|
|
67
|
+
+ }
|
|
68
|
+
+ return converter
|
|
69
|
+
+ }
|
|
70
|
+
+ const executable = await resolveSystemSoffice(this.config.sofficePath)
|
|
71
|
+
+ if (executable === undefined) {
|
|
72
|
+
+ if (this.config.backend === 'system') {
|
|
73
|
+
+ throw new OfficeKitError('unavailable', 'System LibreOffice (soffice) was not found.')
|
|
74
|
+
+ }
|
|
75
|
+
+ return converter
|
|
76
|
+
+ }
|
|
77
|
+
+ if (!this.reportedSystemBackend) {
|
|
78
|
+
+ this.reportedSystemBackend = true
|
|
79
|
+
+ this.ctx.logger.info(`office-kit: rendering PDFs with system LibreOffice at ${executable}`)
|
|
80
|
+
+ }
|
|
81
|
+
+ return withSystemSoffice(converter, {
|
|
82
|
+
+ executable,
|
|
83
|
+
+ profileDirectory: this.config.systemProfileDirectory,
|
|
84
|
+
+ timeoutMs: this.config.timeoutMs,
|
|
85
|
+
+ })
|
|
86
|
+
+ }
|
|
87
|
+
+
|
|
88
|
+
/**
|
|
89
|
+
* Locate and import Kit for a converter. A successful import is reused for the provider lifetime; a missing or
|
|
90
|
+
* unloadable Kit rejects as `unavailable` without being retained, so the next converter request locates Kit again.
|
|
91
|
+
@@ -376,8 +420,10 @@ export class OfficeKit extends TypertRemoteService {
|
|
92
|
+
let directory: string | undefined
|
|
93
|
+
try {
|
|
94
|
+
if (slot.converter === undefined) {
|
|
95
|
+
- slot.converter = this.loadKit().then(({ createConverter, resolveEnginePackage }) =>
|
|
96
|
+
- createConverter({ ...this.options, resolveEnginePackage })).catch((error: unknown) => {
|
|
97
|
+
+ slot.converter = this.loadKit().then(async ({ createConverter, resolveEnginePackage }) => {
|
|
98
|
+
+ const converter = await createConverter({ ...this.options, resolveEnginePackage })
|
|
99
|
+
+ return this.selectBackend(converter)
|
|
100
|
+
+ }).catch((error: unknown) => {
|
|
101
|
+
delete slot.converter
|
|
102
|
+
throw error
|
|
103
|
+
})
|
|
104
|
+
diff --git a/packages/document/office-kit/src/system-soffice.ts b/packages/document/office-kit/src/system-soffice.ts
|
|
105
|
+
new file mode 100644
|
|
106
|
+
index 0000000..6faaaca
|
|
107
|
+
--- /dev/null
|
|
108
|
+
+++ b/packages/document/office-kit/src/system-soffice.ts
|
|
109
|
+
@@ -0,0 +1,210 @@
|
|
110
|
+
+/** System LibreOffice PDF rendering for Linux hosts without a native LibreOfficeKit engine. */
|
|
111
|
+
+import { spawn } from 'node:child_process'
|
|
112
|
+
+import { constants } from 'node:fs'
|
|
113
|
+
+import { access, copyFile, mkdir, mkdtemp, readdir, rm, stat } from 'node:fs/promises'
|
|
114
|
+
+import { tmpdir } from 'node:os'
|
|
115
|
+
+import { join } from 'node:path'
|
|
116
|
+
+import { pathToFileURL } from 'node:url'
|
|
117
|
+
+import type { Converter, RenderResult } from '@deepseek-ai/libreoffice-kit'
|
|
118
|
+
+
|
|
119
|
+
+/** One system LibreOffice installation and the profile directory its serialized runs share. */
|
|
120
|
+
+export interface SystemSofficeOptions {
|
|
121
|
+
+ /** Absolute `soffice` executable. */
|
|
122
|
+
+ readonly executable: string
|
|
123
|
+
+ /** Absolute user-installation profile directory; one profile serves one process at a time. */
|
|
124
|
+
+ readonly profileDirectory: string
|
|
125
|
+
+ /** Per-conversion deadline, including process startup. */
|
|
126
|
+
+ readonly timeoutMs: number
|
|
127
|
+
+ /** Extra environment values for the child process. */
|
|
128
|
+
+ readonly env?: NodeJS.ProcessEnv
|
|
129
|
+
+}
|
|
130
|
+
+
|
|
131
|
+
+/** Error carrying the published conversion code the provider maps to its own failures. */
|
|
132
|
+
+export class SystemSofficeError extends Error {
|
|
133
|
+
+ readonly code: string
|
|
134
|
+
+
|
|
135
|
+
+ /**
|
|
136
|
+
+ * @param code - Published conversion failure category.
|
|
137
|
+
+ * @param message - User-facing failure description.
|
|
138
|
+
+ * @param options - Standard error options.
|
|
139
|
+
+ */
|
|
140
|
+
+ constructor(code: string, message: string, options?: ErrorOptions) {
|
|
141
|
+
+ super(message, options)
|
|
142
|
+
+ this.name = 'SystemSofficeError'
|
|
143
|
+
+ this.code = code
|
|
144
|
+
+ }
|
|
145
|
+
+}
|
|
146
|
+
+
|
|
147
|
+
+const SOFFICE_NAMES = ['soffice', 'libreoffice'] as const
|
|
148
|
+
+const SOFFICE_LOCATIONS = ['/usr/bin', '/usr/local/bin', '/opt/libreoffice/program'] as const
|
|
149
|
+
+
|
|
150
|
+
+/**
|
|
151
|
+
+ * Resolve a system LibreOffice executable without a shell.
|
|
152
|
+
+ * @param explicit - Configured absolute or PATH-resolved executable.
|
|
153
|
+
+ * @returns absolute executable path, or undefined when none is installed.
|
|
154
|
+
+ */
|
|
155
|
+
+export async function resolveSystemSoffice(explicit?: string): Promise<string | undefined> {
|
|
156
|
+
+ if (explicit !== undefined) {
|
|
157
|
+
+ try {
|
|
158
|
+
+ await access(explicit, constants.X_OK)
|
|
159
|
+
+ return explicit
|
|
160
|
+
+ } catch {
|
|
161
|
+
+ return undefined
|
|
162
|
+
+ }
|
|
163
|
+
+ }
|
|
164
|
+
+ for (const directory of SOFFICE_LOCATIONS) {
|
|
165
|
+
+ for (const name of SOFFICE_NAMES) {
|
|
166
|
+
+ const candidate = join(directory, name)
|
|
167
|
+
+ try {
|
|
168
|
+
+ await access(candidate, constants.X_OK)
|
|
169
|
+
+ return candidate
|
|
170
|
+
+ } catch {
|
|
171
|
+
+ // Try the next conventional location.
|
|
172
|
+
+ }
|
|
173
|
+
+ }
|
|
174
|
+
+ }
|
|
175
|
+
+ for (const directory of (process.env.PATH ?? '').split(':').filter(Boolean)) {
|
|
176
|
+
+ for (const name of SOFFICE_NAMES) {
|
|
177
|
+
+ const candidate = join(directory, name)
|
|
178
|
+
+ try {
|
|
179
|
+
+ await access(candidate, constants.X_OK)
|
|
180
|
+
+ return candidate
|
|
181
|
+
+ } catch {
|
|
182
|
+
+ // Try the next PATH entry.
|
|
183
|
+
+ }
|
|
184
|
+
+ }
|
|
185
|
+
+ }
|
|
186
|
+
+ return undefined
|
|
187
|
+
+}
|
|
188
|
+
+
|
|
189
|
+
+/** One serialized queue per profile: LibreOffice cannot serve two processes from one user profile. */
|
|
190
|
+
+class SerialQueue {
|
|
191
|
+
+ private tail: Promise<unknown> = Promise.resolve()
|
|
192
|
+
+
|
|
193
|
+
+ /** Wait for every queued and active turn to settle. */
|
|
194
|
+
+ idle(): Promise<void> {
|
|
195
|
+
+ return this.tail.then(() => undefined)
|
|
196
|
+
+ }
|
|
197
|
+
+
|
|
198
|
+
+ run<T>(task: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
199
|
+
+ signal?.throwIfAborted()
|
|
200
|
+
+ const turn = this.tail.then(() => {
|
|
201
|
+
+ signal?.throwIfAborted()
|
|
202
|
+
+ return task()
|
|
203
|
+
+ })
|
|
204
|
+
+ this.tail = turn.catch(() => undefined)
|
|
205
|
+
+ return turn
|
|
206
|
+
+ }
|
|
207
|
+
+}
|
|
208
|
+
+
|
|
209
|
+
+const queues = new Map<string, SerialQueue>()
|
|
210
|
+
+
|
|
211
|
+
+function queueFor(profileDirectory: string): SerialQueue {
|
|
212
|
+
+ let queue = queues.get(profileDirectory)
|
|
213
|
+
+ if (queue === undefined) {
|
|
214
|
+
+ queue = new SerialQueue()
|
|
215
|
+
+ queues.set(profileDirectory, queue)
|
|
216
|
+
+ }
|
|
217
|
+
+ return queue
|
|
218
|
+
+}
|
|
219
|
+
+
|
|
220
|
+
+/**
|
|
221
|
+
+ * Wrap a Kit converter so PDF rendering uses system LibreOffice while every other operation stays on the
|
|
222
|
+
+ * original engine. The wrapper keeps the same serial render contract and reports a native backend.
|
|
223
|
+
+ * @param base - Converter created by LibreOfficeKit.
|
|
224
|
+
+ * @param options - Executable, profile, and deadline for system rendering.
|
|
225
|
+
+ * @returns converter whose `render()` runs system LibreOffice.
|
|
226
|
+
+ */
|
|
227
|
+
+export function withSystemSoffice<T extends Converter>(base: T, options: SystemSofficeOptions): T {
|
|
228
|
+
+ const queue = queueFor(options.profileDirectory)
|
|
229
|
+
+ const render = createSystemRender(options, queue)
|
|
230
|
+
+ return new Proxy(base, {
|
|
231
|
+
+ get(target, property) {
|
|
232
|
+
+ if (property === 'render') return render
|
|
233
|
+
+ if (property === 'backend') return 'native'
|
|
234
|
+
+ if (property === 'dispose') return async () => { await queue.idle(); await target.dispose() }
|
|
235
|
+
+ const value: unknown = Reflect.get(target, property, target)
|
|
236
|
+
+ return typeof value === 'function' ? value.bind(target) : value
|
|
237
|
+
+ },
|
|
238
|
+
+ }) as T
|
|
239
|
+
+}
|
|
240
|
+
+
|
|
241
|
+
+function createSystemRender(options: SystemSofficeOptions, queue: SerialQueue) {
|
|
242
|
+
+ return (request: { readonly inputPath: string; readonly outputPath: string }, signal?: AbortSignal): Promise<RenderResult> =>
|
|
243
|
+
+ queue.run(async () => {
|
|
244
|
+
+ signal?.throwIfAborted()
|
|
245
|
+
+ await mkdir(options.profileDirectory, { recursive: true, mode: 0o700 })
|
|
246
|
+
+ await assertFreshOutput(request.outputPath)
|
|
247
|
+
+ const scratch = await mkdtemp(join(tmpdir(), 'dsh-office-system-'))
|
|
248
|
+
+ try {
|
|
249
|
+
+ const args = [
|
|
250
|
+
+ '--headless', '--norestore', '--nolockcheck', '--nodefault', '--nofirststartwizard', '--nologo',
|
|
251
|
+
+ `-env:UserInstallation=${pathToFileURL(options.profileDirectory).href}`,
|
|
252
|
+
+ '--convert-to', 'pdf', '--outdir', scratch, request.inputPath,
|
|
253
|
+
+ ]
|
|
254
|
+
+ await runSoffice(options, args, signal)
|
|
255
|
+
+ const produced = (await readdir(scratch)).filter(name => name.toLowerCase().endsWith('.pdf'))
|
|
256
|
+
+ if (produced.length !== 1) {
|
|
257
|
+
+ throw new SystemSofficeError('invalid-output', `LibreOffice produced ${produced.length} PDF files.`)
|
|
258
|
+
+ }
|
|
259
|
+
+ await copyFile(join(scratch, produced[0] as string), request.outputPath, constants.COPYFILE_EXCL)
|
|
260
|
+
+ return { backend: 'native', missingFonts: [] }
|
|
261
|
+
+ } finally {
|
|
262
|
+
+ await rm(scratch, { recursive: true, force: true })
|
|
263
|
+
+ }
|
|
264
|
+
+ }, signal)
|
|
265
|
+
+}
|
|
266
|
+
+
|
|
267
|
+
+/** Reject an output path that already exists, matching the Kit render contract. */
|
|
268
|
+
+async function assertFreshOutput(outputPath: string): Promise<void> {
|
|
269
|
+
+ try {
|
|
270
|
+
+ await stat(outputPath)
|
|
271
|
+
+ } catch (error) {
|
|
272
|
+
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
|
|
273
|
+
+ throw error
|
|
274
|
+
+ }
|
|
275
|
+
+ throw new SystemSofficeError('invalid-output', `Output path already exists: ${outputPath}`)
|
|
276
|
+
+}
|
|
277
|
+
+
|
|
278
|
+
+function runSoffice(options: SystemSofficeOptions, args: readonly string[], signal?: AbortSignal): Promise<void> {
|
|
279
|
+
+ return new Promise<void>((resolve, reject) => {
|
|
280
|
+
+ const child = spawn(options.executable, args, {
|
|
281
|
+
+ stdio: 'ignore',
|
|
282
|
+
+ detached: process.platform !== 'win32',
|
|
283
|
+
+ env: { ...process.env, ...options.env },
|
|
284
|
+
+ })
|
|
285
|
+
+ let settled = false
|
|
286
|
+
+ const finish = (error?: Error): void => {
|
|
287
|
+
+ if (settled) return
|
|
288
|
+
+ settled = true
|
|
289
|
+
+ clearTimeout(timer)
|
|
290
|
+
+ signal?.removeEventListener('abort', abort)
|
|
291
|
+
+ if (error === undefined) resolve()
|
|
292
|
+
+ else reject(error)
|
|
293
|
+
+ }
|
|
294
|
+
+ const kill = (): void => {
|
|
295
|
+
+ try {
|
|
296
|
+
+ if (child.pid !== undefined && process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL')
|
|
297
|
+
+ else child.kill('SIGKILL')
|
|
298
|
+
+ } catch {
|
|
299
|
+
+ // The process already exited.
|
|
300
|
+
+ }
|
|
301
|
+
+ }
|
|
302
|
+
+ const timer = setTimeout(() => {
|
|
303
|
+
+ kill()
|
|
304
|
+
+ finish(new SystemSofficeError('timeout', `LibreOffice conversion exceeded ${options.timeoutMs} ms.`))
|
|
305
|
+
+ }, options.timeoutMs)
|
|
306
|
+
+ const abort = (): void => {
|
|
307
|
+
+ kill()
|
|
308
|
+
+ const reason: unknown = signal?.reason
|
|
309
|
+
+ finish(reason instanceof Error ? reason : new SystemSofficeError('cancelled', 'LibreOffice conversion cancelled.'))
|
|
310
|
+
+ }
|
|
311
|
+
+ signal?.addEventListener('abort', abort, { once: true })
|
|
312
|
+
+ child.once('error', (error) => {
|
|
313
|
+
+ finish(new SystemSofficeError('unavailable', `LibreOffice could not start: ${error.message}`, { cause: error }))
|
|
314
|
+
+ })
|
|
315
|
+
+ child.once('exit', (code, signalName) => {
|
|
316
|
+
+ finish(code === 0 ? undefined : new SystemSofficeError('failed', `LibreOffice exited with ${signalName ?? String(code)}.`))
|
|
317
|
+
+ })
|
|
318
|
+
+ })
|
|
319
|
+
+}
|
|
320
|
+
|
|
321
|
+
diff --git a/packages/document/office-kit/tests/system-soffice.spec.ts b/packages/document/office-kit/tests/system-soffice.spec.ts
|
|
322
|
+
new file mode 100644
|
|
323
|
+
index 0000000..b5bf5a5
|
|
324
|
+
--- /dev/null
|
|
325
|
+
+++ b/packages/document/office-kit/tests/system-soffice.spec.ts
|
|
326
|
+
@@ -0,0 +1,165 @@
|
|
327
|
+
+/** System LibreOffice PDF rendering: serialization, output ownership, deadlines, and Kit delegation. */
|
|
328
|
+
+import { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
|
329
|
+
+import { tmpdir } from 'node:os'
|
|
330
|
+
+import { join } from 'node:path'
|
|
331
|
+
+import type { Converter } from '@deepseek-ai/libreoffice-kit'
|
|
332
|
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
333
|
+
+import { resolveSystemSoffice, withSystemSoffice } from '../src/system-soffice.ts'
|
|
334
|
+
+
|
|
335
|
+
+const POSIX = process.platform !== 'win32'
|
|
336
|
+
+const roots: string[] = []
|
|
337
|
+
+
|
|
338
|
+
+async function scratch(): Promise<string> {
|
|
339
|
+
+ const root = await mkdtemp(join(tmpdir(), 'dsh-system-soffice-'))
|
|
340
|
+
+ roots.push(root)
|
|
341
|
+
+ return root
|
|
342
|
+
+}
|
|
343
|
+
+
|
|
344
|
+
+async function fakeSoffice(body: string): Promise<string> {
|
|
345
|
+
+ const root = await scratch()
|
|
346
|
+
+ const path = join(root, 'soffice')
|
|
347
|
+
+ await writeFile(path, `#!/usr/bin/env node\n${body}`)
|
|
348
|
+
+ await chmod(path, 0o755)
|
|
349
|
+
+ return path
|
|
350
|
+
+}
|
|
351
|
+
+
|
|
352
|
+
+const CONVERT = `
|
|
353
|
+
+const fs = require('node:fs')
|
|
354
|
+
+const path = require('node:path')
|
|
355
|
+
+const args = process.argv.slice(2)
|
|
356
|
+
+const outdir = args[args.indexOf('--outdir') + 1]
|
|
357
|
+
+const input = args[args.length - 1]
|
|
358
|
+
+const delay = Number(process.env.FAKE_DELAY || 0)
|
|
359
|
+
+const lock = process.env.FAKE_LOCK
|
|
360
|
+
+if (lock !== undefined) {
|
|
361
|
+
+ try { fs.writeFileSync(lock, 'held', { flag: 'wx' }) }
|
|
362
|
+
+ catch { fs.appendFileSync(lock + '.overlap', '1') }
|
|
363
|
+
+}
|
|
364
|
+
+setTimeout(() => {
|
|
365
|
+
+ fs.writeFileSync(path.join(outdir, path.basename(input).replace(/\\.[^.]+$/, '.pdf')), '%PDF-1.7\\n')
|
|
366
|
+
+ if (lock !== undefined) fs.rmSync(lock, { force: true })
|
|
367
|
+
+}, delay)
|
|
368
|
+
+`
|
|
369
|
+
+
|
|
370
|
+
+function baseConverter(): Converter {
|
|
371
|
+
+ return {
|
|
372
|
+
+ backend: 'wasm',
|
|
373
|
+
+ render: vi.fn<Converter['render']>().mockRejectedValue(new Error('Kit render must not run')),
|
|
374
|
+
+ renderImages: vi.fn<Converter['renderImages']>().mockResolvedValue({ images: [] } as never),
|
|
375
|
+
+ convert: vi.fn<Converter['convert']>().mockRejectedValue(new Error('unexpected convert')),
|
|
376
|
+
+ recalculate: vi.fn<Converter['recalculate']>().mockRejectedValue(new Error('unexpected recalculate')),
|
|
377
|
+
+ dispose: vi.fn<Converter['dispose']>().mockResolvedValue(undefined),
|
|
378
|
+
+ }
|
|
379
|
+
+}
|
|
380
|
+
+
|
|
381
|
+
+afterEach(async () => {
|
|
382
|
+
+ await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })))
|
|
383
|
+
+})
|
|
384
|
+
+
|
|
385
|
+
+describe.skipIf(!POSIX)('system LibreOffice backend', () => {
|
|
386
|
+
+ it('resolves an explicit executable and reports a missing one', async () => {
|
|
387
|
+
+ const executable = await fakeSoffice('')
|
|
388
|
+
+ await expect(resolveSystemSoffice(executable)).resolves.toBe(executable)
|
|
389
|
+
+ await expect(resolveSystemSoffice(join(executable, 'missing'))).resolves.toBeUndefined()
|
|
390
|
+
+ })
|
|
391
|
+
+
|
|
392
|
+
+ it('renders a PDF and delegates every other Kit operation', async () => {
|
|
393
|
+
+ const root = await scratch()
|
|
394
|
+
+ const executable = await fakeSoffice(CONVERT)
|
|
395
|
+
+ const base = baseConverter()
|
|
396
|
+
+ const converter = withSystemSoffice(base, {
|
|
397
|
+
+ executable,
|
|
398
|
+
+ profileDirectory: join(root, 'profile'),
|
|
399
|
+
+ timeoutMs: 5_000,
|
|
400
|
+
+ })
|
|
401
|
+
+ const outputPath = join(root, 'output.pdf')
|
|
402
|
+
+ const result = await converter.render({ inputPath: join(root, 'input.docx'), outputPath })
|
|
403
|
+
+ expect(result).toEqual({ backend: 'native', missingFonts: [] })
|
|
404
|
+
+ expect(await readFile(outputPath, 'utf8')).toContain('%PDF-1.7')
|
|
405
|
+
+ await converter.renderImages({} as never)
|
|
406
|
+
+ expect(base.renderImages).toHaveBeenCalledTimes(1)
|
|
407
|
+
+ expect(base.render).not.toHaveBeenCalled()
|
|
408
|
+
+ expect(converter.backend).toBe('native')
|
|
409
|
+
+ })
|
|
410
|
+
+
|
|
411
|
+
+ it('serializes concurrent renders that share one profile', async () => {
|
|
412
|
+
+ const root = await scratch()
|
|
413
|
+
+ const executable = await fakeSoffice(CONVERT)
|
|
414
|
+
+ const lock = join(root, 'soffice.lock')
|
|
415
|
+
+ const converter = withSystemSoffice(baseConverter(), {
|
|
416
|
+
+ executable,
|
|
417
|
+
+ profileDirectory: join(root, 'profile'),
|
|
418
|
+
+ timeoutMs: 10_000,
|
|
419
|
+
+ env: { FAKE_DELAY: '250', FAKE_LOCK: lock },
|
|
420
|
+
+ })
|
|
421
|
+
+ await Promise.all([0, 1, 2].map(async (index) => {
|
|
422
|
+
+ await converter.render({ inputPath: join(root, `input-${index}.docx`), outputPath: join(root, `output-${index}.pdf`) })
|
|
423
|
+
+ }))
|
|
424
|
+
+ for (const index of [0, 1, 2]) {
|
|
425
|
+
+ await expect(stat(join(root, `output-${index}.pdf`))).resolves.toBeDefined()
|
|
426
|
+
+ }
|
|
427
|
+
+ await expect(stat(`${lock}.overlap`)).rejects.toMatchObject({ code: 'ENOENT' })
|
|
428
|
+
+ })
|
|
429
|
+
+
|
|
430
|
+
+ it('rejects with the published timeout code and kills the process', async () => {
|
|
431
|
+
+ const root = await scratch()
|
|
432
|
+
+ const executable = await fakeSoffice(CONVERT)
|
|
433
|
+
+ const converter = withSystemSoffice(baseConverter(), {
|
|
434
|
+
+ executable,
|
|
435
|
+
+ profileDirectory: join(root, 'profile'),
|
|
436
|
+
+ timeoutMs: 250,
|
|
437
|
+
+ env: { FAKE_DELAY: '5000' },
|
|
438
|
+
+ })
|
|
439
|
+
+ await expect(converter.render({ inputPath: join(root, 'input.docx'), outputPath: join(root, 'output.pdf') }))
|
|
440
|
+
+ .rejects.toMatchObject({ code: 'timeout' })
|
|
441
|
+
+ await expect(stat(join(root, 'output.pdf'))).rejects.toMatchObject({ code: 'ENOENT' })
|
|
442
|
+
+ })
|
|
443
|
+
+
|
|
444
|
+
+ it('rejects an already existing output path before starting LibreOffice', async () => {
|
|
445
|
+
+ const root = await scratch()
|
|
446
|
+
+ const executable = await fakeSoffice(CONVERT)
|
|
447
|
+
+ const outputPath = join(root, 'output.pdf')
|
|
448
|
+
+ await writeFile(outputPath, 'existing')
|
|
449
|
+
+ const converter = withSystemSoffice(baseConverter(), {
|
|
450
|
+
+ executable,
|
|
451
|
+
+ profileDirectory: join(root, 'profile'),
|
|
452
|
+
+ timeoutMs: 5_000,
|
|
453
|
+
+ })
|
|
454
|
+
+ await expect(converter.render({ inputPath: join(root, 'input.docx'), outputPath }))
|
|
455
|
+
+ .rejects.toMatchObject({ code: 'invalid-output' })
|
|
456
|
+
+ await expect(readFile(outputPath, 'utf8')).resolves.toBe('existing')
|
|
457
|
+
+ })
|
|
458
|
+
+
|
|
459
|
+
+ it('reports a missing PDF as invalid output', async () => {
|
|
460
|
+
+ const root = await scratch()
|
|
461
|
+
+ const executable = await fakeSoffice('process.exit(0)')
|
|
462
|
+
+ const converter = withSystemSoffice(baseConverter(), {
|
|
463
|
+
+ executable,
|
|
464
|
+
+ profileDirectory: join(root, 'profile'),
|
|
465
|
+
+ timeoutMs: 5_000,
|
|
466
|
+
+ })
|
|
467
|
+
+ await expect(converter.render({ inputPath: join(root, 'input.docx'), outputPath: join(root, 'output.pdf') }))
|
|
468
|
+
+ .rejects.toMatchObject({ code: 'invalid-output' })
|
|
469
|
+
+ })
|
|
470
|
+
+
|
|
471
|
+
+ it('honors cancellation before the queued render starts', async () => {
|
|
472
|
+
+ const root = await scratch()
|
|
473
|
+
+ const executable = await fakeSoffice(CONVERT)
|
|
474
|
+
+ const converter = withSystemSoffice(baseConverter(), {
|
|
475
|
+
+ executable,
|
|
476
|
+
+ profileDirectory: join(root, 'profile'),
|
|
477
|
+
+ timeoutMs: 10_000,
|
|
478
|
+
+ env: { FAKE_DELAY: '250' },
|
|
479
|
+
+ })
|
|
480
|
+
+ const first = converter.render({ inputPath: join(root, 'first.docx'), outputPath: join(root, 'first.pdf') })
|
|
481
|
+
+ const controller = new AbortController()
|
|
482
|
+
+ const second = converter.render(
|
|
483
|
+
+ { inputPath: join(root, 'second.docx'), outputPath: join(root, 'second.pdf') },
|
|
484
|
+
+ controller.signal,
|
|
485
|
+
+ )
|
|
486
|
+
+ controller.abort(new Error('cancelled by test'))
|
|
487
|
+
+ await expect(second).rejects.toThrow('cancelled by test')
|
|
488
|
+
+ await first
|
|
489
|
+
+ await expect(stat(join(root, 'second.pdf'))).rejects.toMatchObject({ code: 'ENOENT' })
|
|
490
|
+
+ })
|
|
491
|
+
+})
|
|
492
|
+
|