build-exe-for-python-sdk-office.ts 4.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /** Keep LibreOffice workers, prebuilt engines, and their dependencies on the real filesystem. */
  2. import { existsSync } from 'node:fs'
  3. import { cp, mkdir, readFile, rm } from 'node:fs/promises'
  4. import { createRequire } from 'node:module'
  5. import { isAbsolute, join, relative, sep } from 'node:path'
  6. /** pkg applies these exclusions to dependency `files` as well as root asset globs. */
  7. export const OFFICE_ASSET_IGNORES = [
  8. '**/node_modules/@deepseek-ai/libreoffice-kit/**',
  9. '**/node_modules/@deepseek-ai/libreoffice-kit-*/**',
  10. ]
  11. interface PackageManifest {
  12. name: string
  13. dependencies?: Record<string, string>
  14. optionalDependencies?: Record<string, string>
  15. peerDependencies?: Record<string, string>
  16. peerDependenciesMeta?: Record<string, { optional?: boolean }>
  17. os?: string[]
  18. cpu?: string[]
  19. }
  20. /**
  21. * Copy the installed Office dependency tree without changing package contents or executable modes.
  22. * Harness sidecars require the target native engine on macOS/Windows and WASM on Linux.
  23. * Missing target engines fail with their package name; missing required dependencies or paths outside the deployed closure also fail.
  24. * @param staging - Symlink-free deployed Node closure.
  25. * @param destination - Target-specific Office directory beside the executable; replaced when present.
  26. * @param target - Node platform and CPU of the executable.
  27. * @returns Relative package directories included in the sidecar.
  28. */
  29. export async function copyOfficeSidecar(
  30. staging: string,
  31. destination: string,
  32. target: { platform: string; arch: string },
  33. ): Promise<string[]> {
  34. const engineName = `@deepseek-ai/libreoffice-kit-${target.platform === 'linux' ? 'wasm' : `${target.platform}-${target.arch}`}`
  35. const packages = new Set<string>()
  36. async function visit(packageDirectory: string): Promise<void> {
  37. if (packages.has(packageDirectory)) return
  38. const relativeDirectory = relative(staging, packageDirectory)
  39. if (isAbsolute(relativeDirectory) || relativeDirectory === '..' || relativeDirectory.startsWith(`..${sep}`)) {
  40. throw new Error(`Python Office dependency is outside the deployed closure: ${packageDirectory}`)
  41. }
  42. const manifestPath = join(packageDirectory, 'package.json')
  43. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as PackageManifest
  44. packages.add(packageDirectory)
  45. const require = createRequire(manifestPath)
  46. const dependencies = new Set([
  47. ...Object.keys(manifest.dependencies ?? {}),
  48. ...Object.keys(manifest.optionalDependencies ?? {}),
  49. ...Object.keys(manifest.peerDependencies ?? {}),
  50. ])
  51. for (const name of dependencies) {
  52. if (name.startsWith('@deepseek-ai/libreoffice-kit-') && name !== engineName) continue
  53. const optional = manifest.optionalDependencies?.[name] !== undefined
  54. || manifest.peerDependenciesMeta?.[name]?.optional === true
  55. const dependencyDirectory = (require.resolve.paths(name) ?? [])
  56. .map(directory => join(directory, name))
  57. .find(directory => existsSync(directory))
  58. if (dependencyDirectory === undefined) {
  59. if (optional) continue
  60. throw new Error(`Python Office dependency ${name} required by ${manifest.name} is missing.`)
  61. }
  62. if (optional) {
  63. const dependency = JSON.parse(await readFile(join(dependencyDirectory, 'package.json'), 'utf8')) as PackageManifest
  64. if (!supports(dependency.os, target.platform) || !supports(dependency.cpu, target.arch)) continue
  65. }
  66. await visit(dependencyDirectory)
  67. }
  68. }
  69. await visit(join(staging, 'node_modules', '@deepseek-ai', 'libreoffice-kit'))
  70. const engineDirectory = join(staging, 'node_modules', engineName)
  71. if (!existsSync(engineDirectory)) throw new Error(`Python Office engine ${engineName} required for ${target.platform}/${target.arch} is missing.`)
  72. await visit(engineDirectory)
  73. await rm(destination, { recursive: true, force: true })
  74. await mkdir(destination, { recursive: true })
  75. const directories = [...packages].sort()
  76. for (const source of directories) {
  77. const nestedModules = join(source, 'node_modules')
  78. await cp(source, join(destination, relative(staging, source)), {
  79. recursive: true,
  80. filter: path => path !== nestedModules && !path.startsWith(nestedModules + sep),
  81. })
  82. }
  83. return directories.map(directory => relative(staging, directory))
  84. }
  85. function supports(values: string[] | undefined, value: string): boolean {
  86. return values === undefined || (!values.includes(`!${value}`)
  87. && (values.every(item => item.startsWith('!')) || values.includes(value) || values.includes('any')))
  88. }