forked from unjs/unpdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
77 lines (66 loc) · 1.97 KB
/
Copy pathutils.ts
File metadata and controls
77 lines (66 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import type { DocumentInitParameters, PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api'
import type * as PDFJS from 'pdfjs-dist/types/src/pdf'
let resolvedModule: typeof PDFJS | undefined
// eslint-disable-next-line node/prefer-global/process
export const isNode = globalThis.process?.release?.name === 'node'
export const isBrowser = typeof window !== 'undefined'
/**
* Returns a PDFDocumentProxy instance from a given binary data.
*
* Applies the following defaults:
* - `isEvalSupported: false`
* - `useSystemFonts: true`
*/
export async function getDocumentProxy(
data: DocumentInitParameters['data'],
options: DocumentInitParameters = {},
) {
const { getDocument } = await getResolvedPDFJS()
const pdf = await getDocument({
data,
isEvalSupported: false,
// See: https://github.com/mozilla/pdf.js/issues/4244#issuecomment-1479534301
useSystemFonts: true,
...options,
}).promise
return pdf
}
export async function getResolvedPDFJS(): Promise<typeof PDFJS> {
if (!resolvedModule) {
await resolvePDFJSImport()
}
return resolvedModule!
}
export async function resolvePDFJSImport(
pdfjsResolver?: () => Promise<any>,
{ reload = false } = {},
) {
if (resolvedModule && !reload) {
return
}
if (pdfjsResolver) {
try {
resolvedModule = await interopDefault(pdfjsResolver())
return
}
catch (error) {
throw new Error(`PDF.js could not be resolved: ${error}`)
}
}
try {
// @ts-expect-error: Type mismatch
resolvedModule = await import('unpdf/pdfjs')
}
catch (error) {
throw new Error(`Serverless PDF.js bundle could not be resolved: ${error}`)
}
}
export function isPDFDocumentProxy(data: unknown): data is PDFDocumentProxy {
return typeof data === 'object' && data !== null && '_pdfInfo' in data
}
export async function interopDefault<T>(
m: T | Promise<T>,
): Promise<T extends { default: infer U } ? U : T> {
const resolved = await m
return (resolved as any).default || resolved
}