turbo-html2pdf 0.1.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/Cargo.toml ADDED
@@ -0,0 +1,24 @@
1
+ [package]
2
+ name = "turbo-pdf-napi"
3
+ description = "N-API binding: the turbo-pdf template->PDF pipeline exposed to Node/JS (Phase 10)"
4
+ version.workspace = true
5
+ edition.workspace = true
6
+ license.workspace = true
7
+ repository.workspace = true
8
+ authors.workspace = true
9
+ rust-version.workspace = true
10
+
11
+ # cdylib for the Node native addon; rlib so the binding can be unit-tested and
12
+ # linked from Rust if ever needed. Mirrors the proven turbo-dom napi crate.
13
+ [lib]
14
+ crate-type = ["cdylib", "rlib"]
15
+
16
+ [dependencies]
17
+ turbo-pdf-core = { path = "../turbo-pdf-core" }
18
+ serde_json = { workspace = true }
19
+ # napi-rs front-end (native addon). `napi6` matches turbo-dom's ABI baseline.
20
+ napi = { version = "2", default-features = false, features = ["napi6", "serde-json"] }
21
+ napi-derive = "2"
22
+
23
+ [build-dependencies]
24
+ napi-build = "2"
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 turbo-pdf contributors
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 ADDED
@@ -0,0 +1,95 @@
1
+ # turbo-html2pdf
2
+
3
+ N-API binding that exposes the turbo-pdf template → PDF pipeline to Node/JS. This
4
+ is the "usable in a React project" entry point: compile a template once, render
5
+ it against data to a PDF `Buffer`.
6
+
7
+ ## API
8
+
9
+ ```js
10
+ const { compile, render, TurboPdfError } = require('turbo-html2pdf')
11
+ const fs = require('node:fs')
12
+
13
+ const font = fs.readFileSync('Go-Regular.ttf')
14
+
15
+ // Compile once, render many times. `Program` is a thread-safe native handle.
16
+ const program = compile('<h1>{{ title }}</h1><p>{{ body }}</p>')
17
+
18
+ const { pdf, diagnostics, pageCount } = program.render({
19
+ data: { title: 'Hello', body: 'World' },
20
+ css: '@page { size: A4; margin: 20px } h1 { font-size: 24px }',
21
+ fonts: [font], // raw OpenType/TrueType bytes, one Buffer per face
22
+ meta: { title: 'My Doc', author: 'Me' },
23
+ now: 0, // pin the now() clock for reproducible output
24
+ })
25
+ // pdf: Buffer (starts with %PDF-1.7), diagnostics: lint[], pageCount: number
26
+
27
+ fs.writeFileSync('out.pdf', pdf)
28
+
29
+ // One-shot convenience (compile + render in one call):
30
+ const r = render('<p>{{ x }}</p>', { data: { x: 1 }, fonts: [font] })
31
+ ```
32
+
33
+ ### `compile(templateHtml, opts?) -> Program`
34
+ Parses the template into a reusable `Program`. Throws `TurboPdfError` on a fatal
35
+ template-syntax fault. `opts` is reserved for future compile knobs and currently
36
+ ignored.
37
+
38
+ ### `program.render(opts?) -> { pdf, diagnostics, pageCount }`
39
+ Renders the program against `opts`:
40
+
41
+ | field | type | notes |
42
+ |----------|------------|-------|
43
+ | `data` | any | interpolated into the body (`{{ field }}`, not `{{ data.field }}`) |
44
+ | `css` | string | author CSS; also supplies `@page` geometry (size/margins) |
45
+ | `fonts` | Buffer[] | font programs, registered via `FontFace::from_bytes` |
46
+ | `images` | Buffer[] | accepted but **not yet embedded** (see Deferred) |
47
+ | `meta` | DocMeta | title/author/subject/keywords/creationDate for the PDF info dict |
48
+ | `now` | number | Unix seconds; pins the clock for byte-deterministic output |
49
+
50
+ ### `render(templateHtml, opts?) -> { pdf, diagnostics, pageCount }`
51
+ One-shot convenience that compiles and renders in one call.
52
+
53
+ ### Errors vs. diagnostics
54
+ * **Fatal** compile/render faults are thrown as `TurboPdfError`, carrying
55
+ `.code` (e.g. `"TemplateSyntax"`, `"UndefinedValue"`) and `.span`
56
+ (`{ line, col, byteOffset }`).
57
+ * **Non-fatal** lints (e.g. `"NotdefGlyph"`, `"RegionOverflow"`,
58
+ `"UnsupportedCss"`) are **returned** in `result.diagnostics`, never thrown.
59
+
60
+ ## Building the addon
61
+
62
+ With the napi CLI (preferred, produces a platform `.node` next to `index.js`):
63
+
64
+ ```sh
65
+ npm install # installs @napi-rs/cli
66
+ npm run build # napi build --platform --release
67
+ ```
68
+
69
+ Without the napi CLI (plain cargo + copy step):
70
+
71
+ ```sh
72
+ npm run build:cargo # cargo build -p turbo-pdf-napi --release && copy-addon
73
+ ```
74
+
75
+ `index.js` also falls back to `target/{release,debug}` automatically, so a bare
76
+ `cargo build -p turbo-pdf-napi` is enough for local use.
77
+
78
+ ## Tests
79
+
80
+ ```sh
81
+ npm test # node --test __test__/*.test.mjs
82
+ ```
83
+
84
+ The e2e test compiles a real template + data, renders a PDF, asserts the page
85
+ count and `%PDF` magic, and — when `qpdf` is on `PATH` — asserts `qpdf --check`
86
+ is clean. If the addon is not built the suite **skips** (it never red-bars on a
87
+ missing toolchain).
88
+
89
+ ## Deferred
90
+
91
+ * **`toBytes()` / `fromBytes()` for `Program`** — the core `Program` is not
92
+ serializable today (it holds a live MiniJinja `Environment`). Deferred to
93
+ `phase10b`; omitted from the surface rather than shipped as a throwing stub.
94
+ * **Raster images** — the `images` param is accepted and wired through but is a
95
+ no-op; raster image embedding is Phase 9b.
Binary file
package/build.rs ADDED
@@ -0,0 +1,3 @@
1
+ fn main() {
2
+ napi_build::setup();
3
+ }
package/index.d.ts ADDED
@@ -0,0 +1,97 @@
1
+ /* turbo-pdf N-API binding — TypeScript surface (Phase 10).
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. */
6
+
7
+ /** A source location: 1-based line/column (0 when unknown) and byte offset. */
8
+ export interface Span {
9
+ line: number
10
+ col: number
11
+ byteOffset: number
12
+ }
13
+
14
+ /** A fatal compile/render fault. Thrown by `compile`, `program.render`, and the
15
+ * one-shot `render`. Non-fatal lints are NOT thrown — they come back in
16
+ * `RenderResult.diagnostics`. */
17
+ export class TurboPdfError extends Error {
18
+ name: 'TurboPdfError'
19
+ /** Stable machine-readable code, e.g. `"TemplateSyntax"`, `"UndefinedValue"`. */
20
+ code: string
21
+ /** Source span of the offending construct. */
22
+ span: Span
23
+ }
24
+
25
+ /** A non-fatal diagnostic (lint) collected during render. */
26
+ export interface Diagnostic {
27
+ /** Stable lint code, e.g. `"UnsupportedCss"`, `"RegionOverflow"`. */
28
+ code: string
29
+ message: string
30
+ /** 1-based source line (0 when unknown). */
31
+ line: number
32
+ /** 1-based source column (0 when unknown). */
33
+ col: number
34
+ }
35
+
36
+ /** PDF document-info metadata. Every field is optional. */
37
+ export interface DocMeta {
38
+ title?: string
39
+ author?: string
40
+ subject?: string
41
+ keywords?: string
42
+ /** Creation date as Unix seconds. Omit for the reproducible sentinel date. */
43
+ creationDate?: number
44
+ }
45
+
46
+ /** Options for a single render pass. All fields optional. */
47
+ export interface RenderOptions {
48
+ /** Data object interpolated into the template (`{{ data.* }}`). */
49
+ data?: unknown
50
+ /** Author CSS; also supplies `@page` geometry (size/margins). */
51
+ css?: string
52
+ /** Font programs (raw OpenType/TrueType bytes), one Buffer per face. */
53
+ fonts?: Buffer[]
54
+ /** Raster images. Accepted but not yet embedded (Phase 9b). */
55
+ images?: Buffer[]
56
+ /** PDF document metadata. */
57
+ meta?: DocMeta
58
+ /** Pins the `now()` clock (Unix seconds) for deterministic output. */
59
+ now?: number
60
+ }
61
+
62
+ /** The result of a render. */
63
+ export interface RenderResult {
64
+ /** The rendered PDF 1.7 document. */
65
+ pdf: Buffer
66
+ /** Non-fatal diagnostics (lints) — never thrown. */
67
+ diagnostics: Diagnostic[]
68
+ /** Number of pages. */
69
+ pageCount: number
70
+ }
71
+
72
+ /** A reusable, pre-parsed set of fonts. Build it ONCE — e.g. warm it at server
73
+ * startup — and pass the handle to every `render` call so the font programs are
74
+ * parsed once instead of on every request. Omit to fall back to per-call
75
+ * `RenderOptions.fonts`. */
76
+ export class Fonts {
77
+ /** Parse `fonts` once into a reusable handle. Do this at startup, then reuse. */
78
+ static load(fonts: Buffer[]): Fonts
79
+ }
80
+
81
+ /** A compiled, reusable template program (thread-safe native handle). */
82
+ export interface Program {
83
+ /** Render this program. Pass a prebuilt {@link Fonts} handle to reuse parsed
84
+ * fonts across calls. Throws `TurboPdfError` on a fatal fault. */
85
+ render(opts?: RenderOptions, fonts?: Fonts): RenderResult
86
+ /** Whether the source declared a `<t:running-header>`. */
87
+ hasHeader(): boolean
88
+ /** Whether the source declared a `<t:running-footer>`. */
89
+ hasFooter(): boolean
90
+ }
91
+
92
+ /** Compile a template into a reusable {@link Program}. Throws `TurboPdfError`. */
93
+ export function compile(templateHtml: string, opts?: unknown): Program
94
+
95
+ /** One-shot convenience: compile + render in a single call. Pass a prebuilt
96
+ * {@link Fonts} handle to reuse parsed fonts. */
97
+ export function render(templateHtml: string, opts?: RenderOptions, fonts?: Fonts): RenderResult
package/index.js ADDED
@@ -0,0 +1,129 @@
1
+ /* turbo-pdf N-API binding — JS entry point (Phase 10).
2
+ *
3
+ * Loads the platform-native addon and wraps the native `compile` / `render`
4
+ * surface so that fatal faults surface as a typed `TurboPdfError` (carrying
5
+ * `.code` and `.span`) instead of a bare Error. Non-fatal lints are returned in
6
+ * `result.diagnostics` by the native layer and are passed through untouched.
7
+ */
8
+
9
+ 'use strict'
10
+
11
+ const { existsSync } = require('node:fs')
12
+ const { join } = require('node:path')
13
+
14
+ // --- locate the native addon -------------------------------------------------
15
+ // In a published package, EVERY platform's prebuilt `.node` sits next to this
16
+ // file, each named `turbo-pdf-napi.<platform>.node` (the suffix that
17
+ // `napi build --platform` emits — e.g. `turbo-pdf-napi.darwin-arm64.node`,
18
+ // `turbo-pdf-napi.linux-x64-gnu.node`). We pick the one matching this host, the
19
+ // same way turbo-dom's bundled package does. Local-dev fallbacks: an unsuffixed
20
+ // `turbo-pdf-napi.node` (single-target `napi build`), or the raw cargo cdylib in
21
+ // target/{release,debug} (plain `cargo build -p turbo-pdf-napi`).
22
+ const CANDIDATES = [
23
+ 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
+ ]
28
+
29
+ function isMusl() {
30
+ // glibc builds report a glibc runtime version; musl builds do not.
31
+ if (!process.report || typeof process.report.getReport !== 'function') {
32
+ try {
33
+ const ldd = require('node:child_process').execSync('which ldd').toString().trim()
34
+ return require('node:fs').readFileSync(ldd, 'utf8').includes('musl')
35
+ } catch {
36
+ return true
37
+ }
38
+ }
39
+ const { glibcVersionRuntime } = process.report.getReport().header
40
+ return !glibcVersionRuntime
41
+ }
42
+
43
+ // The platform suffix used by @napi-rs/cli for the bundled `.node` filenames.
44
+ // Mirrors the naming in NAPI-RS's generated loader, for the matrix this repo
45
+ // ships: linux x64 gnu/musl, linux arm64, darwin arm64, win32 x64 msvc.
46
+ 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
53
+ }
54
+ return `${platform}-${arch}`
55
+ }
56
+
57
+ function addonName() {
58
+ // 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'
62
+ }
63
+
64
+ function loadNative() {
65
+ for (const p of CANDIDATES) {
66
+ if (existsSync(p)) return require(p)
67
+ }
68
+ 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
+ )
73
+ }
74
+
75
+ const native = loadNative()
76
+
77
+ // --- typed error -------------------------------------------------------------
78
+ const SENTINEL = 'TURBO_PDF_ERR:'
79
+
80
+ /** A fatal compile/render fault, carrying a machine-readable code and a source
81
+ * span ({line, col, byteOffset}). Thrown by `compile` / `render`. */
82
+ class TurboPdfError extends Error {
83
+ constructor(payload) {
84
+ super(payload.message)
85
+ this.name = 'TurboPdfError'
86
+ this.code = payload.code
87
+ this.span = payload.span
88
+ }
89
+ }
90
+
91
+ /** If `err` is a sentinel-encoded native fault, rethrow it as a TurboPdfError;
92
+ * otherwise rethrow it unchanged. */
93
+ 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
+ try {
100
+ payload = JSON.parse(json)
101
+ } catch {
102
+ throw err
103
+ }
104
+ throw new TurboPdfError(payload)
105
+ }
106
+
107
+ function guard(fn) {
108
+ return (...args) => {
109
+ try {
110
+ return fn(...args)
111
+ } catch (err) {
112
+ rethrow(err)
113
+ }
114
+ }
115
+ }
116
+
117
+ // --- public surface ----------------------------------------------------------
118
+ const compile = guard((templateHtml, opts) => {
119
+ const program = native.compile(templateHtml, opts)
120
+ // 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
+ })
125
+
126
+ const render = guard((templateHtml, opts, fonts) => native.render(templateHtml, opts, fonts))
127
+
128
+ module.exports = { compile, render, Fonts: native.Fonts, TurboPdfError }
129
+ module.exports.default = module.exports
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "turbo-html2pdf",
3
+ "version": "0.1.0",
4
+ "description": "N-API binding for turbo-pdf: compile a template + data to a PDF Buffer from Node/JS (Phase 10).",
5
+ "license": "MIT",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./index.d.ts",
14
+ "import": "./index.js",
15
+ "require": "./index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "index.js",
21
+ "index.d.ts",
22
+ "*.node",
23
+ "assets/fonts/*.ttf",
24
+ "build.rs",
25
+ "Cargo.toml",
26
+ "src/*.rs",
27
+ "LICENSE",
28
+ "README.md"
29
+ ],
30
+ "napi": {
31
+ "name": "turbo-pdf-napi",
32
+ "triples": {
33
+ "defaults": false,
34
+ "additional": [
35
+ "x86_64-unknown-linux-gnu",
36
+ "x86_64-unknown-linux-musl",
37
+ "aarch64-unknown-linux-gnu",
38
+ "aarch64-apple-darwin",
39
+ "x86_64-pc-windows-msvc"
40
+ ]
41
+ }
42
+ },
43
+ "scripts": {
44
+ "build": "napi build --platform --release",
45
+ "build:debug": "napi build --platform",
46
+ "build:cargo": "cargo build -p turbo-pdf-napi --release && node scripts/copy-addon.mjs",
47
+ "test": "node --test __test__/*.test.mjs",
48
+ "test:rust": "cargo test -p turbo-pdf-napi"
49
+ },
50
+ "keywords": ["pdf", "html", "css", "template", "jinja", "napi", "react"],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/miaskiewicz/turbo-html2pdf.git"
54
+ },
55
+ "engines": {
56
+ "node": ">=18"
57
+ },
58
+ "devDependencies": {
59
+ "@napi-rs/cli": "^2.18.4"
60
+ }
61
+ }
package/src/convert.rs ADDED
@@ -0,0 +1,76 @@
1
+ //! Pure conversions between core types and the N-API wire shapes: diagnostics,
2
+ //! lint codes, and the font registry assembled from caller-supplied byte blobs.
3
+
4
+ use napi_derive::napi;
5
+
6
+ use turbo_pdf_core::{Diagnostics, FontFace, FontRegistry, Lint, LintCode};
7
+
8
+ /// A non-fatal diagnostic (lint) returned in the render result, never thrown.
9
+ #[napi(object)]
10
+ pub struct JsDiagnostic {
11
+ /// Stable lint code (e.g. `"UnsupportedCss"`, `"RegionOverflow"`).
12
+ pub code: String,
13
+ /// Human-readable description.
14
+ pub message: String,
15
+ /// 1-based source line (0 when unknown).
16
+ pub line: u32,
17
+ /// 1-based source column (0 when unknown).
18
+ pub col: u32,
19
+ }
20
+
21
+ /// The stable string form of a [`LintCode`] (mirrors the variant name).
22
+ fn lint_code_str(code: LintCode) -> &'static str {
23
+ match code {
24
+ LintCode::UnsupportedCss => "UnsupportedCss",
25
+ LintCode::NonScalarInterpolation => "NonScalarInterpolation",
26
+ LintCode::RawOutput => "RawOutput",
27
+ LintCode::RegionOverflow => "RegionOverflow",
28
+ LintCode::NotdefGlyph => "NotdefGlyph",
29
+ LintCode::FootnoteConvergence => "FootnoteConvergence",
30
+ }
31
+ }
32
+
33
+ /// Convert one core lint into its JS wire shape.
34
+ fn lint_to_js(lint: &Lint) -> JsDiagnostic {
35
+ JsDiagnostic {
36
+ code: lint_code_str(lint.code).to_string(),
37
+ message: lint.message.clone(),
38
+ line: lint.span.line,
39
+ col: lint.span.col,
40
+ }
41
+ }
42
+
43
+ /// Convert the collected diagnostics into the JS array returned to the caller.
44
+ pub fn diagnostics_to_js(diags: &Diagnostics) -> Vec<JsDiagnostic> {
45
+ diags.lints.iter().map(lint_to_js).collect()
46
+ }
47
+
48
+ /// Build a [`FontRegistry`] from caller-supplied font byte blobs. Each blob is
49
+ /// parsed via [`FontFace::from_bytes`]; the family/weight/style are read from the
50
+ /// font program itself by tagging with a synthetic family derived from index, so
51
+ /// author CSS `font-family` still selects via the registry's fallback chain.
52
+ ///
53
+ /// Unparseable blobs are skipped (the registry simply has fewer faces); the
54
+ /// caller sees a `NotdefGlyph` lint downstream if nothing maps a needed glyph.
55
+ pub fn build_registry(fonts: &[Vec<u8>]) -> FontRegistry {
56
+ let mut reg = FontRegistry::new();
57
+ for (i, bytes) in fonts.iter().enumerate() {
58
+ register_one(&mut reg, bytes, i);
59
+ }
60
+ reg
61
+ }
62
+
63
+ /// Parse and register a single font blob, ignoring blobs that fail to parse.
64
+ fn register_one(reg: &mut FontRegistry, bytes: &[u8], index: usize) {
65
+ let family = font_family(bytes, index);
66
+ if let Some(face) = FontFace::from_bytes(bytes.to_vec(), family, 400, false) {
67
+ reg.add(face);
68
+ }
69
+ }
70
+
71
+ /// A stable family tag for a registered font. The face's intrinsic family is not
72
+ /// exposed by the loader, so we tag by registration index; the registry falls
73
+ /// back to the first registered face when no CSS family matches (§ text layout).
74
+ fn font_family(_bytes: &[u8], index: usize) -> String {
75
+ format!("font{index}")
76
+ }
package/src/errors.rs ADDED
@@ -0,0 +1,51 @@
1
+ //! Error marshaling across the N-API boundary.
2
+ //!
3
+ //! Core fatal errors ([`CompileError`]/[`RenderError`]) carry a machine-readable
4
+ //! [`ErrorCode`] and a source [`Span`] (line/col/byte-offset). N-API's own error
5
+ //! type is only a `(Status, String)` pair, so we encode the structured payload as
6
+ //! a JSON object in the error `reason` behind a stable sentinel prefix. The thin
7
+ //! JS wrapper (`index.js`) detects the prefix and rethrows a typed
8
+ //! `TurboPdfError` whose `.code` and `.span` mirror this payload.
9
+
10
+ use turbo_pdf_core::{CompileError, ErrorCode, RenderError, Span};
11
+
12
+ /// Sentinel that marks a `reason` string as a structured turbo-pdf error. The JS
13
+ /// wrapper splits on this to recover the JSON payload.
14
+ pub const SENTINEL: &str = "TURBO_PDF_ERR:";
15
+
16
+ /// The stable string form of an [`ErrorCode`] (mirrors the variant name).
17
+ fn code_str(code: ErrorCode) -> &'static str {
18
+ match code {
19
+ ErrorCode::TemplateSyntax => "TemplateSyntax",
20
+ ErrorCode::UnknownFilter => "UnknownFilter",
21
+ ErrorCode::UndefinedValue => "UndefinedValue",
22
+ ErrorCode::IncludeDepthExceeded => "IncludeDepthExceeded",
23
+ ErrorCode::UnknownElement => "UnknownElement",
24
+ ErrorCode::Render => "Render",
25
+ }
26
+ }
27
+
28
+ /// Build the JSON payload `{code, message, span:{line,col,byteOffset}}`.
29
+ fn payload(code: ErrorCode, message: &str, span: Span) -> serde_json::Value {
30
+ serde_json::json!({
31
+ "code": code_str(code),
32
+ "message": message,
33
+ "span": { "line": span.line, "col": span.col, "byteOffset": span.byte_offset },
34
+ })
35
+ }
36
+
37
+ /// Encode a structured payload into a sentinel-prefixed N-API error.
38
+ fn encode(code: ErrorCode, message: &str, span: Span) -> napi::Error {
39
+ let body = payload(code, message, span).to_string();
40
+ napi::Error::from_reason(format!("{SENTINEL}{body}"))
41
+ }
42
+
43
+ /// Map a fatal compile error to a typed N-API error.
44
+ pub fn from_compile(e: CompileError) -> napi::Error {
45
+ encode(e.code, &e.message, e.span)
46
+ }
47
+
48
+ /// Map a fatal render error to a typed N-API error.
49
+ pub fn from_render(e: RenderError) -> napi::Error {
50
+ encode(e.code, &e.message, e.span)
51
+ }
package/src/lib.rs ADDED
@@ -0,0 +1,232 @@
1
+ //! turbo-pdf N-API binding (Phase 10).
2
+ //!
3
+ //! Exposes the compile -> render -> emit pipeline of `turbo-pdf-core` to Node/JS.
4
+ //! A template is compiled once into a [`Program`] (a `Send + Sync` native handle)
5
+ //! and rendered against data as many times as needed; a one-shot [`render`]
6
+ //! convenience does both in a single call.
7
+ //!
8
+ //! ## Boundary contract
9
+ //! * Input data is an ordinary JS value (object/array/scalar), received as
10
+ //! `serde_json::Value`.
11
+ //! * The rendered PDF crosses back as a `Buffer` built directly from the emitter's
12
+ //! `Vec<u8>` (N-API takes ownership of the allocation — no extra copy).
13
+ //! * Fatal errors are thrown as a typed `TurboPdfError` (see `errors`); non-fatal
14
+ //! lints are *returned* in the result's `diagnostics` array, never thrown.
15
+ //!
16
+ //! The product surface is this thin marshaling layer; all rendering logic lives
17
+ //! in the core crate. This crate is excluded from the coverage gate (a cdylib
18
+ //! addon cannot be line-instrumented), so it is kept deliberately minimal and
19
+ //! mechanical, with every branch pushed down into the covered core.
20
+
21
+ #![deny(clippy::all)]
22
+
23
+ mod convert;
24
+ mod errors;
25
+
26
+ use napi::bindgen_prelude::Buffer;
27
+ use napi_derive::napi;
28
+ use serde_json::Value;
29
+
30
+ use std::sync::Arc;
31
+
32
+ use turbo_pdf_core::style::TokenSet;
33
+ use turbo_pdf_core::{
34
+ build_cascade, compile as core_compile, emit_pdf, render_pages, style::parse_stylesheet,
35
+ CompileOptions, Diagnostics, EmitOptions, FontRegistry, RenderInputs,
36
+ };
37
+
38
+ use convert::{build_registry, diagnostics_to_js, JsDiagnostic};
39
+
40
+ /// Options for a single render pass. All fields are optional; omit what you do
41
+ /// not need. `data` defaults to `null`, `css` to empty, `fonts`/`images` to empty.
42
+ #[napi(object)]
43
+ #[derive(Default)]
44
+ pub struct RenderOptions {
45
+ /// The data object interpolated into the template (`{{ data.* }}`).
46
+ pub data: Option<Value>,
47
+ /// Author CSS. Also feeds `@page` geometry (size/margins) via the parser.
48
+ pub css: Option<String>,
49
+ /// Font programs (raw OpenType/TrueType bytes), one `Buffer` per face.
50
+ pub fonts: Option<Vec<Buffer>>,
51
+ /// Raster images. Accepted but not yet embedded (Phase 9b) — see note below.
52
+ pub images: Option<Vec<Buffer>>,
53
+ /// PDF document metadata written to the info dictionary.
54
+ pub meta: Option<DocMeta>,
55
+ /// Pins the `now()` clock (Unix seconds) for deterministic output.
56
+ pub now: Option<i64>,
57
+ }
58
+
59
+ /// PDF document-info metadata. Every field is optional and omitted when unset.
60
+ #[napi(object)]
61
+ pub struct DocMeta {
62
+ pub title: Option<String>,
63
+ pub author: Option<String>,
64
+ pub subject: Option<String>,
65
+ pub keywords: Option<String>,
66
+ /// Creation date as Unix seconds. Omit for the reproducible sentinel date.
67
+ pub creation_date: Option<i64>,
68
+ }
69
+
70
+ /// The result of a render: the PDF bytes plus the returned (non-fatal) lints and
71
+ /// the page count.
72
+ #[napi(object)]
73
+ pub struct RenderResult {
74
+ /// The rendered PDF 1.7 document.
75
+ pub pdf: Buffer,
76
+ /// Non-fatal diagnostics collected during render (lints), never thrown.
77
+ pub diagnostics: Vec<JsDiagnostic>,
78
+ /// Number of pages in the document.
79
+ pub page_count: u32,
80
+ }
81
+
82
+ /// A reusable, pre-parsed set of fonts. Build it ONCE (e.g. warm it at server
83
+ /// startup) with [`Fonts::load`] and pass the handle to every `render` call:
84
+ /// the registry is shared (cheap `Arc` clone), so font programs are parsed once
85
+ /// instead of on every request. Omit it to fall back to per-call `opts.fonts`.
86
+ #[napi]
87
+ pub struct Fonts {
88
+ inner: Arc<FontRegistry>,
89
+ }
90
+
91
+ #[napi]
92
+ impl Fonts {
93
+ /// Parse `fonts` (raw OpenType/TrueType byte buffers) once into a reusable
94
+ /// handle. Do this at startup, then reuse it across renders.
95
+ #[napi(factory)]
96
+ pub fn load(fonts: Vec<Buffer>) -> Fonts {
97
+ let blobs: Vec<Vec<u8>> = fonts.iter().map(|b| b.to_vec()).collect();
98
+ Fonts {
99
+ inner: Arc::new(build_registry(&blobs)),
100
+ }
101
+ }
102
+ }
103
+
104
+ /// A compiled, reusable template program. Compiling is the expensive parse step;
105
+ /// render it against many data sets. The handle is thread-safe.
106
+ #[napi]
107
+ pub struct Program {
108
+ inner: turbo_pdf_core::Program,
109
+ }
110
+
111
+ #[napi]
112
+ impl Program {
113
+ /// Render this program against `opts` to a PDF. Throws `TurboPdfError` on a
114
+ /// fatal compile/render fault; lints come back in `result.diagnostics`.
115
+ #[napi]
116
+ pub fn render(
117
+ &self,
118
+ opts: Option<RenderOptions>,
119
+ fonts: Option<&Fonts>,
120
+ ) -> napi::Result<RenderResult> {
121
+ run_pipeline(&self.inner, opts.unwrap_or_default(), fonts)
122
+ }
123
+
124
+ /// Whether the source declared a `<t:running-header>`.
125
+ #[napi]
126
+ pub fn has_header(&self) -> bool {
127
+ self.inner.has_header()
128
+ }
129
+
130
+ /// Whether the source declared a `<t:running-footer>`.
131
+ #[napi]
132
+ pub fn has_footer(&self) -> bool {
133
+ self.inner.has_footer()
134
+ }
135
+
136
+ // TODO(phase10b): `to_bytes()` / `from_bytes()`. The core `Program` holds a
137
+ // live MiniJinja `Environment<'static>` and is not serializable today, so a
138
+ // round-trippable handle is deferred rather than shipped as a throwing stub.
139
+ // Compile is cheap enough that callers re-compile from source in the interim.
140
+ }
141
+
142
+ /// Compile `template_html` into a reusable [`Program`]. `_opts` is reserved for
143
+ /// future compile knobs (partials, missing-policy) and currently ignored; the
144
+ /// default [`CompileOptions`] is used.
145
+ #[napi]
146
+ pub fn compile(template_html: String, _opts: Option<Value>) -> napi::Result<Program> {
147
+ let (program, _diags) =
148
+ core_compile(&template_html, &CompileOptions::default()).map_err(errors::from_compile)?;
149
+ Ok(Program { inner: program })
150
+ }
151
+
152
+ /// One-shot convenience: compile `template_html` and render it in a single call.
153
+ #[napi(js_name = "render")]
154
+ pub fn render_oneshot(
155
+ template_html: String,
156
+ opts: Option<RenderOptions>,
157
+ fonts: Option<&Fonts>,
158
+ ) -> napi::Result<RenderResult> {
159
+ let (program, _diags) =
160
+ core_compile(&template_html, &CompileOptions::default()).map_err(errors::from_compile)?;
161
+ run_pipeline(&program, opts.unwrap_or_default(), fonts)
162
+ }
163
+
164
+ /// The shared render pipeline: cascade + geometry + fonts -> `render_pages` ->
165
+ /// `emit_pdf`. Diagnostics flow into the result; only fatal faults throw.
166
+ fn run_pipeline(
167
+ program: &turbo_pdf_core::Program,
168
+ opts: RenderOptions,
169
+ fonts: Option<&Fonts>,
170
+ ) -> napi::Result<RenderResult> {
171
+ let css = opts.css.unwrap_or_default();
172
+ let data = opts.data.unwrap_or(Value::Null);
173
+ let cascade = build_cascade(&css, "", TokenSet::default());
174
+ let at_rules = parse_stylesheet(&css).at_rules;
175
+ // Reuse the prebuilt handle when given; otherwise build a one-off registry
176
+ // from this call's `opts.fonts` (back-compat).
177
+ let owned_registry;
178
+ let registry: &FontRegistry = match fonts {
179
+ Some(handle) => &handle.inner,
180
+ None => {
181
+ owned_registry = build_registry(&font_blobs(&opts.fonts));
182
+ &owned_registry
183
+ }
184
+ };
185
+
186
+ let inputs = RenderInputs {
187
+ program,
188
+ data: &data,
189
+ cascade: &cascade,
190
+ at_rules: &at_rules,
191
+ fonts: registry,
192
+ // Image embedding (§7.4) is not yet surfaced through the Node binding; a
193
+ // future option will supply a resolver here. No images for now.
194
+ images: &turbo_pdf_core::NoImages,
195
+ now: opts.now,
196
+ };
197
+
198
+ let mut diags = Diagnostics::default();
199
+ let pages = render_pages(&inputs, &mut diags).map_err(errors::from_render)?;
200
+ let pdf = emit_pdf(&pages, &emit_options(opts.meta));
201
+
202
+ Ok(RenderResult {
203
+ pdf: pdf.into(),
204
+ diagnostics: diagnostics_to_js(&diags),
205
+ page_count: pages.len() as u32,
206
+ })
207
+ }
208
+
209
+ /// Collect the raw bytes of each supplied font `Buffer`. Images are accepted but
210
+ /// dropped here: raster embedding is Phase 9b (the param is wired through so the
211
+ /// JS API is stable, but has no effect yet).
212
+ fn font_blobs(fonts: &Option<Vec<Buffer>>) -> Vec<Vec<u8>> {
213
+ fonts
214
+ .as_ref()
215
+ .map(|fs| fs.iter().map(|b| b.to_vec()).collect())
216
+ .unwrap_or_default()
217
+ }
218
+
219
+ /// Translate optional [`DocMeta`] into core [`EmitOptions`].
220
+ fn emit_options(meta: Option<DocMeta>) -> EmitOptions {
221
+ match meta {
222
+ None => EmitOptions::default(),
223
+ Some(m) => EmitOptions {
224
+ title: m.title,
225
+ author: m.author,
226
+ subject: m.subject,
227
+ keywords: m.keywords,
228
+ creation_date: m.creation_date,
229
+ ..EmitOptions::default()
230
+ },
231
+ }
232
+ }
Binary file