effect-pdf 0.0.0-stage → 0.0.1
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.md +49 -2
- package/SPEC.md +73 -0
- package/dist/Diagnostic.d.ts +69 -0
- package/dist/Diagnostic.js +15 -0
- package/dist/Document.d.ts +43 -0
- package/dist/Document.js +127 -0
- package/dist/Object.d.ts +63 -0
- package/dist/Object.js +68 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/node.d.ts +14 -0
- package/dist/node.js +25 -0
- package/package.json +88 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ben Jacobson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
-
#
|
|
1
|
+
# effect-pdf
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Effect-native PDF parsing, creation, manipulation, and AcroForm engine for TypeScript.
|
|
4
|
+
|
|
5
|
+
> **Status:** M0 scaffold (`0.0.0-stage`). Core toolchain, typed diagnostics, PDF object model, minimal PDF 1.7 document writer, and Node file helpers are in place. Full parser, content streams, fonts, images, and AcroForms are tracked in [PLAN.md](./PLAN.md).
|
|
6
|
+
|
|
7
|
+
## Architecture Overview
|
|
8
|
+
|
|
9
|
+
- **Pure, browser-safe core (`effect-pdf`):** Zero Node.js built-ins in the main entry point; all runtime I/O lives behind explicit Effect services or the `effect-pdf/node` entrypoint.
|
|
10
|
+
- **Typed error channels (`effect-pdf/Diagnostic`):** Every failure mode (`PdfParseError`, `PdfEncryptedError`, `PdfCompressionError`, `PdfFontError`, `PdfImageError`, `PdfFormError`, `PdfLimitError`) is a `Data.TaggedError`, composable with `Effect.catchTag`.
|
|
11
|
+
- **Immutable PDF object model (`effect-pdf/Object`):** Discriminated-union representation of all PDF 1.7 primitives (`PdfNull`, `PdfBool`, `PdfNumber`, `PdfName`, `PdfString`, `PdfHexString`, `PdfArray`, `PdfDict`, `PdfStream`, `PdfRef`) with constructors and type guards.
|
|
12
|
+
- **Pipeable document API (`effect-pdf/Document`):** `Pipeable` / `Function.dual` combinators for creating, inspecting, transforming, and serializing PDF documents as `Uint8Array` or streams.
|
|
13
|
+
- **Node helpers (`effect-pdf/node`):** `readPdfFile` and `writePdfFile` built on `node:fs/promises` wrapped in `Effect.tryPromise`.
|
|
14
|
+
|
|
15
|
+
See [SPEC.md](./SPEC.md) for the full design specification and [PLAN.md](./PLAN.md) for the M0–M6 roadmap.
|
|
16
|
+
|
|
17
|
+
## Quick Example
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { Effect } from "effect";
|
|
21
|
+
import { Document } from "effect-pdf";
|
|
22
|
+
|
|
23
|
+
const program = Effect.gen(function* () {
|
|
24
|
+
const doc = yield* Document.create({
|
|
25
|
+
title: "Hello Effect PDF",
|
|
26
|
+
pages: [{ width: 612, height: 792 }],
|
|
27
|
+
});
|
|
28
|
+
return yield* Document.save(doc);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const bytes = await Effect.runPromise(program);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Development
|
|
35
|
+
|
|
36
|
+
Requires Node.js `>= 22.12.0` and `pnpm@10.20.0`.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pnpm install
|
|
40
|
+
pnpm typecheck # TypeScript strict typecheck
|
|
41
|
+
pnpm test # Build + Vitest suite (including pdf-lib oracle checks)
|
|
42
|
+
pnpm lint # oxlint (--deny-warnings)
|
|
43
|
+
pnpm format:check # oxfmt check
|
|
44
|
+
pnpm format # Auto-format with oxfmt
|
|
45
|
+
pnpm check # Full verification pipeline (typecheck + test + lint + format:check)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## License
|
|
49
|
+
|
|
50
|
+
MIT © 2026 Ben Jacobson
|
package/SPEC.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# effect-pdf Specification
|
|
2
|
+
|
|
3
|
+
## 1. Goals & Design Principles
|
|
4
|
+
|
|
5
|
+
`effect-pdf` is an Effect-native PDF 1.7 library for parsing, creating, modifying, and filling PDF documents in TypeScript across browsers, edge runtimes, and Node.js.
|
|
6
|
+
|
|
7
|
+
1. **Zero untyped throws:** Every fallible operation returns an `Effect.Effect<A, E, R>` with a structured `Data.TaggedError` union.
|
|
8
|
+
2. **Pure core, explicit capabilities:** The root package (`effect-pdf`) has zero Node.js built-in imports. Filesystem, font loading, and external codecs are provided via Effect services (`Context.Tag` / `Layer`) or `effect-pdf/node`.
|
|
9
|
+
3. **Immutable & pipeable API:** Document operations use `Pipeable` and `Function.dual` so both data-first and data-last (`pipe(...)`) styles work seamlessly.
|
|
10
|
+
4. **Bounded by default:** Parsing and decompression enforce configurable resource limits (`PdfLimitError`) to guard against zip bombs, deeply nested objects, and oversized xref tables.
|
|
11
|
+
5. **Differential conformance:** Generated and round-tripped PDFs are verified against `pdf-lib` (dev-only oracle) and spec fixtures.
|
|
12
|
+
|
|
13
|
+
## 2. Module Layout
|
|
14
|
+
|
|
15
|
+
| Export | Responsibility |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `effect-pdf` | Root namespace barrel (`Diagnostic`, `PdfObject`, `Document`, top-level `create` / `save`). |
|
|
18
|
+
| `effect-pdf/Diagnostic` | `Data.TaggedError` hierarchy for all PDF failures. |
|
|
19
|
+
| `effect-pdf/Object` | PDF 1.7 object AST, constructors, and guards. |
|
|
20
|
+
| `effect-pdf/Document` | `PdfDocument` model, `create`, `load` (M2), `save`, and `Pipeable` / `Function.dual` combinators. |
|
|
21
|
+
| `effect-pdf/node` | Node.js `fs/promises` helpers (`readPdfFile`, `writePdfFile`). |
|
|
22
|
+
|
|
23
|
+
Future milestones add `./Parser`, `./Writer`, `./Stream`, `./Font`, `./Image`, `./Form`, and `./Schema`.
|
|
24
|
+
|
|
25
|
+
## 3. Error Hierarchy (`Diagnostic`)
|
|
26
|
+
|
|
27
|
+
All errors extend `Data.TaggedError` so callers can recover selectively via `Effect.catchTag`:
|
|
28
|
+
|
|
29
|
+
- `PdfParseError` — lexical, syntax, xref, or structural parse failures (with optional `offset`, `objectNumber`, `generation`).
|
|
30
|
+
- `PdfEncryptedError` — encrypted PDFs requiring credentials or unsupported security handlers.
|
|
31
|
+
- `PdfCompressionError` — stream filter decode/encode failures (Flate, ASCII85, ASCIIHex, LZW, RunLength).
|
|
32
|
+
- `PdfFontError` — font lookup, embedding, subsetting, or glyph encoding failures.
|
|
33
|
+
- `PdfImageError` — PNG/JPEG decoding, alpha channel, or color space errors.
|
|
34
|
+
- `PdfFormError` — missing AcroForm, unknown field, invalid field value, or appearance stream errors.
|
|
35
|
+
- `PdfLimitError` — exceeded resource budgets (`maxBytes`, `maxObjects`, `maxDepth`, `maxDecompressedBytes`, `maxPages`).
|
|
36
|
+
|
|
37
|
+
## 4. PDF Object Model (`Object`)
|
|
38
|
+
|
|
39
|
+
All PDF primitives are represented as readonly tagged records:
|
|
40
|
+
|
|
41
|
+
- `PdfNull` (`{ _tag: "PdfNull" }`)
|
|
42
|
+
- `PdfBool` (`{ _tag: "PdfBool", value: boolean }`)
|
|
43
|
+
- `PdfNumber` (`{ _tag: "PdfNumber", value: number }`)
|
|
44
|
+
- `PdfName` (`{ _tag: "PdfName", value: string }`)
|
|
45
|
+
- `PdfString` (`{ _tag: "PdfString", value: string }`)
|
|
46
|
+
- `PdfHexString` (`{ _tag: "PdfHexString", bytes: Uint8Array }`)
|
|
47
|
+
- `PdfArray` (`{ _tag: "PdfArray", items: ReadonlyArray<PdfObject> }`)
|
|
48
|
+
- `PdfDict` (`{ _tag: "PdfDict", entries: ReadonlyMap<string, PdfObject> }`)
|
|
49
|
+
- `PdfStream` (`{ _tag: "PdfStream", dict: PdfDict, data: Uint8Array }`)
|
|
50
|
+
- `PdfRef` (`{ _tag: "PdfRef", objectNumber: number, generation: number }`)
|
|
51
|
+
|
|
52
|
+
## 5. Document, Combinators & Services
|
|
53
|
+
|
|
54
|
+
- **Pipeable & dual combinators:** `Document.save`, page manipulation (`addPage`, `removePage`, `copyPages`, `merge`), metadata setters, and drawing helpers follow `Function.dual` and `Pipeable.Pipeable`.
|
|
55
|
+
- **`FontProvider` service (M4):** A `Context.Tag` resolving standard 14 PDF fonts (built-in) and custom TrueType/OpenType fonts via pluggable `Layer`s (in-memory, filesystem, fetch).
|
|
56
|
+
- **AcroForms + `Effect.Schema` (M5):** Typed form reading, filling, flattening, and schema-derived validation (`Form.decode(schema)` / `Form.fill(schema, data)`).
|
|
57
|
+
- **Streaming & Adapters (M6):** `Stream.Stream<Uint8Array>` serialization/ingestion and Web `ReadableStream` / Node adapters alongside `effect-pdf/node`.
|
|
58
|
+
|
|
59
|
+
## 6. Resource Limits & Security
|
|
60
|
+
|
|
61
|
+
Every parser and stream filter accepts a `PdfLimits` configuration (or `PdfLimitsService` layer) with safe defaults:
|
|
62
|
+
- Maximum input byte size
|
|
63
|
+
- Maximum indirect object count and xref entries
|
|
64
|
+
- Maximum container nesting depth
|
|
65
|
+
- Maximum decompressed stream size and inflation ratio
|
|
66
|
+
|
|
67
|
+
Exceeding any budget fails cleanly with `PdfLimitError`.
|
|
68
|
+
|
|
69
|
+
## 7. Differential Conformance
|
|
70
|
+
|
|
71
|
+
Continuous tests validate `effect-pdf` outputs against `pdf-lib` (dev dependency only, never bundled or shipped):
|
|
72
|
+
- Every generated PDF must parse cleanly with `pdf-lib` and preserve page count, dimensions, metadata, and form fields.
|
|
73
|
+
- Parser round-trips compare object graphs and page geometry against `pdf-lib` on synthetic and real-world PDFs.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
declare const PdfParseError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
2
|
+
readonly _tag: "PdfParseError";
|
|
3
|
+
} & Readonly<A>;
|
|
4
|
+
export declare class PdfParseError extends PdfParseError_base<{
|
|
5
|
+
readonly message: string;
|
|
6
|
+
readonly offset?: number | undefined;
|
|
7
|
+
readonly objectNumber?: number | undefined;
|
|
8
|
+
readonly generation?: number | undefined;
|
|
9
|
+
readonly cause?: unknown;
|
|
10
|
+
}> {
|
|
11
|
+
}
|
|
12
|
+
declare const PdfEncryptedError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
13
|
+
readonly _tag: "PdfEncryptedError";
|
|
14
|
+
} & Readonly<A>;
|
|
15
|
+
export declare class PdfEncryptedError extends PdfEncryptedError_base<{
|
|
16
|
+
readonly message: string;
|
|
17
|
+
readonly filter?: string | undefined;
|
|
18
|
+
readonly version?: number | undefined;
|
|
19
|
+
readonly revision?: number | undefined;
|
|
20
|
+
}> {
|
|
21
|
+
}
|
|
22
|
+
declare const PdfCompressionError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
23
|
+
readonly _tag: "PdfCompressionError";
|
|
24
|
+
} & Readonly<A>;
|
|
25
|
+
export declare class PdfCompressionError extends PdfCompressionError_base<{
|
|
26
|
+
readonly message: string;
|
|
27
|
+
readonly filter?: string | undefined;
|
|
28
|
+
readonly cause?: unknown;
|
|
29
|
+
}> {
|
|
30
|
+
}
|
|
31
|
+
declare const PdfFontError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
32
|
+
readonly _tag: "PdfFontError";
|
|
33
|
+
} & Readonly<A>;
|
|
34
|
+
export declare class PdfFontError extends PdfFontError_base<{
|
|
35
|
+
readonly message: string;
|
|
36
|
+
readonly fontName?: string | undefined;
|
|
37
|
+
readonly cause?: unknown;
|
|
38
|
+
}> {
|
|
39
|
+
}
|
|
40
|
+
declare const PdfImageError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
41
|
+
readonly _tag: "PdfImageError";
|
|
42
|
+
} & Readonly<A>;
|
|
43
|
+
export declare class PdfImageError extends PdfImageError_base<{
|
|
44
|
+
readonly message: string;
|
|
45
|
+
readonly format?: string | undefined;
|
|
46
|
+
readonly cause?: unknown;
|
|
47
|
+
}> {
|
|
48
|
+
}
|
|
49
|
+
declare const PdfFormError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
50
|
+
readonly _tag: "PdfFormError";
|
|
51
|
+
} & Readonly<A>;
|
|
52
|
+
export declare class PdfFormError extends PdfFormError_base<{
|
|
53
|
+
readonly message: string;
|
|
54
|
+
readonly fieldName?: string | undefined;
|
|
55
|
+
readonly cause?: unknown;
|
|
56
|
+
}> {
|
|
57
|
+
}
|
|
58
|
+
declare const PdfLimitError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
59
|
+
readonly _tag: "PdfLimitError";
|
|
60
|
+
} & Readonly<A>;
|
|
61
|
+
export declare class PdfLimitError extends PdfLimitError_base<{
|
|
62
|
+
readonly message: string;
|
|
63
|
+
readonly limit: string;
|
|
64
|
+
readonly actual: number;
|
|
65
|
+
readonly max: number;
|
|
66
|
+
}> {
|
|
67
|
+
}
|
|
68
|
+
export type PdfError = PdfParseError | PdfEncryptedError | PdfCompressionError | PdfFontError | PdfImageError | PdfFormError | PdfLimitError;
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Data } from "effect";
|
|
2
|
+
export class PdfParseError extends Data.TaggedError("PdfParseError") {
|
|
3
|
+
}
|
|
4
|
+
export class PdfEncryptedError extends Data.TaggedError("PdfEncryptedError") {
|
|
5
|
+
}
|
|
6
|
+
export class PdfCompressionError extends Data.TaggedError("PdfCompressionError") {
|
|
7
|
+
}
|
|
8
|
+
export class PdfFontError extends Data.TaggedError("PdfFontError") {
|
|
9
|
+
}
|
|
10
|
+
export class PdfImageError extends Data.TaggedError("PdfImageError") {
|
|
11
|
+
}
|
|
12
|
+
export class PdfFormError extends Data.TaggedError("PdfFormError") {
|
|
13
|
+
}
|
|
14
|
+
export class PdfLimitError extends Data.TaggedError("PdfLimitError") {
|
|
15
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Effect, Pipeable } from "effect";
|
|
2
|
+
import { PdfLimitError } from "./Diagnostic.js";
|
|
3
|
+
export declare const TypeId: unique symbol;
|
|
4
|
+
export type TypeId = typeof TypeId;
|
|
5
|
+
export interface PdfPageSpec {
|
|
6
|
+
readonly width: number;
|
|
7
|
+
readonly height: number;
|
|
8
|
+
}
|
|
9
|
+
export interface PdfMetadata {
|
|
10
|
+
readonly title?: string | undefined;
|
|
11
|
+
readonly author?: string | undefined;
|
|
12
|
+
readonly subject?: string | undefined;
|
|
13
|
+
readonly creator?: string | undefined;
|
|
14
|
+
readonly producer?: string | undefined;
|
|
15
|
+
}
|
|
16
|
+
export interface CreateDocumentOptions {
|
|
17
|
+
readonly pages?: ReadonlyArray<PdfPageSpec> | undefined;
|
|
18
|
+
readonly metadata?: PdfMetadata | undefined;
|
|
19
|
+
}
|
|
20
|
+
export interface SaveOptions {
|
|
21
|
+
readonly maxBytes?: number | undefined;
|
|
22
|
+
}
|
|
23
|
+
export declare const LETTER_PAGE: PdfPageSpec;
|
|
24
|
+
export interface PdfDocument extends Pipeable.Pipeable {
|
|
25
|
+
readonly [TypeId]: TypeId;
|
|
26
|
+
readonly version: "1.7";
|
|
27
|
+
readonly pages: ReadonlyArray<PdfPageSpec>;
|
|
28
|
+
readonly metadata: PdfMetadata;
|
|
29
|
+
}
|
|
30
|
+
export declare const isPdfDocument: (value: unknown) => value is PdfDocument;
|
|
31
|
+
export declare const create: (options?: CreateDocumentOptions) => Effect.Effect<PdfDocument>;
|
|
32
|
+
export declare const addPage: {
|
|
33
|
+
(page?: PdfPageSpec): (self: PdfDocument) => PdfDocument;
|
|
34
|
+
(self: PdfDocument, page?: PdfPageSpec): PdfDocument;
|
|
35
|
+
};
|
|
36
|
+
export declare const setMetadata: {
|
|
37
|
+
(metadata: PdfMetadata): (self: PdfDocument) => PdfDocument;
|
|
38
|
+
(self: PdfDocument, metadata: PdfMetadata): PdfDocument;
|
|
39
|
+
};
|
|
40
|
+
export declare const save: {
|
|
41
|
+
(options?: SaveOptions): (self: PdfDocument) => Effect.Effect<Uint8Array, PdfLimitError>;
|
|
42
|
+
(self: PdfDocument, options?: SaveOptions): Effect.Effect<Uint8Array, PdfLimitError>;
|
|
43
|
+
};
|
package/dist/Document.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { Effect, Function as Fn, Pipeable } from "effect";
|
|
2
|
+
import { PdfLimitError } from "./Diagnostic.js";
|
|
3
|
+
export const TypeId = Symbol.for("effect-pdf/Document");
|
|
4
|
+
export const LETTER_PAGE = { width: 612, height: 792 };
|
|
5
|
+
const DocumentProto = {
|
|
6
|
+
pipe() {
|
|
7
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
8
|
+
},
|
|
9
|
+
};
|
|
10
|
+
const makeDocument = (pages, metadata) => Object.assign(Object.create(DocumentProto), {
|
|
11
|
+
[TypeId]: TypeId,
|
|
12
|
+
version: "1.7",
|
|
13
|
+
pages: [...pages],
|
|
14
|
+
metadata: { ...metadata },
|
|
15
|
+
});
|
|
16
|
+
export const isPdfDocument = (value) => typeof value === "object" && value !== null && TypeId in value;
|
|
17
|
+
export const create = (options) => Effect.sync(() => makeDocument(options?.pages ?? [LETTER_PAGE], {
|
|
18
|
+
producer: "effect-pdf",
|
|
19
|
+
...options?.metadata,
|
|
20
|
+
}));
|
|
21
|
+
export const addPage = Fn.dual((args) => isPdfDocument(args[0]), (self, page = LETTER_PAGE) => makeDocument([...self.pages, page], self.metadata));
|
|
22
|
+
export const setMetadata = Fn.dual(2, (self, metadata) => makeDocument(self.pages, { ...self.metadata, ...metadata }));
|
|
23
|
+
const textEncoder = new TextEncoder();
|
|
24
|
+
const escapePdfLiteral = (value) => value
|
|
25
|
+
.replaceAll("\\", "\\\\")
|
|
26
|
+
.replaceAll("(", "\\(")
|
|
27
|
+
.replaceAll(")", "\\)")
|
|
28
|
+
.replaceAll("\r", "\\r")
|
|
29
|
+
.replaceAll("\n", "\\n");
|
|
30
|
+
const formatNumber = (value) => {
|
|
31
|
+
if (Number.isInteger(value)) {
|
|
32
|
+
return String(value);
|
|
33
|
+
}
|
|
34
|
+
return Number(value.toFixed(6)).toString();
|
|
35
|
+
};
|
|
36
|
+
const serializeMetadataEntries = (metadata) => {
|
|
37
|
+
const pairs = [
|
|
38
|
+
["Title", metadata.title],
|
|
39
|
+
["Author", metadata.author],
|
|
40
|
+
["Subject", metadata.subject],
|
|
41
|
+
["Creator", metadata.creator],
|
|
42
|
+
["Producer", metadata.producer],
|
|
43
|
+
];
|
|
44
|
+
const entries = [];
|
|
45
|
+
for (const [key, value] of pairs) {
|
|
46
|
+
if (value !== undefined) {
|
|
47
|
+
entries.push(`/${key} (${escapePdfLiteral(value)})`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return entries;
|
|
51
|
+
};
|
|
52
|
+
const concatBytes = (chunks) => {
|
|
53
|
+
let total = 0;
|
|
54
|
+
for (const chunk of chunks) {
|
|
55
|
+
total += chunk.byteLength;
|
|
56
|
+
}
|
|
57
|
+
const output = new Uint8Array(total);
|
|
58
|
+
let offset = 0;
|
|
59
|
+
for (const chunk of chunks) {
|
|
60
|
+
output.set(chunk, offset);
|
|
61
|
+
offset += chunk.byteLength;
|
|
62
|
+
}
|
|
63
|
+
return output;
|
|
64
|
+
};
|
|
65
|
+
const serializeDocument = (doc) => {
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let cursor = 0;
|
|
68
|
+
const pushBytes = (bytes) => {
|
|
69
|
+
chunks.push(bytes);
|
|
70
|
+
cursor += bytes.byteLength;
|
|
71
|
+
};
|
|
72
|
+
const pushAscii = (text) => {
|
|
73
|
+
pushBytes(textEncoder.encode(text));
|
|
74
|
+
};
|
|
75
|
+
// PDF 1.7 header + binary comment marker (ISO 32000-1 §7.5.2)
|
|
76
|
+
pushBytes(new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37, 0x0a]));
|
|
77
|
+
pushBytes(new Uint8Array([0x25, 0xe2, 0xe3, 0xcf, 0xd3, 0x0a]));
|
|
78
|
+
const metadataEntries = serializeMetadataEntries(doc.metadata);
|
|
79
|
+
const hasInfo = metadataEntries.length > 0;
|
|
80
|
+
const infoObjectNumber = hasInfo ? 3 : undefined;
|
|
81
|
+
const firstPageObjectNumber = hasInfo ? 4 : 3;
|
|
82
|
+
const pageRefs = doc.pages.map((_, idx) => `${firstPageObjectNumber + idx} 0 R`);
|
|
83
|
+
const offsets = [];
|
|
84
|
+
const writeIndirectObject = (objectNumber, body) => {
|
|
85
|
+
offsets[objectNumber] = cursor;
|
|
86
|
+
pushAscii(`${objectNumber} 0 obj\n${body}\nendobj\n`);
|
|
87
|
+
};
|
|
88
|
+
// 1: Catalog
|
|
89
|
+
writeIndirectObject(1, "<< /Type /Catalog /Pages 2 0 R >>");
|
|
90
|
+
// 2: Pages tree
|
|
91
|
+
writeIndirectObject(2, `<< /Type /Pages /Kids [${pageRefs.join(" ")}] /Count ${doc.pages.length} >>`);
|
|
92
|
+
// 3 (optional): Info dictionary
|
|
93
|
+
if (infoObjectNumber !== undefined) {
|
|
94
|
+
writeIndirectObject(infoObjectNumber, `<< ${metadataEntries.join(" ")} >>`);
|
|
95
|
+
}
|
|
96
|
+
// Page objects
|
|
97
|
+
for (let i = 0; i < doc.pages.length; i++) {
|
|
98
|
+
const page = doc.pages[i];
|
|
99
|
+
const objectNumber = firstPageObjectNumber + i;
|
|
100
|
+
const mediaBox = `[0 0 ${formatNumber(page.width)} ${formatNumber(page.height)}]`;
|
|
101
|
+
writeIndirectObject(objectNumber, `<< /Type /Page /Parent 2 0 R /MediaBox ${mediaBox} >>`);
|
|
102
|
+
}
|
|
103
|
+
const totalObjects = firstPageObjectNumber + doc.pages.length;
|
|
104
|
+
const xrefOffset = cursor;
|
|
105
|
+
pushAscii(`xref\n0 ${totalObjects}\n`);
|
|
106
|
+
pushAscii("0000000000 65535 f \n");
|
|
107
|
+
for (let objNum = 1; objNum < totalObjects; objNum++) {
|
|
108
|
+
const objOffset = offsets[objNum] ?? 0;
|
|
109
|
+
pushAscii(`${String(objOffset).padStart(10, "0")} 00000 n \n`);
|
|
110
|
+
}
|
|
111
|
+
const infoRef = infoObjectNumber !== undefined ? ` /Info ${infoObjectNumber} 0 R` : "";
|
|
112
|
+
pushAscii(`trailer\n<< /Size ${totalObjects} /Root 1 0 R${infoRef} >>\nstartxref\n${xrefOffset}\n%%EOF\n`);
|
|
113
|
+
return concatBytes(chunks);
|
|
114
|
+
};
|
|
115
|
+
export const save = Fn.dual((args) => isPdfDocument(args[0]), (self, options) => Effect.suspend(() => {
|
|
116
|
+
const bytes = serializeDocument(self);
|
|
117
|
+
const maxBytes = options?.maxBytes;
|
|
118
|
+
if (maxBytes !== undefined && bytes.byteLength > maxBytes) {
|
|
119
|
+
return Effect.fail(new PdfLimitError({
|
|
120
|
+
message: `Serialized PDF (${bytes.byteLength} bytes) exceeds maxBytes limit (${maxBytes})`,
|
|
121
|
+
limit: "maxBytes",
|
|
122
|
+
actual: bytes.byteLength,
|
|
123
|
+
max: maxBytes,
|
|
124
|
+
}));
|
|
125
|
+
}
|
|
126
|
+
return Effect.succeed(bytes);
|
|
127
|
+
}));
|
package/dist/Object.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export interface PdfNull {
|
|
2
|
+
readonly _tag: "PdfNull";
|
|
3
|
+
}
|
|
4
|
+
export interface PdfBool {
|
|
5
|
+
readonly _tag: "PdfBool";
|
|
6
|
+
readonly value: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface PdfNumber {
|
|
9
|
+
readonly _tag: "PdfNumber";
|
|
10
|
+
readonly value: number;
|
|
11
|
+
}
|
|
12
|
+
export interface PdfName {
|
|
13
|
+
readonly _tag: "PdfName";
|
|
14
|
+
readonly value: string;
|
|
15
|
+
}
|
|
16
|
+
export interface PdfString {
|
|
17
|
+
readonly _tag: "PdfString";
|
|
18
|
+
readonly value: string;
|
|
19
|
+
}
|
|
20
|
+
export interface PdfHexString {
|
|
21
|
+
readonly _tag: "PdfHexString";
|
|
22
|
+
readonly bytes: Uint8Array;
|
|
23
|
+
}
|
|
24
|
+
export interface PdfArray {
|
|
25
|
+
readonly _tag: "PdfArray";
|
|
26
|
+
readonly items: ReadonlyArray<PdfObject>;
|
|
27
|
+
}
|
|
28
|
+
export interface PdfDict {
|
|
29
|
+
readonly _tag: "PdfDict";
|
|
30
|
+
readonly entries: ReadonlyMap<string, PdfObject>;
|
|
31
|
+
}
|
|
32
|
+
export interface PdfStream {
|
|
33
|
+
readonly _tag: "PdfStream";
|
|
34
|
+
readonly dict: PdfDict;
|
|
35
|
+
readonly data: Uint8Array;
|
|
36
|
+
}
|
|
37
|
+
export interface PdfRef {
|
|
38
|
+
readonly _tag: "PdfRef";
|
|
39
|
+
readonly objectNumber: number;
|
|
40
|
+
readonly generation: number;
|
|
41
|
+
}
|
|
42
|
+
export type PdfObject = PdfNull | PdfBool | PdfNumber | PdfName | PdfString | PdfHexString | PdfArray | PdfDict | PdfStream | PdfRef;
|
|
43
|
+
export declare const pdfNull: () => PdfNull;
|
|
44
|
+
export declare const pdfBool: (value: boolean) => PdfBool;
|
|
45
|
+
export declare const pdfNumber: (value: number) => PdfNumber;
|
|
46
|
+
export declare const pdfName: (value: string) => PdfName;
|
|
47
|
+
export declare const pdfString: (value: string) => PdfString;
|
|
48
|
+
export declare const pdfHexString: (bytes: Uint8Array) => PdfHexString;
|
|
49
|
+
export declare const pdfArray: (items?: ReadonlyArray<PdfObject>) => PdfArray;
|
|
50
|
+
export declare const pdfDict: (entries?: Iterable<readonly [string, PdfObject]> | Record<string, PdfObject>) => PdfDict;
|
|
51
|
+
export declare const pdfStream: (dict: PdfDict, data: Uint8Array) => PdfStream;
|
|
52
|
+
export declare const pdfRef: (objectNumber: number, generation?: number) => PdfRef;
|
|
53
|
+
export declare const isPdfObject: (value: unknown) => value is PdfObject;
|
|
54
|
+
export declare const isPdfNull: (value: PdfObject) => value is PdfNull;
|
|
55
|
+
export declare const isPdfBool: (value: PdfObject) => value is PdfBool;
|
|
56
|
+
export declare const isPdfNumber: (value: PdfObject) => value is PdfNumber;
|
|
57
|
+
export declare const isPdfName: (value: PdfObject) => value is PdfName;
|
|
58
|
+
export declare const isPdfString: (value: PdfObject) => value is PdfString;
|
|
59
|
+
export declare const isPdfHexString: (value: PdfObject) => value is PdfHexString;
|
|
60
|
+
export declare const isPdfArray: (value: PdfObject) => value is PdfArray;
|
|
61
|
+
export declare const isPdfDict: (value: PdfObject) => value is PdfDict;
|
|
62
|
+
export declare const isPdfStream: (value: PdfObject) => value is PdfStream;
|
|
63
|
+
export declare const isPdfRef: (value: PdfObject) => value is PdfRef;
|
package/dist/Object.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const PDF_OBJECT_TAGS = new Set([
|
|
2
|
+
"PdfNull",
|
|
3
|
+
"PdfBool",
|
|
4
|
+
"PdfNumber",
|
|
5
|
+
"PdfName",
|
|
6
|
+
"PdfString",
|
|
7
|
+
"PdfHexString",
|
|
8
|
+
"PdfArray",
|
|
9
|
+
"PdfDict",
|
|
10
|
+
"PdfStream",
|
|
11
|
+
"PdfRef",
|
|
12
|
+
]);
|
|
13
|
+
const NULL_SINGLETON = { _tag: "PdfNull" };
|
|
14
|
+
export const pdfNull = () => NULL_SINGLETON;
|
|
15
|
+
export const pdfBool = (value) => ({ _tag: "PdfBool", value });
|
|
16
|
+
export const pdfNumber = (value) => ({ _tag: "PdfNumber", value });
|
|
17
|
+
export const pdfName = (value) => ({
|
|
18
|
+
_tag: "PdfName",
|
|
19
|
+
value: value.startsWith("/") ? value.slice(1) : value,
|
|
20
|
+
});
|
|
21
|
+
export const pdfString = (value) => ({ _tag: "PdfString", value });
|
|
22
|
+
export const pdfHexString = (bytes) => ({
|
|
23
|
+
_tag: "PdfHexString",
|
|
24
|
+
bytes: new Uint8Array(bytes),
|
|
25
|
+
});
|
|
26
|
+
export const pdfArray = (items = []) => ({
|
|
27
|
+
_tag: "PdfArray",
|
|
28
|
+
items: [...items],
|
|
29
|
+
});
|
|
30
|
+
export const pdfDict = (entries = []) => {
|
|
31
|
+
const map = new Map();
|
|
32
|
+
if (Symbol.iterator in entries) {
|
|
33
|
+
for (const [key, val] of entries) {
|
|
34
|
+
map.set(key.startsWith("/") ? key.slice(1) : key, val);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
for (const [key, val] of Object.entries(entries)) {
|
|
39
|
+
map.set(key.startsWith("/") ? key.slice(1) : key, val);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return { _tag: "PdfDict", entries: map };
|
|
43
|
+
};
|
|
44
|
+
export const pdfStream = (dict, data) => ({
|
|
45
|
+
_tag: "PdfStream",
|
|
46
|
+
dict,
|
|
47
|
+
data: new Uint8Array(data),
|
|
48
|
+
});
|
|
49
|
+
export const pdfRef = (objectNumber, generation = 0) => ({
|
|
50
|
+
_tag: "PdfRef",
|
|
51
|
+
objectNumber,
|
|
52
|
+
generation,
|
|
53
|
+
});
|
|
54
|
+
export const isPdfObject = (value) => typeof value === "object" &&
|
|
55
|
+
value !== null &&
|
|
56
|
+
"_tag" in value &&
|
|
57
|
+
typeof value._tag === "string" &&
|
|
58
|
+
PDF_OBJECT_TAGS.has(value._tag);
|
|
59
|
+
export const isPdfNull = (value) => value._tag === "PdfNull";
|
|
60
|
+
export const isPdfBool = (value) => value._tag === "PdfBool";
|
|
61
|
+
export const isPdfNumber = (value) => value._tag === "PdfNumber";
|
|
62
|
+
export const isPdfName = (value) => value._tag === "PdfName";
|
|
63
|
+
export const isPdfString = (value) => value._tag === "PdfString";
|
|
64
|
+
export const isPdfHexString = (value) => value._tag === "PdfHexString";
|
|
65
|
+
export const isPdfArray = (value) => value._tag === "PdfArray";
|
|
66
|
+
export const isPdfDict = (value) => value._tag === "PdfDict";
|
|
67
|
+
export const isPdfStream = (value) => value._tag === "PdfStream";
|
|
68
|
+
export const isPdfRef = (value) => value._tag === "PdfRef";
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
declare const PdfNodeFsError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
3
|
+
readonly _tag: "PdfNodeFsError";
|
|
4
|
+
} & Readonly<A>;
|
|
5
|
+
export declare class PdfNodeFsError extends PdfNodeFsError_base<{
|
|
6
|
+
readonly operation: "read" | "write";
|
|
7
|
+
readonly path: string;
|
|
8
|
+
readonly message: string;
|
|
9
|
+
readonly cause?: unknown;
|
|
10
|
+
}> {
|
|
11
|
+
}
|
|
12
|
+
export declare const readPdfFile: (path: string) => Effect.Effect<Uint8Array, PdfNodeFsError>;
|
|
13
|
+
export declare const writePdfFile: (path: string, bytes: Uint8Array) => Effect.Effect<void, PdfNodeFsError>;
|
|
14
|
+
export {};
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import * as fs from "node:fs/promises";
|
|
2
|
+
import { Data, Effect } from "effect";
|
|
3
|
+
export class PdfNodeFsError extends Data.TaggedError("PdfNodeFsError") {
|
|
4
|
+
}
|
|
5
|
+
export const readPdfFile = (path) => Effect.tryPromise({
|
|
6
|
+
try: async () => {
|
|
7
|
+
const buffer = await fs.readFile(path);
|
|
8
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
9
|
+
},
|
|
10
|
+
catch: (cause) => new PdfNodeFsError({
|
|
11
|
+
operation: "read",
|
|
12
|
+
path,
|
|
13
|
+
message: `Failed to read PDF file at "${path}"`,
|
|
14
|
+
cause,
|
|
15
|
+
}),
|
|
16
|
+
});
|
|
17
|
+
export const writePdfFile = (path, bytes) => Effect.tryPromise({
|
|
18
|
+
try: () => fs.writeFile(path, bytes),
|
|
19
|
+
catch: (cause) => new PdfNodeFsError({
|
|
20
|
+
operation: "write",
|
|
21
|
+
path,
|
|
22
|
+
message: `Failed to write PDF file at "${path}"`,
|
|
23
|
+
cause,
|
|
24
|
+
}),
|
|
25
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,90 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "effect-pdf",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Effect-native PDF parsing, creation, manipulation, and AcroForm engine",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"acroform",
|
|
7
|
+
"document",
|
|
8
|
+
"effect",
|
|
9
|
+
"parser",
|
|
10
|
+
"pdf",
|
|
11
|
+
"pdf-generation",
|
|
12
|
+
"streaming",
|
|
13
|
+
"typescript"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/bjacobso/effect-pdf#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/bjacobso/effect-pdf/issues"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/bjacobso/effect-pdf.git"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"README.md",
|
|
28
|
+
"SPEC.md"
|
|
29
|
+
],
|
|
30
|
+
"type": "module",
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./Diagnostic": {
|
|
38
|
+
"types": "./dist/Diagnostic.d.ts",
|
|
39
|
+
"import": "./dist/Diagnostic.js"
|
|
40
|
+
},
|
|
41
|
+
"./Object": {
|
|
42
|
+
"types": "./dist/Object.d.ts",
|
|
43
|
+
"import": "./dist/Object.js"
|
|
44
|
+
},
|
|
45
|
+
"./Document": {
|
|
46
|
+
"types": "./dist/Document.d.ts",
|
|
47
|
+
"import": "./dist/Document.js"
|
|
48
|
+
},
|
|
49
|
+
"./node": {
|
|
50
|
+
"types": "./dist/node.d.ts",
|
|
51
|
+
"import": "./dist/node.js"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"publishConfig": {
|
|
55
|
+
"access": "public",
|
|
56
|
+
"provenance": true
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsc -p tsconfig.build.json",
|
|
60
|
+
"typecheck": "tsc --noEmit",
|
|
61
|
+
"test": "pnpm build && vitest run",
|
|
62
|
+
"format": "oxfmt --write src test package.json tsconfig.json tsconfig.build.json .oxlintrc.json .oxfmtrc.json .github",
|
|
63
|
+
"format:check": "oxfmt --check src test package.json tsconfig.json tsconfig.build.json .oxlintrc.json .oxfmtrc.json .github",
|
|
64
|
+
"lint": "oxlint --deny-warnings src test",
|
|
65
|
+
"lint:fix": "pnpm lint --fix",
|
|
66
|
+
"check": "pnpm typecheck && pnpm test && pnpm lint && pnpm format:check",
|
|
67
|
+
"prepublishOnly": "pnpm check",
|
|
68
|
+
"changeset": "changeset",
|
|
69
|
+
"version-packages": "changeset version",
|
|
70
|
+
"release": "pnpm build && changeset publish"
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@changesets/cli": "^3.1.0",
|
|
74
|
+
"@types/node": "22.15.30",
|
|
75
|
+
"effect": "3.22.2",
|
|
76
|
+
"esbuild": "0.25.5",
|
|
77
|
+
"oxfmt": "0.73.0",
|
|
78
|
+
"oxlint": "1.88.0",
|
|
79
|
+
"pdf-lib": "^1.17.1",
|
|
80
|
+
"typescript": "5.9.3",
|
|
81
|
+
"vitest": "3.2.4"
|
|
82
|
+
},
|
|
83
|
+
"peerDependencies": {
|
|
84
|
+
"effect": "^3.22.2"
|
|
85
|
+
},
|
|
86
|
+
"engines": {
|
|
87
|
+
"node": ">=22.12.0"
|
|
88
|
+
},
|
|
89
|
+
"packageManager": "pnpm@10.20.0"
|
|
90
|
+
}
|