turbo-html2pdf 0.1.4 → 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.
package/README.md CHANGED
@@ -201,7 +201,7 @@ fs.writeFileSync('out.pdf', pdf) // %PDF-1.7
201
201
 
202
202
  ## Status
203
203
 
204
- `v0.1.4`. The core engine is complete and heavily tested (the `turbo-pdf-core`
204
+ `v0.2.0`. The core engine is complete and heavily tested (the `turbo-pdf-core`
205
205
  crate holds 100% line coverage with a cyclomatic-complexity ≤ 5 gate). Bindings:
206
206
  Node (napi) and WebAssembly. See [`docs/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/docs/) for the full guide and
207
207
  [`benches/competitive/`](https://github.com/miaskiewicz/turbo-html2pdf/blob/main/benches/competitive/) for the benchmark harness.
package/index.d.ts CHANGED
@@ -1,59 +1,63 @@
1
1
  /* turbo-pdf N-API binding — TypeScript surface (Phase 10).
2
2
  *
3
- * Hand-maintained to mirror the `#[napi]` exports in `src/lib.rs`. When the repo
4
- * gains a `napi build` step in CI this can be regenerated; the shapes below are
5
- * the contract callers depend on. */
3
+ * Hand-maintained to mirror the `#[napi]` exports in `src/lib.rs`. The shapes
4
+ * below are the contract callers depend on — richer than napi's auto-codegen
5
+ * (`Span`, `TurboPdfError`, `CompileOptions`, `unknown` over `any`).
6
+ *
7
+ * Do NOT let `napi build` overwrite this file. The `build`/`build:debug` scripts
8
+ * redirect codegen to `index.generated.d.ts` (git-ignored) via `--dts`. If you
9
+ * run `napi build` by hand, pass `--dts index.generated.d.ts` too. */
6
10
 
7
11
  /** A source location: 1-based line/column (0 when unknown) and byte offset. */
8
12
  export interface Span {
9
- line: number
10
- col: number
11
- byteOffset: number
13
+ line: number;
14
+ col: number;
15
+ byteOffset: number;
12
16
  }
13
17
 
14
18
  /** A fatal compile/render fault. Thrown by `compile`, `program.render`, and the
15
19
  * one-shot `render`. Non-fatal lints are NOT thrown — they come back in
16
20
  * `RenderResult.diagnostics`. */
17
21
  export class TurboPdfError extends Error {
18
- name: 'TurboPdfError'
22
+ name: "TurboPdfError";
19
23
  /** Stable machine-readable code, e.g. `"TemplateSyntax"`, `"UndefinedValue"`. */
20
- code: string
24
+ code: string;
21
25
  /** Source span of the offending construct. */
22
- span: Span
26
+ span: Span;
23
27
  }
24
28
 
25
29
  /** A non-fatal diagnostic (lint) collected during render. */
26
30
  export interface Diagnostic {
27
31
  /** Stable lint code, e.g. `"UnsupportedCss"`, `"RegionOverflow"`. */
28
- code: string
29
- message: string
32
+ code: string;
33
+ message: string;
30
34
  /** 1-based source line (0 when unknown). */
31
- line: number
35
+ line: number;
32
36
  /** 1-based source column (0 when unknown). */
33
- col: number
37
+ col: number;
34
38
  }
35
39
 
36
40
  /** PDF document-info metadata. Every field is optional. */
37
41
  export interface DocMeta {
38
- title?: string
39
- author?: string
40
- subject?: string
41
- keywords?: string
42
+ title?: string;
43
+ author?: string;
44
+ subject?: string;
45
+ keywords?: string;
42
46
  /** Creation date as Unix seconds. Omit for the reproducible sentinel date. */
43
- creationDate?: number
47
+ creationDate?: number;
44
48
  }
45
49
 
46
50
  /** One font face: the program bytes plus the selection metadata the cascade
47
51
  * matches `font-family` / `font-weight` / italic against. */
48
52
  export interface FontFace {
49
53
  /** The font program bytes (`.ttf`/`.otf`). */
50
- data: Buffer
54
+ data: Buffer;
51
55
  /** The CSS `font-family` name this face answers to. */
52
- family: string
56
+ family: string;
53
57
  /** CSS `font-weight` (100..=900). Defaults to 400 (normal). */
54
- weight?: number
58
+ weight?: number;
55
59
  /** Whether this is the italic/oblique face. Defaults to `false`. */
56
- italic?: boolean
60
+ italic?: boolean;
57
61
  }
58
62
 
59
63
  /** One named raster image: a template name plus its encoded PNG/JPEG bytes.
@@ -61,9 +65,9 @@ export interface FontFace {
61
65
  * bytes as a PDF image XObject. */
62
66
  export interface NamedImage {
63
67
  /** The name the template refers to this image by. */
64
- name: string
68
+ name: string;
65
69
  /** The encoded image bytes (PNG or JPEG). */
66
- data: Buffer
70
+ data: Buffer;
67
71
  }
68
72
 
69
73
  /** A page watermark stamped behind the body on every page. Either a shaped-word
@@ -71,28 +75,28 @@ export interface NamedImage {
71
75
  * `RenderOptions.images`); set `image` for the raster form. */
72
76
  export interface Watermark {
73
77
  /** Word to stamp (text mark). Defaults to `DRAFT`. */
74
- text?: string
78
+ text?: string;
75
79
  /** Fill color `#rrggbb` (text mark). Defaults to gray. */
76
- color?: string
80
+ color?: string;
77
81
  /** Image name (image mark), resolved against `RenderOptions.images`. */
78
- image?: string
82
+ image?: string;
79
83
  /** Fill opacity `0.0..=1.0`. Defaults to 0.25 (text) / 1.0 (image). */
80
- opacity?: number
84
+ opacity?: number;
81
85
  /** Rotation in degrees (text mark). Defaults to 45. */
82
- angle?: number
86
+ angle?: number;
83
87
  /** Tile the image mark across the page instead of centering it. */
84
- tiled?: boolean
88
+ tiled?: boolean;
85
89
  }
86
90
 
87
91
  /** Compile-time knobs: partials, missing-value policy, and include depth. */
88
92
  export interface CompileOptions {
89
93
  /** Partial templates by name, for `{% include %}`. */
90
- partials?: Record<string, string>
94
+ partials?: Record<string, string>;
91
95
  /** `"strict"` (default) throws on a missing value; `"empty"`/`"lenient"`
92
96
  * renders it as empty. */
93
- missingPolicy?: 'strict' | 'empty' | 'lenient'
97
+ missingPolicy?: "strict" | "empty" | "lenient";
94
98
  /** Maximum `{% include %}` nesting depth (defaults to the core default). */
95
- includeMaxDepth?: number
99
+ includeMaxDepth?: number;
96
100
  }
97
101
 
98
102
  /** AES-256 password-encryption settings. `userPassword` is required to open the
@@ -101,70 +105,70 @@ export interface CompileOptions {
101
105
  * open. Encrypted output is intentionally non-deterministic. */
102
106
  export interface Encryption {
103
107
  /** Password required to open the document. */
104
- userPassword: string
108
+ userPassword: string;
105
109
  /** Owner password granting full permissions. Defaults to the user password. */
106
- ownerPassword?: string
110
+ ownerPassword?: string;
107
111
  /** Allow printing. Defaults to `true`. */
108
- print?: boolean
112
+ print?: boolean;
109
113
  /** Allow modifying contents. Defaults to `true`. */
110
- modify?: boolean
114
+ modify?: boolean;
111
115
  /** Allow copying/extracting text and graphics. Defaults to `true`. */
112
- copy?: boolean
116
+ copy?: boolean;
113
117
  /** Allow adding/modifying annotations. Defaults to `true`. */
114
- annotate?: boolean
118
+ annotate?: boolean;
115
119
  /** Allow filling existing form fields. Defaults to `true`. */
116
- fillForms?: boolean
120
+ fillForms?: boolean;
117
121
  /** Allow accessibility text extraction. Defaults to `true`. */
118
- accessibility?: boolean
122
+ accessibility?: boolean;
119
123
  /** Allow document assembly (insert/rotate/delete pages). Defaults to `true`. */
120
- assemble?: boolean
124
+ assemble?: boolean;
121
125
  /** Allow full-resolution printing. Defaults to `true`. */
122
- highQualityPrint?: boolean
126
+ highQualityPrint?: boolean;
123
127
  }
124
128
 
125
129
  /** Options for a single render pass. All fields optional. */
126
130
  export interface RenderOptions {
127
131
  /** Data object interpolated into the template (`{{ data.* }}`). */
128
- data?: unknown
132
+ data?: unknown;
129
133
  /** Author CSS; also supplies `@page` geometry (size/margins). */
130
- css?: string
134
+ css?: string;
131
135
  /** Font faces, each `{ data, family, weight?, italic? }`. */
132
- fonts?: FontFace[]
136
+ fonts?: FontFace[];
133
137
  /** Named raster images embedded by template name. */
134
- images?: NamedImage[]
138
+ images?: NamedImage[];
135
139
  /** PDF document metadata. */
136
- meta?: DocMeta
140
+ meta?: DocMeta;
137
141
  /** A faded watermark stamped behind the body on every page. */
138
- watermark?: Watermark
142
+ watermark?: Watermark;
139
143
  /** Pins the `now()` clock (Unix seconds) for deterministic output. */
140
- now?: number
144
+ now?: number;
141
145
  /** Emit PDF/A-2b archival conformance (sRGB `/OutputIntents`, XMP `pdfaid`,
142
146
  * trailer `/ID`). Defaults to `false`. */
143
- pdfA?: boolean
147
+ pdfA?: boolean;
144
148
  /** Emit tagged / accessible PDF/UA-1 machinery (`/StructTreeRoot`, `/MarkInfo`,
145
149
  * per-face `/ToUnicode`, `/Lang`). Defaults to `false`. */
146
- pdfUa?: boolean
150
+ pdfUa?: boolean;
147
151
  /** Natural-language tag (RFC 3066, e.g. `en-US`) written as the catalog
148
152
  * `/Lang`. Only meaningful with `pdfUa`. */
149
- lang?: string
153
+ lang?: string;
150
154
  /** Emit fills in DeviceCMYK instead of DeviceRGB. Defaults to `false`. */
151
- cmyk?: boolean
155
+ cmyk?: boolean;
152
156
  /** AES-256 password protection. Omit for an unencrypted, byte-deterministic
153
157
  * PDF. */
154
- encryption?: Encryption
158
+ encryption?: Encryption;
155
159
  /** Foreign PDF documents glued (page by page) AFTER the rendered pages, in
156
160
  * order. Each entry is a complete PDF. */
157
- appendPdfs?: Buffer[]
161
+ appendPdfs?: Buffer[];
158
162
  }
159
163
 
160
164
  /** The result of a render. */
161
165
  export interface RenderResult {
162
166
  /** The rendered PDF 1.7 document. */
163
- pdf: Buffer
167
+ pdf: Buffer;
164
168
  /** Non-fatal diagnostics (lints) — never thrown. */
165
- diagnostics: Diagnostic[]
169
+ diagnostics: Diagnostic[];
166
170
  /** Number of pages. */
167
- pageCount: number
171
+ pageCount: number;
168
172
  }
169
173
 
170
174
  /** A reusable, pre-parsed set of fonts. Build it ONCE — e.g. warm it at server
@@ -174,28 +178,28 @@ export interface RenderResult {
174
178
  export class Fonts {
175
179
  /** Parse `fonts` (each `{ data, family, weight?, italic? }`) once into a
176
180
  * reusable handle. Do this at startup, then reuse. */
177
- static load(fonts: FontFace[]): Fonts
181
+ static load(fonts: FontFace[]): Fonts;
178
182
  }
179
183
 
180
184
  /** A compiled, reusable template program (thread-safe native handle). */
181
185
  export interface Program {
182
186
  /** Render this program. Pass a prebuilt {@link Fonts} handle to reuse parsed
183
187
  * fonts across calls. Throws `TurboPdfError` on a fatal fault. */
184
- render(opts?: RenderOptions, fonts?: Fonts): RenderResult
188
+ render(opts?: RenderOptions, fonts?: Fonts): RenderResult;
185
189
  /** Whether the source declared a `<t:running-header>`. */
186
- hasHeader(): boolean
190
+ hasHeader(): boolean;
187
191
  /** Whether the source declared a `<t:running-footer>`. */
188
- hasFooter(): boolean
192
+ hasFooter(): boolean;
189
193
  }
190
194
 
191
195
  /** Compile a template into a reusable {@link Program}. Throws `TurboPdfError`. */
192
- export function compile(templateHtml: string, opts?: CompileOptions): Program
196
+ export function compile(templateHtml: string, opts?: CompileOptions): Program;
193
197
 
194
198
  /** One-shot convenience: compile + render in a single call. Pass a prebuilt
195
199
  * {@link Fonts} handle to reuse parsed fonts. */
196
- export function render(templateHtml: string, opts?: RenderOptions, fonts?: Fonts): RenderResult
200
+ export function render(templateHtml: string, opts?: RenderOptions, fonts?: Fonts): RenderResult;
197
201
 
198
202
  /** Glue one or more foreign PDF documents after `base`, page by page, returning
199
203
  * the merged PDF. Equivalent to `RenderOptions.appendPdfs` but usable on
200
204
  * already-emitted bytes. Throws `TurboPdfError` if any input fails to parse. */
201
- export function appendPdf(base: Buffer, extras: Buffer[]): Buffer
205
+ export function appendPdf(base: Buffer, extras: Buffer[]): Buffer;
package/index.js CHANGED
@@ -4,12 +4,17 @@
4
4
  * surface so that fatal faults surface as a typed `TurboPdfError` (carrying
5
5
  * `.code` and `.span`) instead of a bare Error. Non-fatal lints are returned in
6
6
  * `result.diagnostics` by the native layer and are passed through untouched.
7
+ *
8
+ * Do NOT let `napi build` overwrite this file — its plain loader has no
9
+ * `TurboPdfError` wrapper. The build scripts redirect codegen to
10
+ * `index.generated.js` (git-ignored) via `--js`; pass that flag if running
11
+ * `napi build` by hand.
7
12
  */
8
13
 
9
- 'use strict'
14
+ "use strict";
10
15
 
11
- const { existsSync } = require('node:fs')
12
- const { join } = require('node:path')
16
+ const { existsSync } = require("node:fs");
17
+ const { join } = require("node:path");
13
18
 
14
19
  // --- locate the native addon -------------------------------------------------
15
20
  // In a published package, EVERY platform's prebuilt `.node` sits next to this
@@ -21,112 +26,112 @@ const { join } = require('node:path')
21
26
  // target/{release,debug} (plain `cargo build -p turbo-pdf-napi`).
22
27
  const CANDIDATES = [
23
28
  join(__dirname, `turbo-pdf-napi.${napiPlatform()}.node`),
24
- join(__dirname, 'turbo-pdf-napi.node'),
25
- join(__dirname, '..', '..', 'target', 'release', addonName()),
26
- join(__dirname, '..', '..', 'target', 'debug', addonName()),
27
- ]
29
+ join(__dirname, "turbo-pdf-napi.node"),
30
+ join(__dirname, "..", "..", "target", "release", addonName()),
31
+ join(__dirname, "..", "..", "target", "debug", addonName()),
32
+ ];
28
33
 
29
34
  function isMusl() {
30
35
  // glibc builds report a glibc runtime version; musl builds do not.
31
- if (!process.report || typeof process.report.getReport !== 'function') {
36
+ if (!process.report || typeof process.report.getReport !== "function") {
32
37
  try {
33
- const ldd = require('node:child_process').execSync('which ldd').toString().trim()
34
- return require('node:fs').readFileSync(ldd, 'utf8').includes('musl')
38
+ const ldd = require("node:child_process").execSync("which ldd").toString().trim();
39
+ return require("node:fs").readFileSync(ldd, "utf8").includes("musl");
35
40
  } catch {
36
- return true
41
+ return true;
37
42
  }
38
43
  }
39
- const { glibcVersionRuntime } = process.report.getReport().header
40
- return !glibcVersionRuntime
44
+ const { glibcVersionRuntime } = process.report.getReport().header;
45
+ return !glibcVersionRuntime;
41
46
  }
42
47
 
43
48
  // The platform suffix used by @napi-rs/cli for the bundled `.node` filenames.
44
49
  // Mirrors the naming in NAPI-RS's generated loader, for the matrix this repo
45
50
  // ships: linux x64 gnu/musl, linux arm64, darwin arm64, win32 x64 msvc.
46
51
  function napiPlatform() {
47
- const { platform, arch } = process
48
- if (platform === 'darwin') return `darwin-${arch}` // arm64 -> darwin-arm64
49
- if (platform === 'win32') return `win32-${arch}-msvc` // x64 -> win32-x64-msvc
50
- if (platform === 'linux') {
51
- const abi = isMusl() ? 'musl' : 'gnu'
52
- return `linux-${arch}-${abi}` // x64 -> linux-x64-gnu | linux-x64-musl; arm64 -> linux-arm64-gnu
52
+ const { platform, arch } = process;
53
+ if (platform === "darwin") return `darwin-${arch}`; // arm64 -> darwin-arm64
54
+ if (platform === "win32") return `win32-${arch}-msvc`; // x64 -> win32-x64-msvc
55
+ if (platform === "linux") {
56
+ const abi = isMusl() ? "musl" : "gnu";
57
+ return `linux-${arch}-${abi}`; // x64 -> linux-x64-gnu | linux-x64-musl; arm64 -> linux-arm64-gnu
53
58
  }
54
- return `${platform}-${arch}`
59
+ return `${platform}-${arch}`;
55
60
  }
56
61
 
57
62
  function addonName() {
58
63
  // napi-rs emits a platform cdylib; Node loads it regardless of extension.
59
- if (process.platform === 'darwin') return 'libturbo_pdf_napi.dylib'
60
- if (process.platform === 'win32') return 'turbo_pdf_napi.dll'
61
- return 'libturbo_pdf_napi.so'
64
+ if (process.platform === "darwin") return "libturbo_pdf_napi.dylib";
65
+ if (process.platform === "win32") return "turbo_pdf_napi.dll";
66
+ return "libturbo_pdf_napi.so";
62
67
  }
63
68
 
64
69
  function loadNative() {
65
70
  for (const p of CANDIDATES) {
66
- if (existsSync(p)) return require(p)
71
+ if (existsSync(p)) return require(p);
67
72
  }
68
73
  throw new Error(
69
- 'turbo-pdf-napi: native addon not found. Run `napi build --release` (or ' +
70
- '`cargo build -p turbo-pdf-napi --release`) first. Looked in:\n ' +
71
- CANDIDATES.join('\n '),
72
- )
74
+ "turbo-pdf-napi: native addon not found. Run `napi build --release` (or " +
75
+ "`cargo build -p turbo-pdf-napi --release`) first. Looked in:\n " +
76
+ CANDIDATES.join("\n "),
77
+ );
73
78
  }
74
79
 
75
- const native = loadNative()
80
+ const native = loadNative();
76
81
 
77
82
  // --- typed error -------------------------------------------------------------
78
- const SENTINEL = 'TURBO_PDF_ERR:'
83
+ const SENTINEL = "TURBO_PDF_ERR:";
79
84
 
80
85
  /** A fatal compile/render fault, carrying a machine-readable code and a source
81
86
  * span ({line, col, byteOffset}). Thrown by `compile` / `render`. */
82
87
  class TurboPdfError extends Error {
83
88
  constructor(payload) {
84
- super(payload.message)
85
- this.name = 'TurboPdfError'
86
- this.code = payload.code
87
- this.span = payload.span
89
+ super(payload.message);
90
+ this.name = "TurboPdfError";
91
+ this.code = payload.code;
92
+ this.span = payload.span;
88
93
  }
89
94
  }
90
95
 
91
96
  /** If `err` is a sentinel-encoded native fault, rethrow it as a TurboPdfError;
92
97
  * otherwise rethrow it unchanged. */
93
98
  function rethrow(err) {
94
- const msg = err && typeof err.message === 'string' ? err.message : ''
95
- const at = msg.indexOf(SENTINEL)
96
- if (at === -1) throw err
97
- const json = msg.slice(at + SENTINEL.length)
98
- let payload
99
+ const msg = err && typeof err.message === "string" ? err.message : "";
100
+ const at = msg.indexOf(SENTINEL);
101
+ if (at === -1) throw err;
102
+ const json = msg.slice(at + SENTINEL.length);
103
+ let payload;
99
104
  try {
100
- payload = JSON.parse(json)
105
+ payload = JSON.parse(json);
101
106
  } catch {
102
- throw err
107
+ throw err;
103
108
  }
104
- throw new TurboPdfError(payload)
109
+ throw new TurboPdfError(payload);
105
110
  }
106
111
 
107
112
  function guard(fn) {
108
113
  return (...args) => {
109
114
  try {
110
- return fn(...args)
115
+ return fn(...args);
111
116
  } catch (err) {
112
- rethrow(err)
117
+ rethrow(err);
113
118
  }
114
- }
119
+ };
115
120
  }
116
121
 
117
122
  // --- public surface ----------------------------------------------------------
118
123
  const compile = guard((templateHtml, opts) => {
119
- const program = native.compile(templateHtml, opts)
124
+ const program = native.compile(templateHtml, opts);
120
125
  // Wrap `program.render` so render-time faults are typed too.
121
- const render = program.render.bind(program)
122
- program.render = guard(render)
123
- return program
124
- })
126
+ const render = program.render.bind(program);
127
+ program.render = guard(render);
128
+ return program;
129
+ });
125
130
 
126
- const render = guard((templateHtml, opts, fonts) => native.render(templateHtml, opts, fonts))
131
+ const render = guard((templateHtml, opts, fonts) => native.render(templateHtml, opts, fonts));
127
132
 
128
133
  // Glue foreign PDFs after `base`; parse faults surface as a typed TurboPdfError.
129
- const appendPdf = guard((base, extras) => native.appendPdf(base, extras))
134
+ const appendPdf = guard((base, extras) => native.appendPdf(base, extras));
130
135
 
131
- module.exports = { compile, render, appendPdf, Fonts: native.Fonts, TurboPdfError }
132
- module.exports.default = module.exports
136
+ module.exports = { compile, render, appendPdf, Fonts: native.Fonts, TurboPdfError };
137
+ module.exports.default = module.exports;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "turbo-html2pdf",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Fast native HTML/CSS + Jinja templating to PDF for Node — no headless browser, no Chromium.",
5
5
  "license": "MIT",
6
6
  "main": "index.js",
@@ -41,8 +41,8 @@
41
41
  }
42
42
  },
43
43
  "scripts": {
44
- "build": "napi build --platform --release",
45
- "build:debug": "napi build --platform",
44
+ "build": "napi build --platform --release --dts index.generated.d.ts --js index.generated.js",
45
+ "build:debug": "napi build --platform --dts index.generated.d.ts --js index.generated.js",
46
46
  "build:cargo": "cargo build -p turbo-pdf-napi --release && node scripts/copy-addon.mjs",
47
47
  "test": "node --test __test__/*.test.mjs",
48
48
  "test:rust": "cargo test -p turbo-pdf-napi"
Binary file
Binary file
Binary file
Binary file
Binary file