@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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.i18n.yaml +37 -0
  3. package/README.md +128 -2
  4. package/README.zh.md +129 -0
  5. package/lib/index.js +1234 -0
  6. package/lib/typert.host.d.ts +3 -0
  7. package/lib/typert.host.js +346 -0
  8. package/lib/typert.remote-client.d.ts +30 -0
  9. package/lib/typert.remote-client.d.ts.map +1 -0
  10. package/lib/typert.remote-client.js +162 -0
  11. package/lib/types/errors.d.ts +13 -0
  12. package/lib/types/errors.d.ts.map +1 -0
  13. package/lib/types/errors.js +15 -0
  14. package/lib/types/errors.js.map +1 -0
  15. package/lib/types/identity.d.ts +27 -0
  16. package/lib/types/identity.d.ts.map +1 -0
  17. package/lib/types/identity.js +23 -0
  18. package/lib/types/identity.js.map +1 -0
  19. package/lib/types/index.d.ts +157 -0
  20. package/lib/types/index.d.ts.map +1 -0
  21. package/lib/types/index.js +459 -0
  22. package/lib/types/index.js.map +1 -0
  23. package/lib/types/locate.d.ts +48 -0
  24. package/lib/types/locate.d.ts.map +1 -0
  25. package/lib/types/locate.js +65 -0
  26. package/lib/types/locate.js.map +1 -0
  27. package/lib/types/output.d.ts +26 -0
  28. package/lib/types/output.d.ts.map +1 -0
  29. package/lib/types/output.js +75 -0
  30. package/lib/types/output.js.map +1 -0
  31. package/lib/types/outputs.d.ts +75 -0
  32. package/lib/types/outputs.d.ts.map +1 -0
  33. package/lib/types/outputs.js +198 -0
  34. package/lib/types/outputs.js.map +1 -0
  35. package/lib/types/queue.d.ts +106 -0
  36. package/lib/types/queue.d.ts.map +1 -0
  37. package/lib/types/queue.js +276 -0
  38. package/lib/types/queue.js.map +1 -0
  39. package/lib/types/types.d.ts +151 -0
  40. package/lib/types/types.d.ts.map +1 -0
  41. package/lib/types/types.js +2 -0
  42. package/lib/types/types.js.map +1 -0
  43. package/locale/de.json +6 -0
  44. package/locale/en.json +6 -0
  45. package/locale/es.json +6 -0
  46. package/locale/fr.json +6 -0
  47. package/locale/ja.json +6 -0
  48. package/locale/pt.json +6 -0
  49. package/locale/ru.json +6 -0
  50. package/locale/zh.json +6 -0
  51. package/package.json +68 -3
  52. package/src/errors.ts +15 -0
  53. package/src/identity.ts +31 -0
  54. package/src/index.ts +484 -0
  55. package/src/locate.ts +93 -0
  56. package/src/output.ts +69 -0
  57. package/src/outputs.ts +218 -0
  58. package/src/queue.ts +316 -0
  59. package/src/types.ts +168 -0
package/src/locate.ts ADDED
@@ -0,0 +1,93 @@
1
+ /** Locate LibreOffice Kit and its engine packages from the consumer's Kit installation without module hooks. */
2
+ import { lstatSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import { join } from 'node:path'
5
+
6
+ /**
7
+ * Locate an engine package manifest for Kit.
8
+ * @param name - Engine package name requested by Kit.
9
+ * @returns Absolute path of the package's `package.json`.
10
+ * @throws An error with code `MODULE_NOT_FOUND` when the package is absent.
11
+ */
12
+ export type EnginePackageResolver = (name: string) => string
13
+
14
+ /**
15
+ * Locate the Kit entry the consumer imports, normally
16
+ * `() => import.meta.resolve('@deepseek-ai/libreoffice-kit')` written in the consuming module.
17
+ * @returns The Kit entry as a file URL string or `URL`.
18
+ * @throws When the consumer cannot resolve Kit; the resolver treats every thrown value as an absent Kit.
19
+ */
20
+ export type KitEntryLookup = () => string | URL
21
+
22
+ /**
23
+ * Kit module location for a consumer that imports Kit at run time.
24
+ * `available` carries the Kit entry file URL for a dynamic `import()` and an engine resolver anchored at that entry;
25
+ * `missing` carries the lookup failure.
26
+ */
27
+ export type KitModuleResolution =
28
+ | { readonly kind: 'available'; readonly entry: string; readonly resolveEnginePackage: EnginePackageResolver }
29
+ | { readonly kind: 'missing'; readonly error: unknown }
30
+
31
+ /**
32
+ * Locate Kit for a consumer that loads it with a dynamic `import()`.
33
+ * @param lookupKitEntry - Consumer's Kit lookup; anchoring at the consumer, not this library, selects the installation the consumer uses.
34
+ * @returns `available` with the entry file URL and an engine resolver created by {@link createEnginePackageResolver},
35
+ * or `missing` when the lookup throws.
36
+ * @throws Node's error if a returned entry cannot be used by `createRequire`.
37
+ */
38
+ export function resolveKitModule(lookupKitEntry: KitEntryLookup): KitModuleResolution {
39
+ const located = lookupEntry(lookupKitEntry)
40
+ if (located.kind === 'missing') return located
41
+ return { kind: 'available', entry: located.entry, resolveEnginePackage: createEnginePackageResolver(located.entry) }
42
+ }
43
+
44
+ /**
45
+ * Anchor engine resolution to the Kit entry actually used by the consumer, not this package's installation.
46
+ * Each returned callback retains its own Node resolver and installs no module hooks.
47
+ * @param kitEntry - Absolute Kit entry path or file URL, normally the consumer's `import.meta.resolve('@deepseek-ai/libreoffice-kit')`.
48
+ * @returns A callback for Kit's `resolveEnginePackage` option. Native paths map the first ASAR segment to its unpacked copy;
49
+ * WASM and paths outside archives stay unchanged. Kit validates the returned manifest and required engine assets.
50
+ * @throws Node's error if `kitEntry` cannot be used by `createRequire`.
51
+ * On invocation, the callback preserves Node errors for absent packages and other resolution failures.
52
+ * An installed package with an unresolvable manifest throws an incomplete-installation Error with the Node error as its cause,
53
+ * preventing engine fallback. Filesystem inspection errors propagate unchanged.
54
+ */
55
+ export function createEnginePackageResolver(kitEntry: string | URL): EnginePackageResolver {
56
+ const fromKit = createRequire(kitEntry)
57
+ return (name) => {
58
+ let manifest: string
59
+ try {
60
+ manifest = fromKit.resolve(`${name}/package.json`)
61
+ } catch (error) {
62
+ if (error instanceof Error && 'code' in error && error.code === 'MODULE_NOT_FOUND') {
63
+ const installed = (fromKit.resolve.paths(name) ?? []).some(directory =>
64
+ lstatSync(join(directory, name), { throwIfNoEntry: false }) !== undefined,
65
+ )
66
+ if (installed) throw new Error(`Installed LibreOfficeKit package is incomplete: ${name}. Reinstall the package.`, { cause: error })
67
+ }
68
+ throw error
69
+ }
70
+ return name === '@deepseek-ai/libreoffice-kit-wasm' ? manifest : unpackedPath(manifest)
71
+ }
72
+ }
73
+
74
+ type EntryLookup = { readonly kind: 'found'; readonly entry: string } | { readonly kind: 'missing'; readonly error: unknown }
75
+
76
+ function lookupEntry(lookupKitEntry: KitEntryLookup): EntryLookup {
77
+ let entry: string | URL
78
+ try {
79
+ entry = lookupKitEntry()
80
+ } catch (error) {
81
+ return { kind: 'missing', error }
82
+ }
83
+ return { kind: 'found', entry: typeof entry === 'string' ? entry : entry.href }
84
+ }
85
+
86
+ /**
87
+ * Map an ASAR path to its physical unpacked copy for native files read outside Electron's archive support.
88
+ * @param path - Filesystem path, including paths with Windows separators.
89
+ * @returns The path with its first `.asar` segment replaced by `.asar.unpacked`; already-unpacked paths stay unchanged.
90
+ */
91
+ function unpackedPath(path: string): string {
92
+ return path.replace(/\.asar(?=[\\/]|$)/, '.asar.unpacked')
93
+ }
package/src/output.ts ADDED
@@ -0,0 +1,69 @@
1
+ /** Read only bounded, regular output files created inside a private task directory. */
2
+ import { constants } from 'node:fs'
3
+ import { lstat, open } from 'node:fs/promises'
4
+ import { OfficeKitError } from './errors.ts'
5
+
6
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
7
+
8
+ /**
9
+ * Refuse missing, link-shaped, oversized, and truncated output.
10
+ * @param path - kit output path in the provider-owned scratch directory.
11
+ * @param limit - inclusive byte limit.
12
+ * @param signal - conversion lifetime.
13
+ * @returns complete bytes independent of the scratch file.
14
+ * @throws {OfficeKitError} `invalid-output` for a non-regular or changing file and `output-too-large` above `limit`.
15
+ */
16
+ export async function readOutput(path: string, limit: number, signal: AbortSignal): Promise<Buffer> {
17
+ signal.throwIfAborted()
18
+ const entry = await lstat(path)
19
+ if (!entry.isFile()) throw new OfficeKitError('invalid-output', 'The converter output is not a regular file.')
20
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)
21
+ try {
22
+ const info = await file.stat()
23
+ if (!info.isFile()) throw new OfficeKitError('invalid-output', 'The converter output is not a regular file.')
24
+ if (info.size > limit) throw new OfficeKitError('output-too-large', 'The converter output exceeds its byte limit.')
25
+ const bytes = Buffer.alloc(info.size + 1)
26
+ let length = 0
27
+ while (length < bytes.length) {
28
+ signal.throwIfAborted()
29
+ const read = await file.read(bytes, length, bytes.length - length, null)
30
+ if (read.bytesRead === 0) break
31
+ length += read.bytesRead
32
+ }
33
+ signal.throwIfAborted()
34
+ if (length > limit) throw new OfficeKitError('output-too-large', 'The converter output exceeds its byte limit.')
35
+ if (length !== info.size) throw new OfficeKitError('invalid-output', 'The converter output changed while it was read.')
36
+ return bytes.subarray(0, length)
37
+ } finally { await file.close() }
38
+ }
39
+
40
+ /**
41
+ * Refuse missing, link-shaped, oversized, truncated, and non-PDF output.
42
+ * @param path - kit output path in the provider-owned scratch directory.
43
+ * @param limit - inclusive PDF byte limit.
44
+ * @param signal - conversion lifetime.
45
+ * @returns complete bytes independent of the scratch file.
46
+ */
47
+ export async function readPdf(path: string, limit: number, signal: AbortSignal): Promise<Uint8Array> {
48
+ const pdf = await readOutput(path, limit, signal)
49
+ if (!pdf.subarray(0, 8).toString('ascii').match(/^%PDF-\d\.\d/u)
50
+ || !pdf.subarray(-1024).toString('ascii').trimEnd().endsWith('%%EOF')) {
51
+ throw new OfficeKitError('invalid-output', 'The converter did not produce a complete PDF.')
52
+ }
53
+ return pdf
54
+ }
55
+
56
+ /**
57
+ * Refuse missing, link-shaped, oversized, and non-PNG image output.
58
+ * @param path - kit image path in the provider-owned scratch directory.
59
+ * @param limit - inclusive PNG byte limit.
60
+ * @param signal - rendering lifetime.
61
+ * @returns complete PNG bytes independent of the scratch file.
62
+ */
63
+ export async function readPng(path: string, limit: number, signal: AbortSignal): Promise<Uint8Array> {
64
+ const png = await readOutput(path, limit, signal)
65
+ if (!png.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
66
+ throw new OfficeKitError('invalid-output', 'The converter did not produce a PNG image.')
67
+ }
68
+ return png
69
+ }
package/src/outputs.ts ADDED
@@ -0,0 +1,218 @@
1
+ /** Private, bounded, Session-owned files for converted and recalculated Office outputs. */
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import type { Dirent } from 'node:fs'
4
+ import { lstat, mkdir, readdir, rm, rmdir, writeFile } from 'node:fs/promises'
5
+ import { basename, join } from 'node:path'
6
+ import { OfficeKitError } from './errors.ts'
7
+
8
+ /** Limits and location of the output store. */
9
+ export interface OutputStoreOptions {
10
+ /** Absolute directory owned by the store; created on first save with owner-only permissions. */
11
+ readonly root: string
12
+ /** Milliseconds a saved file is kept before deletion. */
13
+ readonly retentionMs: number
14
+ /** Inclusive bytes across retained files; older files are deleted first to make room. */
15
+ readonly maxBytes: number
16
+ }
17
+
18
+ interface Entry {
19
+ readonly path: string
20
+ readonly directory: string
21
+ readonly owner: string
22
+ readonly bytes: number
23
+ readonly timer: ReturnType<typeof setTimeout>
24
+ /** Deletion in progress; absent while the file is retained, including after a failed deletion awaiting retry. */
25
+ removal?: Promise<boolean>
26
+ }
27
+
28
+ /** Names {@link ownerDirectory} generates. */
29
+ const OWNER_DIRECTORY = /^session-[0-9a-f]{24}$/u
30
+ /** Names of per-output directories, which `randomUUID()` generates. */
31
+ const OUTPUT_DIRECTORY = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
32
+
33
+ /** Directory name for one owner, independent of characters the owner id may contain. */
34
+ function ownerDirectory(owner: string): string {
35
+ return `session-${createHash('sha256').update(owner).digest('hex').slice(0, 24)}`
36
+ }
37
+
38
+ /** Create an output's private directory and write its file, removing the directory when either step fails. */
39
+ async function writeOutput(directory: string, path: string, data: Uint8Array): Promise<void> {
40
+ try {
41
+ await mkdir(directory, { recursive: true, mode: 0o700 })
42
+ await writeFile(path, data, { flag: 'wx', mode: 0o600 })
43
+ } catch (error) {
44
+ await rm(directory, { recursive: true, force: true })
45
+ throw error
46
+ }
47
+ }
48
+
49
+ function isMissingPath(error: unknown): boolean {
50
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
51
+ }
52
+
53
+ /**
54
+ * Keeps each saved output in its own private directory under a per-owner directory. Files leave when their retention
55
+ * expires, when newer files need the byte budget, when their owner is released, and when the store is disposed. A file
56
+ * counts toward the byte budget until its deletion succeeds; a failed deletion is reported and retried by later
57
+ * eviction, release, and disposal. Only files this store saved are deleted, apart from a startup sweep of expired
58
+ * leftovers of earlier processes. The sweep considers only real directories, never links or junctions, whose names this
59
+ * store generates: `session-` and 24 lowercase hexadecimal digits under the root, and a lowercase UUID v4 below that.
60
+ */
61
+ export class OutputStore {
62
+ private readonly entries = new Map<string, Entry>()
63
+ private bytes = 0
64
+ private disposed = false
65
+ private readonly sweep: Promise<void>
66
+ private saving: Promise<unknown> = Promise.resolve()
67
+ /** Deletions and releases in progress, awaited by disposal. */
68
+ private readonly pending = new Set<Promise<unknown>>()
69
+
70
+ /**
71
+ * @param options - root directory, retention, and byte budget.
72
+ * @param warn - receives contained cleanup failures.
73
+ */
74
+ constructor(private readonly options: OutputStoreOptions, private readonly warn: (message: string) => void) {
75
+ this.sweep = this.sweepExpired()
76
+ }
77
+
78
+ /**
79
+ * Save one output for an owner.
80
+ * @param owner - opaque owner identity, such as a Session id.
81
+ * @param name - file name shown to the consumer; only its final path component is used.
82
+ * @param data - complete output bytes.
83
+ * @returns the absolute path of the saved file.
84
+ * @throws {OfficeKitError} `output-too-large` when the file alone exceeds the byte budget, and `unavailable` after
85
+ * disposal or when retained files whose deletion failed leave too little of the budget.
86
+ */
87
+ save(owner: string, name: string, data: Uint8Array): Promise<string> {
88
+ const saved = this.saving.then(() => this.saveNow(owner, name, data))
89
+ this.saving = saved.catch((_failedSave: unknown) => undefined)
90
+ return saved
91
+ }
92
+
93
+ /** Saves run one at a time so the byte budget covers every retained file. */
94
+ private async saveNow(owner: string, name: string, data: Uint8Array): Promise<string> {
95
+ await this.sweep
96
+ if (this.disposed) throw new OfficeKitError('unavailable', 'The document converter is unavailable.')
97
+ if (data.byteLength > this.options.maxBytes) {
98
+ throw new OfficeKitError('output-too-large', `The output exceeds the ${this.options.maxBytes}-byte output store limit.`)
99
+ }
100
+ for (const entry of [...this.entries.values()]) {
101
+ if (this.bytes + data.byteLength <= this.options.maxBytes) break
102
+ await this.remove(entry)
103
+ }
104
+ if (this.bytes + data.byteLength > this.options.maxBytes) {
105
+ throw new OfficeKitError('unavailable', 'Earlier outputs could not be deleted to make room for this output.')
106
+ }
107
+ const directory = join(this.options.root, ownerDirectory(owner), randomUUID())
108
+ const path = join(directory, basename(name))
109
+ await writeOutput(directory, path, data).catch((error: unknown) => {
110
+ if (!isMissingPath(error)) throw error
111
+ // A concurrent release, or another process's sweep, removed the empty owner directory before the write.
112
+ return writeOutput(directory, path, data)
113
+ })
114
+ const timer = setTimeout(() => { void this.remove(entry) }, this.options.retentionMs)
115
+ timer.unref()
116
+ const entry: Entry = { path, directory, owner, bytes: data.byteLength, timer }
117
+ this.entries.set(path, entry)
118
+ this.bytes += data.byteLength
119
+ return path
120
+ }
121
+
122
+ /**
123
+ * Delete every file saved for an owner. Disposal waits for a release in progress.
124
+ * @param owner - owner whose files are released.
125
+ * @returns completion after deletion settles; failed deletions are reported and retained for retry.
126
+ */
127
+ release(owner: string): Promise<void> {
128
+ return this.track(this.releaseNow(owner))
129
+ }
130
+
131
+ private async releaseNow(owner: string): Promise<void> {
132
+ await Promise.all([...this.entries.values()].filter(entry => entry.owner === owner).map(entry => this.remove(entry)))
133
+ await this.removeEmpty(join(this.options.root, ownerDirectory(owner)))
134
+ }
135
+
136
+ /**
137
+ * Refuse further saves, wait for deletions and releases in progress, and delete every file this store saved,
138
+ * retrying earlier failed deletions once more.
139
+ * @returns completion after deletion settles; files that still cannot be deleted are reported.
140
+ */
141
+ async dispose(): Promise<void> {
142
+ this.disposed = true
143
+ await this.sweep
144
+ await this.saving
145
+ await this.settle()
146
+ const owners = new Set([...this.entries.values()].map(entry => entry.owner))
147
+ await Promise.all([...owners].map(owner => this.release(owner)))
148
+ await this.settle()
149
+ }
150
+
151
+ /** Wait until no deletion or release is in progress, including ones started while waiting. */
152
+ private async settle(): Promise<void> {
153
+ while (this.pending.size > 0) await Promise.all(this.pending)
154
+ }
155
+
156
+ /** Record a non-rejecting deletion or release as in progress until it settles. */
157
+ private track<T>(operation: Promise<T>): Promise<T> {
158
+ this.pending.add(operation)
159
+ const settled = (): void => { this.pending.delete(operation) }
160
+ operation.then(settled, settled)
161
+ return operation
162
+ }
163
+
164
+ /**
165
+ * Delete one saved file, sharing a deletion already in progress. The entry and its bytes leave the store only after
166
+ * the deletion succeeds; a failure is reported and leaves the entry for a later retry.
167
+ * @returns whether the file is gone.
168
+ */
169
+ private remove(entry: Entry): Promise<boolean> {
170
+ if (entry.removal !== undefined) return entry.removal
171
+ if (this.entries.get(entry.path) !== entry) return Promise.resolve(true)
172
+ clearTimeout(entry.timer)
173
+ const removal = this.track(rm(entry.directory, { recursive: true, force: true }).then(() => {
174
+ this.entries.delete(entry.path)
175
+ this.bytes -= entry.bytes
176
+ return true
177
+ }, (error: unknown) => {
178
+ this.warn(`office-kit: could not delete output ${entry.path}: ${String(error)}`)
179
+ return false
180
+ }).finally(() => { delete entry.removal }))
181
+ entry.removal = removal
182
+ return removal
183
+ }
184
+
185
+ private async removeEmpty(directory: string): Promise<void> {
186
+ try { await rmdir(directory) }
187
+ catch (_notEmptyOrMissing) {
188
+ // A directory that still holds another process's output, or no longer exists, is left as is.
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Delete output directories, including those of earlier processes, whose files are older than the retention. Only
194
+ * real directories with store-generated names are considered; links, junctions, and other entries stay untouched.
195
+ */
196
+ private async sweepExpired(): Promise<void> {
197
+ const cutoff = Date.now() - this.options.retentionMs
198
+ for (const owner of await generatedDirectories(this.options.root, OWNER_DIRECTORY)) {
199
+ for (const directory of await generatedDirectories(owner, OUTPUT_DIRECTORY)) {
200
+ try {
201
+ if ((await lstat(directory)).mtimeMs < cutoff) await rm(directory, { recursive: true, force: true })
202
+ } catch (error) { this.warn(`office-kit: could not sweep output ${directory}: ${String(error)}`) }
203
+ }
204
+ await this.removeEmpty(owner)
205
+ }
206
+ }
207
+ }
208
+
209
+ /**
210
+ * List the real subdirectories of `directory` whose names match `name`.
211
+ * @param directory - directory to list; a missing or unreadable directory has none.
212
+ * @param name - names the store generates at this level.
213
+ * @returns absolute paths, excluding links, junctions, and non-directories.
214
+ */
215
+ async function generatedDirectories(directory: string, name: RegExp): Promise<string[]> {
216
+ const entries = await readdir(directory, { withFileTypes: true }).catch((_missingDirectory: unknown) => [] as Dirent[])
217
+ return entries.filter(entry => entry.isDirectory() && name.test(entry.name)).map(entry => join(directory, entry.name))
218
+ }