@deepseek-ai/dsh-office-kit 0.0.0-stage → 0.2.2-rc.2
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/LICENSE +21 -0
- package/README.i18n.yaml +37 -0
- package/README.md +128 -2
- package/README.zh.md +129 -0
- package/lib/index.js +1234 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +346 -0
- package/lib/typert.remote-client.d.ts +30 -0
- package/lib/typert.remote-client.d.ts.map +1 -0
- package/lib/typert.remote-client.js +162 -0
- package/lib/types/errors.d.ts +13 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +15 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +27 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +23 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +157 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +459 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/locate.d.ts +48 -0
- package/lib/types/locate.d.ts.map +1 -0
- package/lib/types/locate.js +65 -0
- package/lib/types/locate.js.map +1 -0
- package/lib/types/output.d.ts +26 -0
- package/lib/types/output.d.ts.map +1 -0
- package/lib/types/output.js +75 -0
- package/lib/types/output.js.map +1 -0
- package/lib/types/outputs.d.ts +75 -0
- package/lib/types/outputs.d.ts.map +1 -0
- package/lib/types/outputs.js +198 -0
- package/lib/types/outputs.js.map +1 -0
- package/lib/types/queue.d.ts +106 -0
- package/lib/types/queue.d.ts.map +1 -0
- package/lib/types/queue.js +276 -0
- package/lib/types/queue.js.map +1 -0
- package/lib/types/types.d.ts +151 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +2 -0
- package/lib/types/types.js.map +1 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +68 -3
- package/src/errors.ts +15 -0
- package/src/identity.ts +31 -0
- package/src/index.ts +484 -0
- package/src/locate.ts +93 -0
- package/src/output.ts +69 -0
- package/src/outputs.ts +218 -0
- package/src/queue.ts +316 -0
- package/src/types.ts +168 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.js","sourceRoot":"","sources":["../../src/identity.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,OAAO,EAAE,WAAW,EAAgB,MAAM,wBAAwB,CAAA;AAIlE;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,GAAW,IAAqB,OAAO,WAAW,CAAkB,GAAG,CAAC,CAAA,CAAC,CAAC;AAI1G;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa;IAC/C,OAAO,WAAW,CAAsB,KAAK,CAAC,CAAA;AAChD,CAAC;AAID;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa,IAAkB,OAAO,WAAW,CAAe,KAAK,CAAC,CAAA,CAAC,CAAC"}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import z from '@deepseek-ai/schemastery';
|
|
3
|
+
import type { WorkspaceFileScope } from '@deepseek-ai/dsh-api-workspace-files';
|
|
4
|
+
import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
|
5
|
+
import { OfficeKitGeneration } from './identity.ts';
|
|
6
|
+
import type { OfficeConversionRequest, OfficeFileResult, OfficeImagesRequest, OfficeImagesResult, OfficeKitRequest, OfficeKitResult, OfficeKitPriority, OfficeRecalculationRequest, RenderedDocumentBytes } from './types.ts';
|
|
7
|
+
export * from './errors.ts';
|
|
8
|
+
export * from './identity.ts';
|
|
9
|
+
export * from './types.ts';
|
|
10
|
+
declare module '@deepseek-ai/cordis' {
|
|
11
|
+
interface Context {
|
|
12
|
+
/** Shared Office rendering, conversion, recalculation, and authorized workspace-file previews. */
|
|
13
|
+
officeKit: OfficeKit;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Provider concurrency and kit rendering/font configuration. */
|
|
17
|
+
export interface Config {
|
|
18
|
+
/** Maximum simultaneous conversions; queued callers remain cancellable. */
|
|
19
|
+
maxConcurrentConversions: number;
|
|
20
|
+
/** Maximum metadata-only jobs awaiting source admission. */
|
|
21
|
+
maxQueuedJobs: number;
|
|
22
|
+
/** Maximum outstanding conversion readers. */
|
|
23
|
+
maxReaders: number;
|
|
24
|
+
/** Maximum reserved bytes across admitted source reads and conversions. */
|
|
25
|
+
maxSourceBytes: number;
|
|
26
|
+
/** Maximum concurrent background jobs; zero refuses speculative work. */
|
|
27
|
+
maxBackgroundConversions: number;
|
|
28
|
+
/** Maximum retained content-addressed outputs. */
|
|
29
|
+
maxCachedEntries: number;
|
|
30
|
+
/** Maximum retained output bytes. */
|
|
31
|
+
maxCachedBytes: number;
|
|
32
|
+
/** Maximum retained source-version aliases to cached content. */
|
|
33
|
+
maxSourceEntries: number;
|
|
34
|
+
/** Absolute directory for converted and recalculated files, with one subdirectory per Session. */
|
|
35
|
+
outputDirectory: string;
|
|
36
|
+
/** Milliseconds a converted or recalculated file is kept. */
|
|
37
|
+
outputRetentionMs: number;
|
|
38
|
+
/** Maximum bytes across retained converted and recalculated files; the oldest leave first. */
|
|
39
|
+
maxOutputStoreBytes: number;
|
|
40
|
+
/** Conversion deadline in milliseconds; excludes the DSH queue. */
|
|
41
|
+
timeoutMs: number;
|
|
42
|
+
/** Maximum authorized source bytes. */
|
|
43
|
+
maxInputBytes: number;
|
|
44
|
+
/** Maximum complete PDF, converted, or recalculated file bytes. */
|
|
45
|
+
maxOutputBytes: number;
|
|
46
|
+
/** Image resolution in DPI of PDF exports; `renderImages()` takes its resolution from each request's `dpi`. */
|
|
47
|
+
maxImageResolution: number;
|
|
48
|
+
/** Maximum OOXML ZIP entries. */
|
|
49
|
+
maxArchiveEntries: number;
|
|
50
|
+
/** Maximum total declared uncompressed OOXML bytes. */
|
|
51
|
+
maxUncompressedBytes: number;
|
|
52
|
+
/** Absolute font roots; omission uses the kit's platform defaults. */
|
|
53
|
+
fontDirectories?: string[];
|
|
54
|
+
/** Ordered font-family preference groups; omission retains the kit defaults. */
|
|
55
|
+
fontFallbacks?: string[][];
|
|
56
|
+
/** Maximum physical font files indexed by each converter. */
|
|
57
|
+
maxFontFiles: number;
|
|
58
|
+
/** Maximum individual font-file bytes. */
|
|
59
|
+
maxFontFileBytes: number;
|
|
60
|
+
/** Maximum original font bytes loaded for a conversion. */
|
|
61
|
+
maxLoadedFontBytes: number;
|
|
62
|
+
}
|
|
63
|
+
/** Deployment defaults resolved before provider construction. */
|
|
64
|
+
export declare const Config: z<Partial<Config>, Config>;
|
|
65
|
+
/** A provider lifetime owns all converters, queued calls, and temporary files. */
|
|
66
|
+
export declare class OfficeKit extends TypertRemoteService {
|
|
67
|
+
private readonly config;
|
|
68
|
+
static Config: z<Partial<Config>, Config>;
|
|
69
|
+
/** Changes whenever engine, font, or conversion configuration is replaced. */
|
|
70
|
+
readonly generation: OfficeKitGeneration;
|
|
71
|
+
/** Absolute Host directory holding converted and recalculated files; consumers check that their execution world reads it. */
|
|
72
|
+
readonly outputDirectory: string;
|
|
73
|
+
private readonly remoteLifetime;
|
|
74
|
+
private readonly remoteRequests;
|
|
75
|
+
private readonly slots;
|
|
76
|
+
private readonly queue;
|
|
77
|
+
private readonly outputs;
|
|
78
|
+
private readonly options;
|
|
79
|
+
private loadedKit?;
|
|
80
|
+
private readonly reportedKitFailures;
|
|
81
|
+
/**
|
|
82
|
+
* @param ctx - owning Host context.
|
|
83
|
+
* @param config - resolved rendering, font, and concurrency limits.
|
|
84
|
+
*/
|
|
85
|
+
constructor(ctx: Context, config: Config);
|
|
86
|
+
/**
|
|
87
|
+
* Convert Office bytes to PDF without modifying the source or writing Session events.
|
|
88
|
+
* @param request - authorized metadata and deferred bounded source read.
|
|
89
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
90
|
+
* @returns caller-owned PDF bytes after conversion and scratch cleanup settle; canceled readers reject independently.
|
|
91
|
+
* @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
|
|
92
|
+
*/
|
|
93
|
+
convert(request: OfficeKitRequest, signal?: AbortSignal): Promise<OfficeKitResult>;
|
|
94
|
+
/**
|
|
95
|
+
* Render selected pages, slides, or worksheet areas of one document as PNG images. Requests share the admission
|
|
96
|
+
* queue, concurrency, source-byte reservation, and cache with previews, and run at foreground priority.
|
|
97
|
+
* @param request - authorized metadata, deferred bounded source read, selection, and complete-result limits.
|
|
98
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
99
|
+
* @returns caller-owned images in document order whose count, per-image size, and total bytes satisfy the limits.
|
|
100
|
+
* @throws {OfficeKitError} `invalid-request` for a selection the engine rejects, `output-too-large` when the
|
|
101
|
+
* selection exceeds a limit, and the other conversion codes; cancellation rejects with its reason.
|
|
102
|
+
*/
|
|
103
|
+
renderImages(request: OfficeImagesRequest, signal?: AbortSignal): Promise<OfficeImagesResult>;
|
|
104
|
+
/**
|
|
105
|
+
* Convert one document to another format at foreground priority, sharing admission, concurrency, and cache with
|
|
106
|
+
* previews, and save the result in the provider's output store.
|
|
107
|
+
* @param request - authorized metadata, deferred bounded source read, target format, and output owner and name.
|
|
108
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
109
|
+
* @returns the saved file's absolute Host path and size; the file is deleted after `outputRetentionMs`, when older
|
|
110
|
+
* outputs need `maxOutputStoreBytes`, when the Session whose id is `output.owner` is disposed, or when the provider is disposed.
|
|
111
|
+
* @throws {OfficeKitError} `invalid-request` for a format or sheet the engine rejects and the other conversion
|
|
112
|
+
* codes; cancellation rejects with its reason.
|
|
113
|
+
*/
|
|
114
|
+
convertTo(request: OfficeConversionRequest, signal?: AbortSignal): Promise<OfficeFileResult>;
|
|
115
|
+
/**
|
|
116
|
+
* Recalculate every formula of one workbook at foreground priority and save formulas with refreshed cached results, sharing admission,
|
|
117
|
+
* concurrency, and cache with previews, and save the workbook in the provider's output store. This does not validate
|
|
118
|
+
* formulas or business data.
|
|
119
|
+
* @param request - authorized workbook metadata, deferred bounded source read, output format, and output owner and name.
|
|
120
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
121
|
+
* @returns the saved workbook's absolute Host path and size, retained like {@link convertTo} outputs.
|
|
122
|
+
* @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
|
|
123
|
+
*/
|
|
124
|
+
recalculate(request: OfficeRecalculationRequest, signal?: AbortSignal): Promise<OfficeFileResult>;
|
|
125
|
+
private saveFile;
|
|
126
|
+
/**
|
|
127
|
+
* Read and convert one Office file using the Session's ordinary filesystem authorization.
|
|
128
|
+
* @param workspaceFileScope - Session header lookup shared with workspaceFiles.
|
|
129
|
+
* @param path - absolute or workspace-relative Office path.
|
|
130
|
+
* @param priority - foreground preview or speculative background work.
|
|
131
|
+
* @param signal - Remote cancellation; disposal also cancels outstanding reads and conversions.
|
|
132
|
+
* @returns complete PDF bytes with original source identity and missing font families.
|
|
133
|
+
*/
|
|
134
|
+
render(workspaceFileScope: WorkspaceFileScope, path: string, priority: OfficeKitPriority, signal: AbortSignal): Promise<RenderedDocumentBytes>;
|
|
135
|
+
/**
|
|
136
|
+
* Read the current rendering generation before reusing a Client PDF.
|
|
137
|
+
* @param signal - Remote caller cancellation.
|
|
138
|
+
* @returns provider lifetime, replaced with rendering, font, or engine configuration.
|
|
139
|
+
*/
|
|
140
|
+
getGeneration(signal: AbortSignal): OfficeKitGeneration;
|
|
141
|
+
private renderFile;
|
|
142
|
+
/**
|
|
143
|
+
* Locate and import Kit for a converter. A successful import is reused for the provider lifetime; a missing or
|
|
144
|
+
* unloadable Kit rejects as `unavailable` without being retained, so the next converter request locates Kit again.
|
|
145
|
+
*/
|
|
146
|
+
private loadKit;
|
|
147
|
+
private importKit;
|
|
148
|
+
/** Classify a Kit failure as `unavailable`, logging each distinct message and cause once per provider lifetime. */
|
|
149
|
+
private unavailableKit;
|
|
150
|
+
private runOperation;
|
|
151
|
+
/** Run one engine operation in a private scratch directory and read its complete, bounded output. */
|
|
152
|
+
private runEngine;
|
|
153
|
+
private readFile;
|
|
154
|
+
private renderPng;
|
|
155
|
+
}
|
|
156
|
+
export default OfficeKit;
|
|
157
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
|
|
2
|
+
var useValue = arguments.length > 2;
|
|
3
|
+
for (var i = 0; i < initializers.length; i++) {
|
|
4
|
+
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
|
|
5
|
+
}
|
|
6
|
+
return useValue ? value : void 0;
|
|
7
|
+
};
|
|
8
|
+
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
|
|
9
|
+
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
|
|
10
|
+
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
|
|
11
|
+
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
|
|
12
|
+
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
|
|
13
|
+
var _, done = false;
|
|
14
|
+
for (var i = decorators.length - 1; i >= 0; i--) {
|
|
15
|
+
var context = {};
|
|
16
|
+
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
|
|
17
|
+
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
|
|
18
|
+
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
|
|
19
|
+
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
|
|
20
|
+
if (kind === "accessor") {
|
|
21
|
+
if (result === void 0) continue;
|
|
22
|
+
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
|
|
23
|
+
if (_ = accept(result.get)) descriptor.get = _;
|
|
24
|
+
if (_ = accept(result.set)) descriptor.set = _;
|
|
25
|
+
if (_ = accept(result.init)) initializers.unshift(_);
|
|
26
|
+
}
|
|
27
|
+
else if (_ = accept(result)) {
|
|
28
|
+
if (kind === "field") initializers.unshift(_);
|
|
29
|
+
else descriptor[key] = _;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (target) Object.defineProperty(target, contextIn.name, descriptor);
|
|
33
|
+
done = true;
|
|
34
|
+
};
|
|
35
|
+
/** Host LibreOffice Kit provider with reusable converters, shared admission, and private disk input/output. */
|
|
36
|
+
import { randomUUID } from 'node:crypto';
|
|
37
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
38
|
+
import { tmpdir } from 'node:os';
|
|
39
|
+
import { extname, isAbsolute, join, relative, sep } from 'node:path';
|
|
40
|
+
import z from '@deepseek-ai/schemastery';
|
|
41
|
+
import { dshHomePath } from '@deepseek-ai/dsh-home-paths';
|
|
42
|
+
import { brandString } from '@deepseek-ai/dsh-brand';
|
|
43
|
+
import { resolveKitModule } from "./locate.js";
|
|
44
|
+
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
|
|
45
|
+
import { OfficeKitError } from "./errors.js";
|
|
46
|
+
import { OfficeKitGeneration } from "./identity.js";
|
|
47
|
+
import { readOutput, readPdf, readPng } from "./output.js";
|
|
48
|
+
import { OutputStore } from "./outputs.js";
|
|
49
|
+
import { ConversionQueue } from "./queue.js";
|
|
50
|
+
export * from "./errors.js";
|
|
51
|
+
export * from "./identity.js";
|
|
52
|
+
export * from "./types.js";
|
|
53
|
+
/** Deployment defaults resolved before provider construction. */
|
|
54
|
+
export const Config = z.object({
|
|
55
|
+
maxConcurrentConversions: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(2),
|
|
56
|
+
maxQueuedJobs: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8),
|
|
57
|
+
maxReaders: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(32),
|
|
58
|
+
maxSourceBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(104857600),
|
|
59
|
+
maxBackgroundConversions: z.natural().min(0).max(Number.MAX_SAFE_INTEGER).default(1),
|
|
60
|
+
maxCachedEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(8),
|
|
61
|
+
maxCachedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(134217728),
|
|
62
|
+
maxSourceEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(64),
|
|
63
|
+
outputDirectory: z.string().min(1).default(dshHomePath('office-kit', 'outputs')),
|
|
64
|
+
outputRetentionMs: z.natural().min(1).max(2_147_483_647).default(24 * 60 * 60 * 1000),
|
|
65
|
+
maxOutputStoreBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024),
|
|
66
|
+
timeoutMs: z.natural().min(1).max(2_147_483_647).default(60_000),
|
|
67
|
+
maxInputBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER - 1).default(50 * 1024 * 1024),
|
|
68
|
+
maxOutputBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER - 1).default(100 * 1024 * 1024),
|
|
69
|
+
maxImageResolution: z.natural().min(1).max(2_147_483_647).default(192),
|
|
70
|
+
maxArchiveEntries: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(10_000),
|
|
71
|
+
maxUncompressedBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(250 * 1024 * 1024),
|
|
72
|
+
fontDirectories: z.array(z.string().min(1)).extra('default', undefined),
|
|
73
|
+
fontFallbacks: z.array(z.array(z.string().pattern(/\S/)).min(2)).extra('default', undefined),
|
|
74
|
+
maxFontFiles: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(20_000),
|
|
75
|
+
maxFontFileBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(256 * 1024 * 1024),
|
|
76
|
+
maxLoadedFontBytes: z.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(512 * 1024 * 1024),
|
|
77
|
+
});
|
|
78
|
+
const KIT_INSTALL_HINT = 'This deployment does not provide LibreOffice Kit; install or enable it as this deployment requires, then retry.';
|
|
79
|
+
/** A provider lifetime owns all converters, queued calls, and temporary files. */
|
|
80
|
+
let OfficeKit = (() => {
|
|
81
|
+
let _classSuper = TypertRemoteService;
|
|
82
|
+
let _instanceExtraInitializers = [];
|
|
83
|
+
let _render_decorators;
|
|
84
|
+
let _getGeneration_decorators;
|
|
85
|
+
return class OfficeKit extends _classSuper {
|
|
86
|
+
static {
|
|
87
|
+
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
88
|
+
_render_decorators = [Remote];
|
|
89
|
+
_getGeneration_decorators = [Remote('generation')];
|
|
90
|
+
__esDecorate(this, null, _render_decorators, { kind: "method", name: "render", static: false, private: false, access: { has: obj => "render" in obj, get: obj => obj.render }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
91
|
+
__esDecorate(this, null, _getGeneration_decorators, { kind: "method", name: "getGeneration", static: false, private: false, access: { has: obj => "getGeneration" in obj, get: obj => obj.getGeneration }, metadata: _metadata }, null, _instanceExtraInitializers);
|
|
92
|
+
if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
|
|
93
|
+
}
|
|
94
|
+
config = __runInitializers(this, _instanceExtraInitializers);
|
|
95
|
+
static Config = Config;
|
|
96
|
+
/** Changes whenever engine, font, or conversion configuration is replaced. */
|
|
97
|
+
generation = OfficeKitGeneration(randomUUID());
|
|
98
|
+
/** Absolute Host directory holding converted and recalculated files; consumers check that their execution world reads it. */
|
|
99
|
+
outputDirectory;
|
|
100
|
+
remoteLifetime = new AbortController();
|
|
101
|
+
remoteRequests = new Set();
|
|
102
|
+
slots = [];
|
|
103
|
+
queue;
|
|
104
|
+
outputs;
|
|
105
|
+
options;
|
|
106
|
+
loadedKit;
|
|
107
|
+
reportedKitFailures = new Set();
|
|
108
|
+
/**
|
|
109
|
+
* @param ctx - owning Host context.
|
|
110
|
+
* @param config - resolved rendering, font, and concurrency limits.
|
|
111
|
+
*/
|
|
112
|
+
constructor(ctx, config) {
|
|
113
|
+
super(ctx, 'officeKit');
|
|
114
|
+
this.config = config;
|
|
115
|
+
if (config.fontDirectories?.some(path => !isAbsolute(path)))
|
|
116
|
+
throw new Error('fontDirectories must contain absolute paths.');
|
|
117
|
+
if (config.maxSourceBytes < config.maxInputBytes)
|
|
118
|
+
throw new Error('maxSourceBytes must be at least maxInputBytes.');
|
|
119
|
+
if (!isAbsolute(config.outputDirectory))
|
|
120
|
+
throw new Error('outputDirectory must be an absolute path.');
|
|
121
|
+
const { fontDirectories, fontFallbacks, timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution, maxArchiveEntries, maxUncompressedBytes, maxFontFiles, maxFontFileBytes, maxLoadedFontBytes } = config;
|
|
122
|
+
this.options = { timeoutMs, maxInputBytes, maxOutputBytes, maxImageResolution,
|
|
123
|
+
maxArchiveEntries, maxUncompressedBytes, maxFontFiles, maxFontFileBytes, maxLoadedFontBytes,
|
|
124
|
+
...(fontDirectories === undefined ? {} : { fontDirectories }),
|
|
125
|
+
...(fontFallbacks === undefined ? {} : { fontFallbacks }),
|
|
126
|
+
};
|
|
127
|
+
this.queue = new ConversionQueue(config, this.generation, (bytes, request, signal) => this.runOperation(bytes, request, signal));
|
|
128
|
+
this.outputDirectory = config.outputDirectory;
|
|
129
|
+
this.outputs = new OutputStore({ root: config.outputDirectory, retentionMs: config.outputRetentionMs,
|
|
130
|
+
maxBytes: config.maxOutputStoreBytes }, ctx.logger.warn.bind(ctx.logger));
|
|
131
|
+
// The output store records this release, and its disposal below waits for the release to settle.
|
|
132
|
+
ctx.on('session/disposed', (session) => { void this.outputs.release(session.id); });
|
|
133
|
+
ctx.effect(() => async () => {
|
|
134
|
+
this.remoteLifetime.abort();
|
|
135
|
+
await this.queue.dispose();
|
|
136
|
+
await this.outputs.dispose();
|
|
137
|
+
await Promise.allSettled(this.remoteRequests);
|
|
138
|
+
const results = await Promise.allSettled(this.slots.map(async (slot) => {
|
|
139
|
+
const converter = await slot.converter;
|
|
140
|
+
await converter?.dispose();
|
|
141
|
+
}));
|
|
142
|
+
const failures = results.filter(result => result.status === 'rejected');
|
|
143
|
+
if (failures.length > 0)
|
|
144
|
+
throw new AggregateError(failures.map((result) => result.reason), 'LibreOffice converter disposal failed.');
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Convert Office bytes to PDF without modifying the source or writing Session events.
|
|
149
|
+
* @param request - authorized metadata and deferred bounded source read.
|
|
150
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
151
|
+
* @returns caller-owned PDF bytes after conversion and scratch cleanup settle; canceled readers reject independently.
|
|
152
|
+
* @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
|
|
153
|
+
*/
|
|
154
|
+
async convert(request, signal) {
|
|
155
|
+
const { kind: _kind, ...result } = await this.queue.read({ ...request, operation: { kind: 'pdf' } }, signal);
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Render selected pages, slides, or worksheet areas of one document as PNG images. Requests share the admission
|
|
160
|
+
* queue, concurrency, source-byte reservation, and cache with previews, and run at foreground priority.
|
|
161
|
+
* @param request - authorized metadata, deferred bounded source read, selection, and complete-result limits.
|
|
162
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
163
|
+
* @returns caller-owned images in document order whose count, per-image size, and total bytes satisfy the limits.
|
|
164
|
+
* @throws {OfficeKitError} `invalid-request` for a selection the engine rejects, `output-too-large` when the
|
|
165
|
+
* selection exceeds a limit, and the other conversion codes; cancellation rejects with its reason.
|
|
166
|
+
*/
|
|
167
|
+
async renderImages(request, signal) {
|
|
168
|
+
const { extension, source, pages, sheet, range, dpi, maxImages, maxPixels, maxDimension, maxBytes } = request;
|
|
169
|
+
const result = await this.queue.read({ extension, priority: 'foreground', source, operation: {
|
|
170
|
+
kind: 'images',
|
|
171
|
+
...(pages === undefined ? {} : { pages: [...pages] }),
|
|
172
|
+
...(sheet === undefined ? {} : { sheet }),
|
|
173
|
+
...(range === undefined ? {} : { range }),
|
|
174
|
+
...(dpi === undefined ? {} : { dpi }),
|
|
175
|
+
maxImages, maxPixels, maxDimension, maxBytes,
|
|
176
|
+
} }, signal);
|
|
177
|
+
return { images: result.images, pageCount: result.pageCount, dpi: result.dpi, missingFonts: result.missingFonts };
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Convert one document to another format at foreground priority, sharing admission, concurrency, and cache with
|
|
181
|
+
* previews, and save the result in the provider's output store.
|
|
182
|
+
* @param request - authorized metadata, deferred bounded source read, target format, and output owner and name.
|
|
183
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
184
|
+
* @returns the saved file's absolute Host path and size; the file is deleted after `outputRetentionMs`, when older
|
|
185
|
+
* outputs need `maxOutputStoreBytes`, when the Session whose id is `output.owner` is disposed, or when the provider is disposed.
|
|
186
|
+
* @throws {OfficeKitError} `invalid-request` for a format or sheet the engine rejects and the other conversion
|
|
187
|
+
* codes; cancellation rejects with its reason.
|
|
188
|
+
*/
|
|
189
|
+
async convertTo(request, signal) {
|
|
190
|
+
const { extension, source, format, sheet, output } = request;
|
|
191
|
+
return this.saveFile(output, await this.queue.read({ extension, priority: 'foreground', source,
|
|
192
|
+
operation: { kind: 'convert', format, ...(sheet === undefined ? {} : { sheet }) } }, signal), signal);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Recalculate every formula of one workbook at foreground priority and save formulas with refreshed cached results, sharing admission,
|
|
196
|
+
* concurrency, and cache with previews, and save the workbook in the provider's output store. This does not validate
|
|
197
|
+
* formulas or business data.
|
|
198
|
+
* @param request - authorized workbook metadata, deferred bounded source read, output format, and output owner and name.
|
|
199
|
+
* @param signal - caller cancellation; provider disposal also stops active work.
|
|
200
|
+
* @returns the saved workbook's absolute Host path and size, retained like {@link convertTo} outputs.
|
|
201
|
+
* @throws {OfficeKitError} Invalid input, unusable output, or engine failure; cancellation rejects with its reason.
|
|
202
|
+
*/
|
|
203
|
+
async recalculate(request, signal) {
|
|
204
|
+
const { extension, source, format, output } = request;
|
|
205
|
+
return this.saveFile(output, await this.queue.read({ extension, priority: 'foreground', source, operation: { kind: 'recalculate', format } }, signal), signal);
|
|
206
|
+
}
|
|
207
|
+
async saveFile(output, result, signal) {
|
|
208
|
+
signal?.throwIfAborted();
|
|
209
|
+
const path = await this.outputs.save(output.owner, output.name, result.data);
|
|
210
|
+
return { path, bytes: result.data.byteLength, ...(result.pageCount === undefined ? {} : { pageCount: result.pageCount }),
|
|
211
|
+
missingFonts: result.missingFonts };
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Read and convert one Office file using the Session's ordinary filesystem authorization.
|
|
215
|
+
* @param workspaceFileScope - Session header lookup shared with workspaceFiles.
|
|
216
|
+
* @param path - absolute or workspace-relative Office path.
|
|
217
|
+
* @param priority - foreground preview or speculative background work.
|
|
218
|
+
* @param signal - Remote cancellation; disposal also cancels outstanding reads and conversions.
|
|
219
|
+
* @returns complete PDF bytes with original source identity and missing font families.
|
|
220
|
+
*/
|
|
221
|
+
async render(workspaceFileScope, path, priority, signal) {
|
|
222
|
+
const upstream = AbortSignal.any([signal, this.remoteLifetime.signal]);
|
|
223
|
+
const operation = this.renderFile(workspaceFileScope, path, priority, upstream);
|
|
224
|
+
this.remoteRequests.add(operation);
|
|
225
|
+
try {
|
|
226
|
+
return await operation;
|
|
227
|
+
}
|
|
228
|
+
finally {
|
|
229
|
+
this.remoteRequests.delete(operation);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Read the current rendering generation before reusing a Client PDF.
|
|
234
|
+
* @param signal - Remote caller cancellation.
|
|
235
|
+
* @returns provider lifetime, replaced with rendering, font, or engine configuration.
|
|
236
|
+
*/
|
|
237
|
+
getGeneration(signal) { signal.throwIfAborted(); return this.generation; }
|
|
238
|
+
async renderFile(scope, path, priority, signal) {
|
|
239
|
+
try {
|
|
240
|
+
signal.throwIfAborted();
|
|
241
|
+
const extension = extname(path).slice(1).toLowerCase();
|
|
242
|
+
if (extension !== 'doc' && extension !== 'docx' && extension !== 'xls'
|
|
243
|
+
&& extension !== 'xlsx' && extension !== 'ppt' && extension !== 'pptx') {
|
|
244
|
+
throw new OfficeKitError('unsupported-format', 'The path must end in doc, docx, xls, xlsx, ppt, or pptx.');
|
|
245
|
+
}
|
|
246
|
+
const files = this.ctx.get('workspaceFiles');
|
|
247
|
+
const fs = this.ctx.get('fs');
|
|
248
|
+
if (files === undefined || fs === undefined)
|
|
249
|
+
throw new OfficeKitError('unavailable', 'Office file rendering requires workspaceFiles and fs.');
|
|
250
|
+
const authorized = await files.readBytes(scope, path, { range: { offset: 0, length: 1 } }, signal);
|
|
251
|
+
const source = await files.stat(scope, path, signal);
|
|
252
|
+
const assertUnchanged = (current) => {
|
|
253
|
+
if (current.absolutePath !== source.absolutePath || current.version !== source.version) {
|
|
254
|
+
throw new OfficeKitError('source-changed', 'The source changed.');
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
assertUnchanged(authorized);
|
|
258
|
+
signal.throwIfAborted();
|
|
259
|
+
const result = await this.convert({ extension, priority, source: {
|
|
260
|
+
key: brandString(JSON.stringify([scope.sessionId, scope.workspaceRoot, source.absolutePath])),
|
|
261
|
+
version: source.version, ...(source.bytes === undefined ? {} : { bytes: source.bytes }),
|
|
262
|
+
read: async (upstream, maxBytes) => {
|
|
263
|
+
const target = await fs.resolve(source.absolutePath, { signal: upstream });
|
|
264
|
+
const info = await fs.stat(target, upstream);
|
|
265
|
+
if (info === undefined || info.type !== 'file')
|
|
266
|
+
throw new OfficeKitError('source-changed', 'The source changed.');
|
|
267
|
+
assertUnchanged({ absolutePath: fs.processPath(target), version: info.version });
|
|
268
|
+
const bytes = await fs.readBytes(target, upstream, maxBytes).catch(async (cause) => {
|
|
269
|
+
if (typeof cause === 'object' && cause !== null && 'code' in cause && cause.code === 'FS_TOO_LARGE') {
|
|
270
|
+
assertUnchanged(await files.stat(scope, path, upstream));
|
|
271
|
+
throw new OfficeKitError('input-too-large', 'The source exceeds the reserved byte capacity.', { cause });
|
|
272
|
+
}
|
|
273
|
+
throw cause;
|
|
274
|
+
});
|
|
275
|
+
upstream.throwIfAborted();
|
|
276
|
+
const after = await files.stat(scope, path, upstream);
|
|
277
|
+
assertUnchanged(after);
|
|
278
|
+
return { bytes, version: source.version };
|
|
279
|
+
},
|
|
280
|
+
} }, signal);
|
|
281
|
+
signal.throwIfAborted();
|
|
282
|
+
return { absolutePath: source.absolutePath, version: source.version,
|
|
283
|
+
offset: 0, eof: true, bytes: result.pdf.byteLength, data: result.pdf,
|
|
284
|
+
missingFonts: result.missingFonts, generation: result.generation };
|
|
285
|
+
}
|
|
286
|
+
catch (cause) {
|
|
287
|
+
if (signal.aborted)
|
|
288
|
+
throw new RemoteError('gateway/cancelled', 'The document preview was cancelled.', {}, { cause });
|
|
289
|
+
if (cause instanceof OfficeKitError) {
|
|
290
|
+
throw new RemoteError('document-render/failed', 'Office conversion failed.', { reason: cause.code }, { cause });
|
|
291
|
+
}
|
|
292
|
+
throw cause;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Locate and import Kit for a converter. A successful import is reused for the provider lifetime; a missing or
|
|
297
|
+
* unloadable Kit rejects as `unavailable` without being retained, so the next converter request locates Kit again.
|
|
298
|
+
*/
|
|
299
|
+
loadKit() {
|
|
300
|
+
if (this.loadedKit !== undefined)
|
|
301
|
+
return this.loadedKit;
|
|
302
|
+
const loading = this.importKit();
|
|
303
|
+
this.loadedKit = loading;
|
|
304
|
+
loading.catch(() => { delete this.loadedKit; });
|
|
305
|
+
return loading;
|
|
306
|
+
}
|
|
307
|
+
async importKit() {
|
|
308
|
+
const kit = resolveKitModule(() => import.meta.resolve('@deepseek-ai/libreoffice-kit'));
|
|
309
|
+
if (kit.kind === 'missing')
|
|
310
|
+
throw this.unavailableKit('LibreOffice Kit is not installed.', kit.error);
|
|
311
|
+
let createConverter;
|
|
312
|
+
try {
|
|
313
|
+
({ createConverter } = await import(kit.entry));
|
|
314
|
+
}
|
|
315
|
+
catch (cause) {
|
|
316
|
+
throw this.unavailableKit('LibreOffice Kit could not be loaded.', cause);
|
|
317
|
+
}
|
|
318
|
+
return { createConverter, resolveEnginePackage: kit.resolveEnginePackage };
|
|
319
|
+
}
|
|
320
|
+
/** Classify a Kit failure as `unavailable`, logging each distinct message and cause once per provider lifetime. */
|
|
321
|
+
unavailableKit(message, cause) {
|
|
322
|
+
const error = new OfficeKitError('unavailable', `${message} ${KIT_INSTALL_HINT}`, { cause });
|
|
323
|
+
const key = `${message}\n${cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause)}`;
|
|
324
|
+
if (!this.reportedKitFailures.has(key)) {
|
|
325
|
+
this.reportedKitFailures.add(key);
|
|
326
|
+
this.ctx.logger.warn(error);
|
|
327
|
+
}
|
|
328
|
+
return error;
|
|
329
|
+
}
|
|
330
|
+
async runOperation(bytes, request, signal) {
|
|
331
|
+
signal.throwIfAborted();
|
|
332
|
+
let slot = this.slots.find(candidate => !candidate.busy);
|
|
333
|
+
if (slot === undefined) {
|
|
334
|
+
slot = { busy: false };
|
|
335
|
+
this.slots.push(slot);
|
|
336
|
+
}
|
|
337
|
+
slot.busy = true;
|
|
338
|
+
let directory;
|
|
339
|
+
try {
|
|
340
|
+
if (slot.converter === undefined) {
|
|
341
|
+
slot.converter = this.loadKit().then(({ createConverter, resolveEnginePackage }) => createConverter({ ...this.options, resolveEnginePackage })).catch((error) => {
|
|
342
|
+
delete slot.converter;
|
|
343
|
+
throw error;
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
const converter = await slot.converter;
|
|
347
|
+
signal.throwIfAborted();
|
|
348
|
+
directory = await mkdtemp(join(tmpdir(), 'dsh-office-kit-'));
|
|
349
|
+
const inputPath = join(directory, `source.${request.extension}`);
|
|
350
|
+
await writeFile(inputPath, bytes, { flag: 'wx', mode: 0o600, signal });
|
|
351
|
+
signal.throwIfAborted();
|
|
352
|
+
const output = await this.runEngine(converter, inputPath, directory, request.operation, signal);
|
|
353
|
+
signal.throwIfAborted();
|
|
354
|
+
return output;
|
|
355
|
+
}
|
|
356
|
+
catch (cause) {
|
|
357
|
+
signal.throwIfAborted();
|
|
358
|
+
if (cause instanceof OfficeKitError)
|
|
359
|
+
throw cause;
|
|
360
|
+
if (cause instanceof TypeError || cause instanceof RangeError)
|
|
361
|
+
throw new OfficeKitError('invalid-request', cause.message, { cause });
|
|
362
|
+
const code = typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined;
|
|
363
|
+
switch (code) {
|
|
364
|
+
case 'input-too-large':
|
|
365
|
+
case 'output-too-large':
|
|
366
|
+
case 'invalid-document':
|
|
367
|
+
case 'unsupported-format':
|
|
368
|
+
case 'invalid-output':
|
|
369
|
+
case 'timeout':
|
|
370
|
+
case 'unavailable':
|
|
371
|
+
throw new OfficeKitError(code, cause instanceof Error ? cause.message : 'LibreOffice conversion failed.', { cause });
|
|
372
|
+
default: throw new OfficeKitError('failed', 'LibreOffice conversion failed.', { cause });
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
try {
|
|
377
|
+
if (directory !== undefined)
|
|
378
|
+
await rm(directory, { recursive: true, force: true });
|
|
379
|
+
}
|
|
380
|
+
finally {
|
|
381
|
+
slot.busy = false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** Run one engine operation in a private scratch directory and read its complete, bounded output. */
|
|
386
|
+
async runEngine(converter, inputPath, directory, operation, signal) {
|
|
387
|
+
switch (operation.kind) {
|
|
388
|
+
case 'pdf': {
|
|
389
|
+
const outputPath = join(directory, 'converted.pdf');
|
|
390
|
+
const result = await converter.render({ inputPath, outputPath }, signal);
|
|
391
|
+
return { kind: 'pdf', pdf: await this.readFile(outputPath, 'pdf', signal), missingFonts: result.missingFonts };
|
|
392
|
+
}
|
|
393
|
+
case 'convert':
|
|
394
|
+
case 'recalculate': {
|
|
395
|
+
const outputPath = join(directory, `output.${operation.format}`);
|
|
396
|
+
const result = operation.kind === 'convert'
|
|
397
|
+
? await converter.convert({ inputPath, outputPath, ...(operation.sheet === undefined ? {} : { sheet: operation.sheet }) }, signal)
|
|
398
|
+
: await converter.recalculate({ inputPath, outputPath }, signal);
|
|
399
|
+
return { kind: 'file', data: await this.readFile(outputPath, operation.format, signal),
|
|
400
|
+
...(result.pageCount === undefined ? {} : { pageCount: result.pageCount }), missingFonts: result.missingFonts };
|
|
401
|
+
}
|
|
402
|
+
case 'images': return this.renderPng(converter, inputPath, directory, operation, signal);
|
|
403
|
+
/* v8 ignore next -- OfficeOperation is a closed union */
|
|
404
|
+
default: throw new Error(`Unexpected Office operation: ${JSON.stringify(operation)}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
async readFile(path, format, signal) {
|
|
408
|
+
try {
|
|
409
|
+
return format === 'pdf' ? await readPdf(path, this.config.maxOutputBytes, signal) : await readOutput(path, this.config.maxOutputBytes, signal);
|
|
410
|
+
}
|
|
411
|
+
catch (cause) {
|
|
412
|
+
if (cause instanceof OfficeKitError)
|
|
413
|
+
throw cause;
|
|
414
|
+
throw new OfficeKitError('invalid-output', 'The converter output could not be read.', { cause });
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
async renderPng(converter, inputPath, directory, operation, signal) {
|
|
418
|
+
const outputDir = join(directory, 'images');
|
|
419
|
+
const result = await converter.renderImages({
|
|
420
|
+
inputPath, outputDir,
|
|
421
|
+
...(operation.pages === undefined ? {} : { pages: operation.pages }),
|
|
422
|
+
...(operation.sheet === undefined ? {} : { sheet: operation.sheet }),
|
|
423
|
+
...(operation.range === undefined ? {} : { range: operation.range }),
|
|
424
|
+
...(operation.dpi === undefined ? {} : { dpi: operation.dpi }),
|
|
425
|
+
maxPages: operation.maxImages, maxPixels: operation.maxPixels, maxDimension: operation.maxDimension,
|
|
426
|
+
}, signal);
|
|
427
|
+
const declared = result.images.reduce((sum, image) => sum + image.byteLength, 0);
|
|
428
|
+
if (declared > operation.maxBytes) {
|
|
429
|
+
throw new OfficeKitError('output-too-large', `The rendered images total ${declared} bytes, above the ${operation.maxBytes}-byte limit.`);
|
|
430
|
+
}
|
|
431
|
+
const images = [];
|
|
432
|
+
let remaining = operation.maxBytes;
|
|
433
|
+
for (const image of [...result.images].sort((left, right) => left.index - right.index)) {
|
|
434
|
+
const within = relative(outputDir, image.path);
|
|
435
|
+
if (within === '' || within === '..' || within.startsWith(`..${sep}`) || isAbsolute(within)) {
|
|
436
|
+
throw new OfficeKitError('invalid-output', 'The converter reported an image outside its output directory.');
|
|
437
|
+
}
|
|
438
|
+
let png;
|
|
439
|
+
try {
|
|
440
|
+
png = await readPng(image.path, remaining, signal);
|
|
441
|
+
}
|
|
442
|
+
catch (cause) {
|
|
443
|
+
if (cause instanceof OfficeKitError)
|
|
444
|
+
throw cause;
|
|
445
|
+
throw new OfficeKitError('invalid-output', 'The rendered image could not be read.', { cause });
|
|
446
|
+
}
|
|
447
|
+
remaining -= png.byteLength;
|
|
448
|
+
images.push({ png, width: image.width, height: image.height,
|
|
449
|
+
...(image.page === undefined ? {} : { page: image.page }),
|
|
450
|
+
...(image.sheet === undefined ? {} : { sheet: image.sheet }),
|
|
451
|
+
...(image.range === undefined ? {} : { range: image.range }) });
|
|
452
|
+
}
|
|
453
|
+
return { kind: 'images', images, pageCount: result.pageCount, dpi: result.dpi, missingFonts: result.missingFonts };
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
})();
|
|
457
|
+
export { OfficeKit };
|
|
458
|
+
export default OfficeKit;
|
|
459
|
+
//# sourceMappingURL=index.js.map
|