qpdf-node 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,18 @@
1
+ export type QpdfErrorCode = "INVALID_ARGUMENT" | "OPERATION_FAILED";
2
+ /**
3
+ * The only error type this package rejects with.
4
+ *
5
+ * - `INVALID_ARGUMENT`: the request was rejected before any output was written
6
+ * (wrong type, empty path, bad page range syntax, page 0 or repeated, output
7
+ * equal to an input, use after `close()`).
8
+ * - `OPERATION_FAILED`: qpdf could not read an input or write an output (missing
9
+ * file, not a PDF, page out of bounds, wrong password, unwritable directory).
10
+ */
11
+ export declare class QpdfError extends Error {
12
+ readonly code: QpdfErrorCode;
13
+ constructor(code: QpdfErrorCode, message: string, options?: {
14
+ cause?: unknown;
15
+ });
16
+ }
17
+ /** The native addon rejects with an Error whose `code` is already a {@link QpdfErrorCode}. */
18
+ export declare function toQpdfError(error: unknown): QpdfError;
package/dist/errors.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QpdfError = void 0;
4
+ exports.toQpdfError = toQpdfError;
5
+ /**
6
+ * The only error type this package rejects with.
7
+ *
8
+ * - `INVALID_ARGUMENT`: the request was rejected before any output was written
9
+ * (wrong type, empty path, bad page range syntax, page 0 or repeated, output
10
+ * equal to an input, use after `close()`).
11
+ * - `OPERATION_FAILED`: qpdf could not read an input or write an output (missing
12
+ * file, not a PDF, page out of bounds, wrong password, unwritable directory).
13
+ */
14
+ class QpdfError extends Error {
15
+ code;
16
+ constructor(code, message, options) {
17
+ super(message, options);
18
+ this.name = "QpdfError";
19
+ this.code = code;
20
+ }
21
+ }
22
+ exports.QpdfError = QpdfError;
23
+ /** The native addon rejects with an Error whose `code` is already a {@link QpdfErrorCode}. */
24
+ function toQpdfError(error) {
25
+ if (error instanceof QpdfError) {
26
+ return error;
27
+ }
28
+ const message = error instanceof Error ? error.message : String(error);
29
+ const nativeCode = error?.code;
30
+ const code = nativeCode === "INVALID_ARGUMENT" ? "INVALID_ARGUMENT" : "OPERATION_FAILED";
31
+ return new QpdfError(code, message, { cause: error });
32
+ }
@@ -0,0 +1,7 @@
1
+ export { QpdfError } from "./errors";
2
+ export type { QpdfErrorCode } from "./errors";
3
+ export { merge, pageCount, splitPages } from "./operations";
4
+ export type { MergeInputOptions, MergeOptions, PageCountOptions, SplitPagesOptions, } from "./operations";
5
+ export { openPdf } from "./open-pdf";
6
+ export type { OpenedPdf } from "./open-pdf";
7
+ export { qpdfVersion } from "./version";
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.qpdfVersion = exports.openPdf = exports.splitPages = exports.pageCount = exports.merge = exports.QpdfError = void 0;
4
+ var errors_1 = require("./errors");
5
+ Object.defineProperty(exports, "QpdfError", { enumerable: true, get: function () { return errors_1.QpdfError; } });
6
+ var operations_1 = require("./operations");
7
+ Object.defineProperty(exports, "merge", { enumerable: true, get: function () { return operations_1.merge; } });
8
+ Object.defineProperty(exports, "pageCount", { enumerable: true, get: function () { return operations_1.pageCount; } });
9
+ Object.defineProperty(exports, "splitPages", { enumerable: true, get: function () { return operations_1.splitPages; } });
10
+ var open_pdf_1 = require("./open-pdf");
11
+ Object.defineProperty(exports, "openPdf", { enumerable: true, get: function () { return open_pdf_1.openPdf; } });
12
+ var version_1 = require("./version");
13
+ Object.defineProperty(exports, "qpdfVersion", { enumerable: true, get: function () { return version_1.qpdfVersion; } });
@@ -0,0 +1,34 @@
1
+ /** Shape of the C++ N-API addon (native/node/addon.cc). Not public API. */
2
+ export interface NativeDocument {
3
+ readonly pageCount: number;
4
+ /** Pages are 1-based integers. Resolves with the new PDF's bytes. */
5
+ extract(pages: number[]): Promise<Uint8Array>;
6
+ /** Drops this handle's reference. Extractions already started still finish. */
7
+ close(): void;
8
+ }
9
+ export interface NativeMergeInput {
10
+ path: string;
11
+ pages?: string;
12
+ }
13
+ export interface NativeMergeOptions {
14
+ inputs: NativeMergeInput[];
15
+ output: string;
16
+ password?: string;
17
+ }
18
+ export interface NativeSplitPagesOptions {
19
+ input: string;
20
+ outputPattern: string;
21
+ pagesPerFile?: number;
22
+ password?: string;
23
+ }
24
+ export interface NativePageCountOptions {
25
+ input: string;
26
+ password?: string;
27
+ }
28
+ export interface NativeBinding {
29
+ openDocument(bytes: Uint8Array, password?: string): Promise<NativeDocument>;
30
+ mergeNative(options: NativeMergeOptions): Promise<void>;
31
+ splitPagesNative(options: NativeSplitPagesOptions): Promise<void>;
32
+ pageCountNative(options: NativePageCountOptions): Promise<number>;
33
+ qpdfVersion(): string;
34
+ }
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ /** Shape of the C++ N-API addon (native/node/addon.cc). Not public API. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,30 @@
1
+ import type { NativeBinding } from "./native-binding";
2
+ /** What the loader needs to know about the machine it runs on. */
3
+ export interface RuntimePlatform {
4
+ platform: string;
5
+ arch: string;
6
+ /** Only meaningful on Linux: the C library this Node.js process runs on. */
7
+ libc: "glibc" | "musl" | undefined;
8
+ }
9
+ export declare const supportedAddonFileNames: readonly string[];
10
+ /** The bundled addon's file name for `runtime`, or undefined when no prebuilt exists. */
11
+ export declare function bundledAddonFileName(runtime: RuntimePlatform): string | undefined;
12
+ export declare function detectRuntimePlatform(): RuntimePlatform;
13
+ export interface NativeLoaderEnvironment {
14
+ /** Directory of the loader's own file (`src/` or `dist/`). */
15
+ directory: string;
16
+ runtime: RuntimePlatform;
17
+ fileExists(path: string): boolean;
18
+ requireModule(specifier: string): unknown;
19
+ }
20
+ /**
21
+ * Loads the addon. Order:
22
+ * 1. `build/Release/qpdf_node.node` next to the package, if present: a source checkout
23
+ * after `pnpm run build:native`. Published packages do not contain it.
24
+ * 2. `native/qpdf_node.<target>.node` in the package for this runtime: every supported
25
+ * platform's addon is bundled in the one published package.
26
+ * A file that exists but fails to load (wrong architecture, missing system library) is
27
+ * reported as is, never silently replaced by another binary.
28
+ */
29
+ export declare function loadNativeBinding(environment: NativeLoaderEnvironment): NativeBinding;
30
+ export declare function loadNativeBindingForCurrentProcess(directory: string): NativeBinding;
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.supportedAddonFileNames = void 0;
4
+ exports.bundledAddonFileName = bundledAddonFileName;
5
+ exports.detectRuntimePlatform = detectRuntimePlatform;
6
+ exports.loadNativeBinding = loadNativeBinding;
7
+ exports.loadNativeBindingForCurrentProcess = loadNativeBindingForCurrentProcess;
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ /** Prebuilt targets, keyed by `${platform}-${arch}` (plus `-glibc` on Linux), to their addon file names. */
11
+ const bundledAddonFileNames = {
12
+ "darwin-arm64": "qpdf_node.darwin-arm64.node",
13
+ "darwin-x64": "qpdf_node.darwin-x64.node",
14
+ "linux-x64-glibc": "qpdf_node.linux-x64-gnu.node",
15
+ "linux-arm64-glibc": "qpdf_node.linux-arm64-gnu.node",
16
+ "win32-x64": "qpdf_node.win32-x64-msvc.node",
17
+ };
18
+ exports.supportedAddonFileNames = Object.values(bundledAddonFileNames);
19
+ /** Path of the addon that `pnpm run build:native` writes, relative to `dist/` or `src/`. */
20
+ function developmentAddonPath(directory) {
21
+ return (0, node_path_1.join)(directory, "..", "build", "Release", "qpdf_node.node");
22
+ }
23
+ /** Path of a bundled addon inside the published package, relative to `dist/`. */
24
+ function bundledAddonPath(directory, addonFileName) {
25
+ return (0, node_path_1.join)(directory, "..", "native", addonFileName);
26
+ }
27
+ /** The bundled addon's file name for `runtime`, or undefined when no prebuilt exists. */
28
+ function bundledAddonFileName(runtime) {
29
+ const key = runtime.platform === "linux"
30
+ ? `linux-${runtime.arch}-${runtime.libc ?? "unknown"}`
31
+ : `${runtime.platform}-${runtime.arch}`;
32
+ return bundledAddonFileNames[key];
33
+ }
34
+ function detectRuntimePlatform() {
35
+ return {
36
+ platform: process.platform,
37
+ arch: process.arch,
38
+ libc: process.platform === "linux" ? detectLinuxLibc() : undefined,
39
+ };
40
+ }
41
+ function detectLinuxLibc() {
42
+ // glibc builds of Node.js report the glibc version; musl builds do not.
43
+ const report = process.report;
44
+ if (report === undefined || report === null) {
45
+ return undefined;
46
+ }
47
+ const previousExcludeNetwork = report.excludeNetwork;
48
+ report.excludeNetwork = true; // skip the slow network interface lookup
49
+ try {
50
+ const header = report.getReport()
51
+ .header;
52
+ return header?.glibcVersionRuntime === undefined ? "musl" : "glibc";
53
+ }
54
+ finally {
55
+ report.excludeNetwork = previousExcludeNetwork;
56
+ }
57
+ }
58
+ function describeRuntime(runtime) {
59
+ const libc = runtime.platform === "linux" ? `, libc=${runtime.libc ?? "unknown"}` : "";
60
+ return `platform=${runtime.platform}, arch=${runtime.arch}${libc}`;
61
+ }
62
+ /**
63
+ * Loads the addon. Order:
64
+ * 1. `build/Release/qpdf_node.node` next to the package, if present: a source checkout
65
+ * after `pnpm run build:native`. Published packages do not contain it.
66
+ * 2. `native/qpdf_node.<target>.node` in the package for this runtime: every supported
67
+ * platform's addon is bundled in the one published package.
68
+ * A file that exists but fails to load (wrong architecture, missing system library) is
69
+ * reported as is, never silently replaced by another binary.
70
+ */
71
+ function loadNativeBinding(environment) {
72
+ const developmentAddon = developmentAddonPath(environment.directory);
73
+ if (environment.fileExists(developmentAddon)) {
74
+ return environment.requireModule(developmentAddon);
75
+ }
76
+ const addonFileName = bundledAddonFileName(environment.runtime);
77
+ if (addonFileName === undefined) {
78
+ throw new Error(`qpdf-node has no prebuilt native addon for this platform. ${describeRuntime(environment.runtime)}. ` +
79
+ `Bundled addons: ${exports.supportedAddonFileNames.join(", ")}. ` +
80
+ "To use another platform, build the addon from source (see the qpdf-node README).");
81
+ }
82
+ const addonPath = bundledAddonPath(environment.directory, addonFileName);
83
+ if (!environment.fileExists(addonPath)) {
84
+ throw new Error(`qpdf-node could not find its bundled native addon ${addonFileName} ` +
85
+ `(${describeRuntime(environment.runtime)}, expected at ${addonPath}). ` +
86
+ "The published package contains it: reinstall qpdf-node. " +
87
+ "In a source checkout, run `pnpm run build:native` instead.");
88
+ }
89
+ try {
90
+ return environment.requireModule(addonPath);
91
+ }
92
+ catch (error) {
93
+ throw new Error(`qpdf-node found its bundled native addon ${addonFileName} but could not load it ` +
94
+ `(${describeRuntime(environment.runtime)}): ${String(error)}`, { cause: error });
95
+ }
96
+ }
97
+ function loadNativeBindingForCurrentProcess(directory) {
98
+ return loadNativeBinding({
99
+ directory,
100
+ runtime: detectRuntimePlatform(),
101
+ fileExists: node_fs_1.existsSync,
102
+ requireModule: require,
103
+ });
104
+ }
@@ -0,0 +1,2 @@
1
+ import type { NativeBinding } from "./native-binding";
2
+ export declare const native: NativeBinding;
package/dist/native.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.native = void 0;
4
+ const native_loader_1 = require("./native-loader");
5
+ // `__dirname` is `src/` or `dist/`, both one level below the package root.
6
+ exports.native = (0, native_loader_1.loadNativeBindingForCurrentProcess)(__dirname);
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A PDF opened from bytes. See {@link openPdf}. Call {@link OpenedPdf.close} in
3
+ * a `finally` block.
4
+ */
5
+ export interface OpenedPdf {
6
+ /** Number of pages in the opened PDF. */
7
+ readonly pageCount: number;
8
+ /**
9
+ * Returns a new unencrypted PDF holding the given pages, in the given order.
10
+ *
11
+ * Pages are 1-based integers between 1 and {@link OpenedPdf.pageCount}. The
12
+ * array must not be empty and must not repeat a page. Every page is validated
13
+ * before any work starts. May be called any number of times, including
14
+ * concurrently, until {@link OpenedPdf.close}. Calls on one `OpenedPdf` run
15
+ * one after another on the libuv thread pool (qpdf's document objects are not
16
+ * thread-safe); different `OpenedPdf`s run in parallel.
17
+ *
18
+ * Streams (page content, images, fonts) are copied as they are, without
19
+ * decoding or recompressing. Resources a page inherits from the page tree are
20
+ * copied onto the page.
21
+ */
22
+ extract(pages: readonly number[]): Promise<Uint8Array>;
23
+ /**
24
+ * Releases the parsed document. Idempotent. Waits for extractions already in
25
+ * progress, which still complete; later `extract` calls reject with
26
+ * `INVALID_ARGUMENT`.
27
+ */
28
+ close(): Promise<void>;
29
+ }
30
+ /**
31
+ * Opens a PDF from bytes so that pages can be extracted from it.
32
+ *
33
+ * The bytes are copied into the addon and parsed once, on the libuv thread
34
+ * pool. The parsed qpdf document stays in memory inside the returned handle, and
35
+ * every `extract` reuses it: nothing is written to disk and the input is not
36
+ * parsed again. Changing `input` after this call resolves has no effect.
37
+ *
38
+ * Always call {@link OpenedPdf.close} in a `finally` block. If you forget, the
39
+ * memory is released when the handle is garbage collected, which may be late.
40
+ *
41
+ * Encrypted inputs that need a real password are not supported through this
42
+ * function; inputs with an empty user password open and the output is
43
+ * unencrypted. A damaged PDF is repaired when qpdf can (warnings are
44
+ * discarded); otherwise opening rejects.
45
+ *
46
+ * Rejects with `INVALID_ARGUMENT` when `input` is not a non-empty `Uint8Array`
47
+ * (a `Buffer` is one), and with `OPERATION_FAILED` when the bytes are not a
48
+ * readable PDF.
49
+ */
50
+ export declare function openPdf(input: Uint8Array): Promise<OpenedPdf>;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openPdf = openPdf;
4
+ const errors_1 = require("./errors");
5
+ const native_1 = require("./native");
6
+ const options_1 = require("./options");
7
+ /**
8
+ * Opens a PDF from bytes so that pages can be extracted from it.
9
+ *
10
+ * The bytes are copied into the addon and parsed once, on the libuv thread
11
+ * pool. The parsed qpdf document stays in memory inside the returned handle, and
12
+ * every `extract` reuses it: nothing is written to disk and the input is not
13
+ * parsed again. Changing `input` after this call resolves has no effect.
14
+ *
15
+ * Always call {@link OpenedPdf.close} in a `finally` block. If you forget, the
16
+ * memory is released when the handle is garbage collected, which may be late.
17
+ *
18
+ * Encrypted inputs that need a real password are not supported through this
19
+ * function; inputs with an empty user password open and the output is
20
+ * unencrypted. A damaged PDF is repaired when qpdf can (warnings are
21
+ * discarded); otherwise opening rejects.
22
+ *
23
+ * Rejects with `INVALID_ARGUMENT` when `input` is not a non-empty `Uint8Array`
24
+ * (a `Buffer` is one), and with `OPERATION_FAILED` when the bytes are not a
25
+ * readable PDF.
26
+ */
27
+ async function openPdf(input) {
28
+ if (!(input instanceof Uint8Array)) {
29
+ throw (0, options_1.invalidArgument)(`openPdf input must be a Uint8Array or Buffer. received=${(0, options_1.describe)(input)}`);
30
+ }
31
+ if (input.length === 0) {
32
+ throw (0, options_1.invalidArgument)("openPdf input must not be empty. byteLength=0");
33
+ }
34
+ let document;
35
+ try {
36
+ document = await native_1.native.openDocument(input);
37
+ }
38
+ catch (error) {
39
+ const qpdfError = (0, errors_1.toQpdfError)(error);
40
+ throw new errors_1.QpdfError(qpdfError.code, `openPdf could not read the input bytes. byteLength=${input.length}: ${qpdfError.message}`, { cause: error });
41
+ }
42
+ return new NativePdf(document);
43
+ }
44
+ class NativePdf {
45
+ pageCount;
46
+ document;
47
+ inFlight = new Set();
48
+ closing;
49
+ constructor(document) {
50
+ this.document = document;
51
+ this.pageCount = document.pageCount;
52
+ }
53
+ extract(pages) {
54
+ if (this.closing !== undefined) {
55
+ return Promise.reject((0, options_1.invalidArgument)("extract called on a closed OpenedPdf"));
56
+ }
57
+ try {
58
+ this.validatePages(pages);
59
+ }
60
+ catch (error) {
61
+ return Promise.reject(error);
62
+ }
63
+ const extraction = this.document.extract([...pages]).catch((error) => {
64
+ throw (0, errors_1.toQpdfError)(error);
65
+ });
66
+ this.inFlight.add(extraction);
67
+ const forget = () => {
68
+ this.inFlight.delete(extraction);
69
+ };
70
+ extraction.then(forget, forget);
71
+ return extraction;
72
+ }
73
+ close() {
74
+ if (this.closing === undefined) {
75
+ this.closing = this.releaseAfterInFlight();
76
+ }
77
+ return this.closing;
78
+ }
79
+ validatePages(pages) {
80
+ if (!Array.isArray(pages)) {
81
+ throw (0, options_1.invalidArgument)(`extract pages must be an array. received=${(0, options_1.describe)(pages)}`);
82
+ }
83
+ if (pages.length === 0) {
84
+ throw (0, options_1.invalidArgument)("extract pages must not be empty. pages=[]");
85
+ }
86
+ const seen = new Set();
87
+ pages.forEach((page, index) => {
88
+ if (!Number.isInteger(page) || page < 1 || page > this.pageCount) {
89
+ throw (0, options_1.invalidArgument)(`extract pages[${index}] must be an integer between 1 and ${this.pageCount}. received=${String(page)}`);
90
+ }
91
+ if (seen.has(page)) {
92
+ throw (0, options_1.invalidArgument)(`extract pages must not repeat a page. pages[${index}]=${page}, pageCount=${this.pageCount}`);
93
+ }
94
+ seen.add(page);
95
+ });
96
+ }
97
+ async releaseAfterInFlight() {
98
+ await Promise.allSettled([...this.inFlight]);
99
+ this.document.close();
100
+ }
101
+ }
@@ -0,0 +1,68 @@
1
+ /** One merge input: a whole PDF, or the pages of it selected by `pages`. */
2
+ export interface MergeInputOptions {
3
+ /** Path to the input PDF. Relative paths are relative to the process working directory. */
4
+ path: string;
5
+ /**
6
+ * Page range selecting pages of this input, in output order: `"1-3"`,
7
+ * `"4-z"`, `"r1"`, `"7-3,1"`. Pages are 1-based, `z` is the last page, `rN` is
8
+ * the Nth page from the end (`r1` is the last), `7-3` runs backwards, and
9
+ * commas combine parts in the order written. A page may be listed more than
10
+ * once. Bad syntax rejects with `INVALID_ARGUMENT`; out-of-bounds pages reject
11
+ * with `OPERATION_FAILED` and are never clamped. Omit to take every page.
12
+ */
13
+ pages?: string;
14
+ }
15
+ export interface MergeOptions {
16
+ /** Inputs in output order. A plain string is shorthand for `{ path }`. */
17
+ inputs: ReadonlyArray<string | MergeInputOptions>;
18
+ /**
19
+ * Where to write the merged PDF. An existing file is replaced. The directory
20
+ * must already exist. It must not be one of the inputs.
21
+ */
22
+ output: string;
23
+ /** Only for encrypted inputs that do not open with the empty user password. */
24
+ password?: string;
25
+ }
26
+ export interface SplitPagesOptions {
27
+ /** Path to the input PDF. */
28
+ input: string;
29
+ /**
30
+ * Output path template containing exactly one `%d`, e.g. `"out/page-%d.pdf"`.
31
+ * With one page per file, `%d` is the original page number, zero-padded to
32
+ * the width of the last page number (`page-07.pdf` in a 12-page file). With
33
+ * `pagesPerFile > 1`, `%d` is the 1-based chunk number, zero-padded to the
34
+ * width of the chunk count. Existing files are replaced. The directory must
35
+ * already exist.
36
+ */
37
+ outputPattern: string;
38
+ /** Consecutive pages per output file. Defaults to 1. */
39
+ pagesPerFile?: number;
40
+ /** Only for encrypted inputs that do not open with the empty user password. */
41
+ password?: string;
42
+ }
43
+ export interface PageCountOptions {
44
+ input: string;
45
+ /** Only for encrypted inputs that do not open with the empty user password. */
46
+ password?: string;
47
+ }
48
+ /**
49
+ * Concatenates PDFs into one unencrypted PDF.
50
+ *
51
+ * The work runs on the libuv thread pool, not on the event loop. Rejects with
52
+ * {@link QpdfError}.
53
+ */
54
+ export declare function merge(options: MergeOptions): Promise<void>;
55
+ /**
56
+ * Splits a PDF into one file per page, or per chunk of `pagesPerFile` pages.
57
+ * Outputs are unencrypted. The names of the written files follow
58
+ * {@link SplitPagesOptions.outputPattern}.
59
+ *
60
+ * The work runs on the libuv thread pool, not on the event loop. Rejects with
61
+ * {@link QpdfError}.
62
+ */
63
+ export declare function splitPages(options: SplitPagesOptions): Promise<void>;
64
+ /**
65
+ * Counts pages by walking the page tree (not by trusting the `/Count` entry).
66
+ * Rejects with {@link QpdfError}.
67
+ */
68
+ export declare function pageCount(options: PageCountOptions): Promise<number>;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.merge = merge;
4
+ exports.splitPages = splitPages;
5
+ exports.pageCount = pageCount;
6
+ const native_1 = require("./native");
7
+ const errors_1 = require("./errors");
8
+ const options_1 = require("./options");
9
+ /**
10
+ * Concatenates PDFs into one unencrypted PDF.
11
+ *
12
+ * The work runs on the libuv thread pool, not on the event loop. Rejects with
13
+ * {@link QpdfError}.
14
+ */
15
+ async function merge(options) {
16
+ try {
17
+ await native_1.native.mergeNative(parseMergeOptions(options));
18
+ }
19
+ catch (error) {
20
+ throw (0, errors_1.toQpdfError)(error);
21
+ }
22
+ }
23
+ /**
24
+ * Splits a PDF into one file per page, or per chunk of `pagesPerFile` pages.
25
+ * Outputs are unencrypted. The names of the written files follow
26
+ * {@link SplitPagesOptions.outputPattern}.
27
+ *
28
+ * The work runs on the libuv thread pool, not on the event loop. Rejects with
29
+ * {@link QpdfError}.
30
+ */
31
+ async function splitPages(options) {
32
+ try {
33
+ await native_1.native.splitPagesNative(parseSplitPagesOptions(options));
34
+ }
35
+ catch (error) {
36
+ throw (0, errors_1.toQpdfError)(error);
37
+ }
38
+ }
39
+ /**
40
+ * Counts pages by walking the page tree (not by trusting the `/Count` entry).
41
+ * Rejects with {@link QpdfError}.
42
+ */
43
+ async function pageCount(options) {
44
+ try {
45
+ return await native_1.native.pageCountNative(parsePageCountOptions(options));
46
+ }
47
+ catch (error) {
48
+ throw (0, errors_1.toQpdfError)(error);
49
+ }
50
+ }
51
+ function parseMergeOptions(options) {
52
+ const fields = (0, options_1.requireObject)("merge options", options);
53
+ const inputs = fields.inputs;
54
+ if (!Array.isArray(inputs)) {
55
+ throw (0, options_1.invalidArgument)(`merge options.inputs must be an array. received=${typeof inputs}`);
56
+ }
57
+ return {
58
+ inputs: inputs.map((input, index) => parseMergeInput(`merge options.inputs[${index}]`, input)),
59
+ output: (0, options_1.requireNonEmptyString)("merge options.output", fields.output),
60
+ password: (0, options_1.optionalString)("merge options.password", fields.password),
61
+ };
62
+ }
63
+ function parseMergeInput(label, input) {
64
+ if (typeof input === "string") {
65
+ return { path: (0, options_1.requireNonEmptyString)(label, input) };
66
+ }
67
+ const fields = (0, options_1.requireObject)(label, input);
68
+ return {
69
+ path: (0, options_1.requireNonEmptyString)(`${label}.path`, fields.path),
70
+ pages: (0, options_1.optionalString)(`${label}.pages`, fields.pages),
71
+ };
72
+ }
73
+ function parseSplitPagesOptions(options) {
74
+ const fields = (0, options_1.requireObject)("splitPages options", options);
75
+ return {
76
+ input: (0, options_1.requireNonEmptyString)("splitPages options.input", fields.input),
77
+ outputPattern: (0, options_1.requireNonEmptyString)("splitPages options.outputPattern", fields.outputPattern),
78
+ pagesPerFile: (0, options_1.optionalPositiveUint32)("splitPages options.pagesPerFile", fields.pagesPerFile),
79
+ password: (0, options_1.optionalString)("splitPages options.password", fields.password),
80
+ };
81
+ }
82
+ function parsePageCountOptions(options) {
83
+ const fields = (0, options_1.requireObject)("pageCount options", options);
84
+ return {
85
+ input: (0, options_1.requireNonEmptyString)("pageCount options.input", fields.input),
86
+ password: (0, options_1.optionalString)("pageCount options.password", fields.password),
87
+ };
88
+ }
@@ -0,0 +1,7 @@
1
+ import { QpdfError } from "./errors";
2
+ export declare function invalidArgument(message: string): QpdfError;
3
+ export declare function describe(value: unknown): string;
4
+ export declare function requireObject(label: string, value: unknown): Record<string, unknown>;
5
+ export declare function requireNonEmptyString(label: string, value: unknown): string;
6
+ export declare function optionalString(label: string, value: unknown): string | undefined;
7
+ export declare function optionalPositiveUint32(label: string, value: unknown): number | undefined;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.invalidArgument = invalidArgument;
4
+ exports.describe = describe;
5
+ exports.requireObject = requireObject;
6
+ exports.requireNonEmptyString = requireNonEmptyString;
7
+ exports.optionalString = optionalString;
8
+ exports.optionalPositiveUint32 = optionalPositiveUint32;
9
+ const errors_1 = require("./errors");
10
+ function invalidArgument(message) {
11
+ return new errors_1.QpdfError("INVALID_ARGUMENT", message);
12
+ }
13
+ function describe(value) {
14
+ if (value === null) {
15
+ return "null";
16
+ }
17
+ if (Array.isArray(value)) {
18
+ return "array";
19
+ }
20
+ return typeof value;
21
+ }
22
+ function requireObject(label, value) {
23
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
24
+ throw invalidArgument(`${label} must be an object. received=${describe(value)}`);
25
+ }
26
+ return value;
27
+ }
28
+ function requireNonEmptyString(label, value) {
29
+ if (typeof value !== "string") {
30
+ throw invalidArgument(`${label} must be a string. received=${describe(value)}`);
31
+ }
32
+ if (value.length === 0) {
33
+ throw invalidArgument(`${label} must not be empty`);
34
+ }
35
+ return value;
36
+ }
37
+ function optionalString(label, value) {
38
+ if (value === undefined) {
39
+ return undefined;
40
+ }
41
+ if (typeof value !== "string") {
42
+ throw invalidArgument(`${label} must be a string when provided. received=${describe(value)}`);
43
+ }
44
+ return value;
45
+ }
46
+ const MAX_UINT32 = 4_294_967_295;
47
+ function optionalPositiveUint32(label, value) {
48
+ if (value === undefined) {
49
+ return undefined;
50
+ }
51
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_UINT32) {
52
+ throw invalidArgument(`${label} must be an integer between 1 and ${MAX_UINT32} when provided. received=${String(value)}`);
53
+ }
54
+ return value;
55
+ }
@@ -0,0 +1,2 @@
1
+ /** The qpdf library version compiled into the addon, e.g. `"12.4.2"`. */
2
+ export declare function qpdfVersion(): string;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.qpdfVersion = qpdfVersion;
4
+ const native_1 = require("./native");
5
+ /** The qpdf library version compiled into the addon, e.g. `"12.4.2"`. */
6
+ function qpdfVersion() {
7
+ return native_1.native.qpdfVersion();
8
+ }
Binary file