@projektemacher/vivliostyle-batch-cli 0.1.2 → 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.
@@ -1,6 +1,6 @@
1
1
  The MIT License
2
2
 
3
- Copyright © 2010-2024 three.js authors
3
+ Copyright © 2025-2026 Chrsitian Mahnke
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,26 +1,32 @@
1
- # Vivliostyle CLI Wrapper
1
+ # Vivliostyle Batch CLI
2
2
 
3
- A powerful CLI wrapper for [Vivliostyle](https://vivliostyle.org/) with enhanced static asset handling and HTML parsing capabilities.
3
+ A batch-oriented wrapper around [Vivliostyle](https://vivliostyle.org/) that renders HTML pages to PDF with full control over where their assets come from.
4
+
5
+ It runs the [Vivliostyle viewer](https://www.npmjs.com/package/@vivliostyle/viewer) in Chrome and prints the rendered page to PDF. Nothing is downloaded or installed at render time beyond the browser it finds on the machine.
4
6
 
5
7
  ## Features
6
8
 
7
- - Build PDF, EPUB, and WebPub output from HTML or publication manifests
8
- - Preview documents in the browser with live reloading
9
+ - Build PDF output from an HTML file
10
+ - Preview documents in the browser
11
+ - Render with the real browser engine, so canvas charts, WebGL scenes and cross-origin iframes end up in the PDF
12
+ - Stay sharp past 96dpi: `--pixel-ratio` redraws JS-painted content at higher backing resolution
13
+ - Per-push showcase page (GitHub Pages) with the render fixtures next to their PDFs
9
14
  - Automatic detection and mapping of static assets from HTML (`<link>`, `<script>`, `<img>`, etc.)
10
15
  - Support for custom static asset mappings via `--static`
11
16
  - Map external URLs (CDNs, etc.) to local directories using `--asset-base`
12
17
  - Ignore specific assets with `--ignore-asset`
13
- - Forward extra Vivliostyle options using `--`
18
+ - Forward extra viewer options using `--`
14
19
  - Debug mode with detailed logging
15
20
  - Temporary file management and cleanup
16
21
 
17
22
  ## Installation
18
23
 
19
24
  ```bash
20
- #npm install -g @vivliostyle/cli
21
25
  npm install -g @projektemacher/vivliostyle-batch-cli
22
26
  ```
23
27
 
28
+ Rendering needs a Chrome or Chromium binary. The CLI looks for a browser cached by `puppeteer` (`~/.cache/puppeteer`), then for a system installation; `--executable-browser <path>` overrides the search.
29
+
24
30
  ## Usage
25
31
 
26
32
  ### Build a PDF from an HTML file
@@ -50,42 +56,79 @@ vivliostyle-cli -i index.html -o output.pdf \
50
56
  --asset-base https://cdn.example.com/=/home/user/cdn-cache
51
57
  ```
52
58
 
53
- ### Pass extra Vivliostyle options after `--`
59
+ ### Pass extra viewer options after `--`
54
60
 
55
61
  ```bash
56
- vivliostyle-cli -i index.html -o output.pdf -- --timeout 60000 --debug
62
+ vivliostyle-cli -i index.html -o output.pdf -- --size A4 --viewer-param pixelRatio=2
57
63
  ```
58
64
 
59
65
  ## Options
60
66
 
61
- | Option | Description |
62
- | ---------------------------------- | ---------------------------------------------------------------------------- |
63
- | `-i, --input <input>` | Input HTML or publication manifest file (required) |
64
- | `-o, --output <file>` | Output file path (default: `output.pdf`) |
65
- | `--title <title>` | Document title (overrides source) |
66
- | `--author <author>` | Document author |
67
- | `--language <lang>` | Document language tag (e.g. `en`, `de`, `ja`) (default: `de`) |
68
- | `--static <mapping>` | Map virtual path to local path: `/virtual/path:/local/path` (repeatable) |
69
- | `--no-scripts` | Do not map `<script src>` tags as static assets (recommended for PDF builds) |
70
- | `--asset-base <urlBase=localBase>` | Map URLs starting with `urlBase` to files under `localBase` (repeatable) |
71
- | `--ignore-asset <path>` | Skip specific virtual paths when deriving static mappings (repeatable) |
72
- | `--cwd <dir>` | Working directory for Vivliostyle (default: directory of `--input`) |
73
- | `--format <format>` | Output format: `pdf`, `epub`, or `webpub` (default: `pdf`) |
74
- | `--log-level <level>` | Log level: `silent`, `info`, `verbose`, or `debug` (default: `info`) |
75
- | `--mode <mode>` | Execution mode: `build` or `preview` (default: `build`) |
76
- | `--preview` | Shorthand for `--mode preview` — open result in browser |
77
- | `-d, --debug` | Enable debug mode (sets log level to `debug`) |
67
+ | Option | Description |
68
+ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
69
+ | `-i, --input <input>` | Input HTML or publication manifest file (required) |
70
+ | `-o, --output <file>` | Output file path (default: `output.pdf`) |
71
+ | `--title <title>` | Document title (overrides source) |
72
+ | `--author <author>` | Document author |
73
+ | `--language <lang>` | Document language tag (e.g. `en`, `de`, `ja`) (default: `de`) |
74
+ | `--static <mapping>` | Map virtual path to local path: `/virtual/path:/local/path` (repeatable) |
75
+ | `--no-scripts` | Do not map `<script src>` tags as static assets |
76
+ | `--asset-base <urlBase=localBase>` | Map URLs starting with `urlBase` to files under `localBase` (repeatable) |
77
+ | `--ignore-asset <path>` | Skip specific virtual paths when deriving static mappings (repeatable) |
78
+ | `--allow-remote` | Keep subresource references that would be fetched from the network (default: drop) |
79
+ | `--executable-browser <path>` | Chrome/Chromium binary to render with (default: search puppeteer cache, then system) |
80
+ | `--dump-html <dir>` | Write the rewritten input HTML into `<dir>` and keep it (debugging aid) |
81
+ | `--fetch-missing` | Load references without a local file from the web (implies `--allow-remote`; drops gone remotes after a HEAD probe) |
82
+ | `--wait-for-content [ms]` --------- | Delay pagination until the page finished its own async work (default limit 25000ms) |
83
+ | `--quiet-ms <ms>` ----------------- | Quiet period before the layout gate opens (default 400) --------------------------- |
84
+ | `--pixel-ratio <n>` --------------- | Render at `n` times the output resolution; redraws `__vivResize` pages at `n`× backing pixels |
85
+ | `--timeout <ms>` ------------------ | Give up on a page after `<ms>` (default: 300000) --------------------------------- |
86
+ | `--format <format>` | Output format: `pdf` (default: `pdf`) |
87
+ | `--log-level <level>` | Log level: `silent`, `info`, `verbose`, or `debug` (default: `info`) |
88
+ | `--mode <mode>` | Execution mode: `build` or `preview` (default: `build`) |
89
+ | `--preview` | Shorthand for `--mode preview` — open result in browser |
90
+ | `-d, --debug` | Enable debug mode (sets log level to `debug`) |
78
91
 
79
92
  ## Notes
80
93
 
81
94
  - HTML input (`.html`/`.htm`) is auto-detected by file extension.
82
95
  - For HTML input, `<link href>` and `<script src>` tags are parsed and automatically mapped.
83
- - Options after `--` are forwarded verbatim to Vivliostyle.
96
+ - Everything else the document references (`<img src>`, `<source>`, `<iframe>`, `srcset`, …) is rewritten to the local static server as well, so only files from `--static` / `--asset-base` roots are ever loaded.
97
+ - **Offline by default**: any subresource reference without a local file is removed from the document and reported as `[offline] Dropped remote reference: <url>`. Use `--allow-remote` to keep them and let the browser fetch them. Hyperlinks (`<a href>`) are never touched — a link is not a fetch.
98
+ - Options after `--` are forwarded to the viewer as-is; `--size`, `--style`, `--user-style` and `--viewer-param key=value` are turned into viewer parameters.
84
99
  - `--debug` automatically sets `--log-level` to `debug`.
85
100
  - `--preview` and `--mode preview` are equivalent.
86
- - In **preview mode**, Vivliostyle serves everything via its own Vite server.
87
- - In **build mode**, an Express server is started to serve assets.
101
+ - Both modes run a local HTTP server that serves the rewritten document, the mapped assets and the stock Vivliostyle viewer. The viewer page sits in the document's own directory, so URLs that page scripts build from relative paths resolve the way they do on the live site.
88
102
  - `--asset-base` local directories are also used as fallback roots for CSS-referenced assets (fonts, images, etc.).
103
+ - `--dump-html` keeps the rewritten HTML outside the input directory, which is handy when a page does not render as expected.
104
+ - `--wait-for-content` injects a gate image that the static server holds open until the page has no request in flight and its height stopped changing. Vivliostyle waits for every image of a document before it paginates, so this postpones the layout until charts and canvases are rendered. The tracker also logs `devicePixelRatio` and the canvas sizes, which makes resolution problems visible.
105
+ - Pages that paint asynchronously can set `window.__vivReady = true` when done; the layout gate and the renderer treat it as an immediate “painted” signal instead of guessing from network quietness.
106
+ - Pages with resolution-dependent content (canvas, WebGL) can expose `window.__vivResize = (factor) => void` to redraw at `clientSize × factor` backing pixels. `--pixel-ratio <n>` calls that hook with `n` before printing, so output past 96dpi stays sharp while layout keeps its CSS size. Without the hook a `resize` event is still dispatched so chart libraries can re-layout.
107
+ - `--fetch-missing` HEADs every remote reference without a local file and drops the ones that are definitively gone (404/410), so retired embeds do not stall the build. A reference that resolves to a local file is never probed: the live site may have moved on while the local copy still has what the page needs.
108
+ - Collapsed `<details>` elements are opened for the PDF. Vivliostyle loads the page's scripts itself and only re-dispatches `DOMContentLoaded` on the window, so the print scripts that expand collapsible content never run. The preview is left untouched.
109
+ - Print media is active before the document loads, otherwise JS-driven containers are measured as `0x0` and charts stay empty.
110
+ - Every push to `main` publishes a showcase page (GitHub Pages): a landing page rendering this README next to the synthetic fixtures from `test/render-fixtures/` and the PDFs CI rendered from them — input iframe on the left, output PDF, settle reason and canvas sizes on the right. Build it locally with `npm run site:dev` (sample data) or render first and run `npm run site:collect && npm run site:build`.
111
+
112
+ ### Converting a built website
113
+
114
+ ```bash
115
+ vivliostyle-cli -i docs/post/example/article.html -o pdf/example.pdf \
116
+ --asset-base "https://example.com/=$PWD/docs" \
117
+ --static "/:$PWD/docs" \
118
+ --language en
119
+ ```
120
+
121
+ `--asset-base` maps every absolute URL below `https://example.com/` to the local build output. Use `--dump-html tmp/` to inspect the rewritten document, and `--debug` to see every resolved mapping.
122
+
123
+ For pages whose content JavaScript builds (charts, WebGL viewers, PDF viewers):
124
+
125
+ ```bash
126
+ vivliostyle-cli -i docs/post/example/article.html -o pdf/example.pdf \
127
+ --asset-base "https://example.com/=$PWD/docs" \
128
+ --wait-for-content 12000 --fetch-missing --timeout 150000 --pixel-ratio 2
129
+ ```
130
+
131
+ Cross-origin iframes are printed by the browser as they appear on screen, so maps and video players that render for a visitor render in the PDF as well. A frame that needs interaction (or refuses to load without cookies) shows what a visitor without that state would see.
89
132
 
90
133
  ## Examples
91
134
 
@@ -104,8 +147,8 @@ vivliostyle-cli -i index.html -o output.pdf \
104
147
  vivliostyle-cli -i index.html -o output.pdf \
105
148
  --asset-base https://cdn.example.com/=/home/user/cdn-cache
106
149
 
107
- # Pass extra Vivliostyle options after --
108
- vivliostyle-cli -i index.html -o output.pdf -- --timeout 60000
150
+ # Pass extra viewer options after --
151
+ vivliostyle-cli -i index.html -o output.pdf -- --size A4
109
152
  ```
110
153
 
111
154
  ## License
package/dist/index.d.ts CHANGED
@@ -1,7 +1,23 @@
1
+ /**
2
+ * The static server the renderer serves the document and its assets from.
3
+ *
4
+ * It replaces the Vite based server this package used before: everything is
5
+ * served by us, which is what makes the document's origin (and therefore the
6
+ * base URI of scripts the page runs) ours as well.
7
+ */
8
+
1
9
  type AssetBaseMapping = {
2
10
  urlBase: string;
3
11
  localBase: string;
4
12
  };
13
+ type StaticMap = Record<string, string>;
14
+ type SettleGate = {
15
+ /** Hold the gate response until the page reports that it settled. */
16
+ quietMs: number;
17
+ /** Never hold longer than this. */
18
+ deadlineMs: number;
19
+ };
20
+
5
21
  type CliOptions = {
6
22
  input: string;
7
23
  output: string;
@@ -10,7 +26,6 @@ type CliOptions = {
10
26
  language?: string;
11
27
  static: string[];
12
28
  scripts: boolean;
13
- cwd?: string;
14
29
  format: string;
15
30
  logLevel: string;
16
31
  debug?: boolean;
@@ -18,58 +33,193 @@ type CliOptions = {
18
33
  ignoreAsset: string[];
19
34
  mode: string;
20
35
  preview?: boolean;
36
+ allowRemote?: boolean;
37
+ fetchMissing?: boolean;
38
+ dumpHtml?: string;
39
+ waitForContent?: string | boolean;
40
+ pixelRatio?: string;
41
+ timeout?: string;
42
+ quietMs?: string;
43
+ };
44
+ /**
45
+ * Options shared by the build-mode and preview-mode HTML rewriters.
46
+ */
47
+ type HtmlRewriteOptions = {
48
+ /** Keep references that would be fetched from the network. Off by default. */
49
+ allowRemote?: boolean;
50
+ /** Write the rewritten HTML here (and keep it) instead of a temp file. */
51
+ dumpDir?: string | null;
52
+ /** Let the browser load references without a local file from the web. */
53
+ fetchMissing?: boolean;
54
+ /** Delay pagination until the page's own async work finished. */
55
+ settle?: SettleGate | null;
56
+ /** Origin that page-script requests are routed to. */
57
+ shimOrigin?: string | null;
58
+ /** Base that page-relative URLs resolve against (the page's directory). */
59
+ documentBaseUrl?: string | null;
60
+ /** Remote references that turned out not to exist. */
61
+ unavailableUrls?: Set<string>;
62
+ /** Extra CSS handed to the viewer (`@page` rules, print tweaks). */
63
+ css?: string;
64
+ /** Additional user stylesheet for the viewer. */
65
+ userStyle?: string;
21
66
  };
22
- type Dbg = (_label: string, _value?: unknown) => void;
67
+ /** Directory part of a site path, without a trailing slash (`""` for the root). */
68
+ declare function siteDirectory(sitePath: string): string;
23
69
  /**
24
- * Returns true when the input file should be treated as HTML.
25
- * Vivliostyle also accepts publication manifests (JSON/TOML/JS config files);
26
- * we detect HTML by extension to avoid trying to parse those as markup.
70
+ * Path the document has on the mapped site, e.g. `/post/tag-pairs/article.html`
71
+ * for `<localBase>/post/tag-pairs/article.html`. Used as the URL Vivliostyle
72
+ * loads, so page-relative and root-relative references resolve like they do on
73
+ * the real site.
27
74
  */
75
+ declare function deriveSitePath(inputAbs: string, assetBases: AssetBaseMapping[]): string | null;
76
+ /**
77
+ * Tracker injected into the document. It wraps fetch/XHR, watches the document
78
+ * for late content and reports back once nothing is pending and the height has
79
+ * been stable for `quietMs` — or when the deadline is reached.
80
+ */
81
+ type RuntimeScriptOptions = {
82
+ origin: string;
83
+ documentBaseUrl: string;
84
+ gate: SettleGate | null;
85
+ /**
86
+ * Open every `<details>` element. Vivliostyle loads the page's scripts itself
87
+ * and only re-dispatches `DOMContentLoaded` on the window, so scripts that
88
+ * wait for it on the document — the usual way to expand collapsible content —
89
+ * never run and their content would be missing from the PDF.
90
+ */
91
+ expandDetails?: boolean;
92
+ };
93
+ /**
94
+ * Opens every `<details>` element, now and for any the page adds later.
95
+ *
96
+ * Print output has to contain the collapsed content too, and the page's own
97
+ * print script cannot do it: Vivliostyle re-dispatches `DOMContentLoaded` on
98
+ * the window rather than on the document, so a `document`-level listener never
99
+ * runs.
100
+ */
101
+ declare const EXPAND_DETAILS_SNIPPET = "function expandDetails(root){\n var open=function(el){\n if(el.tagName!==\"DETAILS\"||el.open)return;\n el.open=true;\n el.setAttribute(\"data-viv-details-expanded\",\"\");\n };\n if(root.nodeType!==1)return;\n [].forEach.call(root.querySelectorAll(\"details\"),open);\n open(root);\n}\nexpandDetails(document);\ntry{new MutationObserver(function(records){\n for(var i=0;i<records.length;i++){\n var added=records[i].addedNodes;\n for(var j=0;j<added.length;j++)expandDetails(added[j]);\n }\n}).observe(document.documentElement,{childList:true,subtree:true});}catch(e){}\n";
102
+ /** Gate image Vivliostyle waits for before it paginates. */
103
+ declare function buildSettleGateImage(origin: string): string;
104
+ /**
105
+ * The script injected into the document: it routes the URLs that page scripts
106
+ * create to our server and tracks whether the page has finished.
107
+ *
108
+ * Everything lives in one scope on purpose — the settle tracker wraps the same
109
+ * `fetch`/XHR that the routing patches.
110
+ */
111
+ declare function buildRuntimeScript(options: RuntimeScriptOptions): string;
112
+ /**
113
+ * Injects the runtime script as the first thing in `<head>` (so it wraps `fetch`
114
+ * before any page script runs) and the gate image at the end of `<body>`.
115
+ */
116
+ declare function injectRuntimeScriptInDom(document: Document, options: RuntimeScriptOptions): void;
28
117
  declare function isHtmlInput(inputAbs: string): boolean;
29
118
  declare function splitArgsAtDoubleDash(argv: string[]): {
30
119
  cliArgv: string[];
31
120
  extraArgs: string[];
32
121
  };
33
- type StaticServer = {
34
- baseUrl: string;
35
- close: () => void;
36
- };
37
- declare function startStaticServer(staticMap: Record<string, string>, assetBases: AssetBaseMapping[], htmlFilePath: string | null, dbg: Dbg, port?: number): Promise<StaticServer>;
38
- declare function rewriteAbsoluteUrlsInDom(document: Document, assetBases: AssetBaseMapping[]): boolean;
39
- declare function rewriteVirtualPathsToServerInDom(document: Document, staticMapKeys: string[], serverBaseUrl: string): boolean;
40
- declare function rewriteAbsoluteUrls(htmlContent: string, assetBases: AssetBaseMapping[]): string;
41
- declare function rewriteVirtualPathsToServer(htmlContent: string, staticMap: Record<string, string>, serverBaseUrl: string): string;
42
- declare function extractUrlsFromHtml(htmlPath: string, includeScripts?: boolean, doc?: Document): string[];
43
122
  /**
44
- * Rewrites absolute external URLs to root-relative virtual paths and writes
45
- * the result as a sibling of the original input file so that
46
- * cwd = dirname(inputAbs) remains valid for Vivliostyle's path resolution.
123
+ * Applies `transform` to every URL of every subresource attribute.
124
+ *
125
+ * A `srcset` candidate list is transformed candidate by candidate, keeping the
126
+ * descriptors (`1x`, `480w`). Returning `null` drops the candidate; an attribute
127
+ * without any remaining candidate is removed.
128
+ */
129
+ declare function rewriteUrlAttributes(document: Document, transform: (url: string) => string | null): boolean;
130
+ /**
131
+ * True when the browser would have to fetch the URL over the network.
132
+ */
133
+ declare function isRemoteUrl(value: string): boolean;
134
+ /**
135
+ * Drops subresource references that are not available locally so nothing is
136
+ * fetched from the web. `srcset` candidates are filtered individually; an
137
+ * attribute whose candidates are all remote is removed entirely.
138
+ *
139
+ * `isAllowed` exempts URLs that are served by the wrapper itself, e.g. the
140
+ * static server URLs produced by the virtual-path rewrite.
141
+ *
142
+ * Returns every dropped URL.
143
+ */
144
+ declare function dropRemoteReferencesInDom(document: Document, isAllowed?: (url: string) => boolean): string[];
145
+ /**
146
+ * Extracts the target of `<meta http-equiv="refresh" content="0; url=…">`.
147
+ */
148
+ declare function parseMetaRefreshTarget(content: string): string | null;
149
+ /**
150
+ * Root-relative subresource paths that survive the rewrites and therefore end
151
+ * up resolved against the file system location of the input document. They are
152
+ * broken unless something else provides them (e.g. the input is served over
153
+ * HTTP), so they are worth reporting.
154
+ */
155
+ declare function collectUnservedVirtualPaths(document: Document, staticMapKeys: string[], isServable?: (virtualPath: string) => boolean): string[];
156
+ /** Remote subresource URLs a document would have to fetch. */
157
+ declare function collectRemoteReferences(document: Document): string[];
158
+ /**
159
+ * Whether a remote reference is worth probing on the live site.
47
160
  *
48
- * The output filename uses a non-dotfile prefix so Vite's static server
49
- * (which ignores dotfiles by default) can serve it correctly.
161
+ * A reference that resolves to a local file is served from disk, so only that
162
+ * file decides whether it stays: the live site may have moved on (a new CSS
163
+ * hash, a rotated upload) while our copy of the page still has what it needs.
164
+ */
165
+ declare function referencesToProbe(url: string, assetBases: AssetBaseMapping[]): boolean;
166
+ /**
167
+ * Checks which remote references actually exist, so that content that is gone
168
+ * (a deleted slide deck, a retired CSS file) is dropped instead of leaving a
169
+ * broken embed that never finishes loading.
170
+ */
171
+ declare function probeRemoteReferences(urls: string[], timeoutMs?: number): Promise<Set<string>>;
172
+ /** Removes the attributes that point at the given URLs. */
173
+ declare function dropUnavailableReferencesInDom(document: Document, unavailable: Set<string>): string[];
174
+ /**
175
+ * Exempts the wrapper's own static server from the offline pass: URLs pointing
176
+ * at it are served from the local file system, never from the web.
177
+ */
178
+ declare function isStaticServerUrl(serverBaseUrl: string): (url: string) => boolean;
179
+ /**
180
+ * Discriminated union returned by mapAbsoluteUrlToLocal.
50
181
  *
51
- * Also derives extra static mounts from each assetBase so that secondary
52
- * assets referenced from CSS (fonts, images) are served by Vivliostyle's
53
- * own Vite server without needing Express.
182
+ * - "mapped" — the URL matched an asset-base prefix and has a sub-path that
183
+ * can be mapped to a local file.
184
+ * - "root-only" — the URL matched a prefix but carried no sub-path (i.e. the
185
+ * URL is exactly the base root). The caller should skip it
186
+ * with a precise message rather than treating it as an
187
+ * unrecognised external URL.
188
+ * - "no-match" — no asset-base prefix matched; caller handles as usual.
189
+ */
190
+ type AssetBaseMatch = {
191
+ kind: "mapped";
192
+ virtualPath: string;
193
+ localPath: string;
194
+ } | {
195
+ kind: "root-only";
196
+ } | {
197
+ kind: "no-match";
198
+ };
199
+ declare function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): AssetBaseMatch;
200
+ declare function rewriteAbsoluteUrlsInDom(document: Document, assetBases: AssetBaseMapping[], keepMissing?: boolean): boolean;
201
+ declare function rewriteVirtualPathsToServerInDom(document: Document, staticMapKeys: string[], serverBaseUrl: string, isServable?: (virtualPath: string) => boolean): boolean;
202
+ /**
203
+ * Returns a predicate that reports whether a root-relative path can be served
204
+ * from one of the configured asset-base local roots.
54
205
  *
55
- * Returns:
56
- * - htmlPath – sibling file path, or inputAbs if no rewriting was needed
57
- * - extraStatic – virtual→local entries for assetBase roots to merge into
58
- * the static map passed to Vivliostyle
59
- * - cleanup – deletes the sibling file (no-op if inputAbs was returned)
206
+ * Absolute URLs that were rewritten to root-relative virtual paths (see
207
+ * rewriteAbsoluteUrlsInDom) are not necessarily part of the static map — an
208
+ * `<img src>` is never collected by extractUrlsFromHtml — but the static server
209
+ * resolves any request path against an asset-base localBase, so those paths are
210
+ * servable and must be pointed at the server instead of being resolved against
211
+ * the file system location of the input document.
60
212
  */
61
- declare function buildPreviewHtml(inputAbs: string, assetBases: AssetBaseMapping[], dbg: Dbg): {
213
+ declare function createAssetBasePathProbe(assetBases: AssetBaseMapping[]): (virtualPath: string) => boolean;
214
+ declare function rewriteAbsoluteUrls(htmlContent: string, assetBases: AssetBaseMapping[]): string;
215
+ declare function rewriteVirtualPathsToServer(htmlContent: string, staticMap: Record<string, string>, serverBaseUrl: string): string;
216
+ declare function extractUrlsFromHtml(htmlPath: string, includeScripts?: boolean, doc?: Document): string[];
217
+ declare function buildPreviewHtml(inputAbs: string, assetBases: AssetBaseMapping[], options?: HtmlRewriteOptions): {
62
218
  htmlPath: string;
63
219
  extraStatic: Record<string, string>;
64
220
  cleanup: () => void;
65
221
  };
66
- /**
67
- * Prepares the HTML for BUILD mode.
68
- * Both rewrite passes (absolute → virtual, virtual → absolute server URL)
69
- * are applied in a single DOM parse.
70
- * If nothing changed the original file path is returned with a no-op cleanup.
71
- */
72
- declare function prepareInputHtmlForBuild(inputAbs: string, assetBases: AssetBaseMapping[], staticMap: Record<string, string>, serverBaseUrl: string, dbg: Dbg): {
222
+ declare function prepareInputHtmlForBuild(inputAbs: string, assetBases: AssetBaseMapping[], staticMap: Record<string, string>, serverBaseUrl: string, options?: HtmlRewriteOptions): {
73
223
  vivliostyleInput: string;
74
224
  cleanup: () => void;
75
225
  };
@@ -77,10 +227,6 @@ declare function normalizeUrlBase(urlBase: string): string;
77
227
  declare function normalizeIgnoreAssetPath(pathValue: string): string;
78
228
  declare function shouldIgnoreVirtualPath(virtualPath: string, ignoredAssets: Set<string>): boolean;
79
229
  declare function parseAssetBaseMapping(value: string): AssetBaseMapping;
80
- declare function mapAbsoluteUrlToLocal(url: string, assetBases: AssetBaseMapping[]): {
81
- virtualPath: string;
82
- localPath: string;
83
- } | null;
84
230
  type MappingResult = {
85
231
  kind: "mapped";
86
232
  mapping: string;
@@ -89,17 +235,40 @@ type MappingResult = {
89
235
  url: string;
90
236
  reason: string;
91
237
  };
92
- declare function urlToStaticMapping(url: string, htmlDir: string, assetBases: AssetBaseMapping[], ignoredAssets: Set<string>, dbg: Dbg): MappingResult;
238
+ declare function urlToStaticMapping(url: string, htmlDir: string, assetBases: AssetBaseMapping[], ignoredAssets: Set<string>): MappingResult;
93
239
  declare function parseStaticMapping(mapping: string): {
94
240
  virtual: string;
95
241
  local: string;
96
242
  };
243
+ /**
244
+ * Vivliostyle's config object uses camelCase keys (`viewerParam`, `userStyle`)
245
+ * and typed values, so `--viewer-param` has to arrive as `viewerParam` and
246
+ * `--timeout 60000` as the number 60000.
247
+ */
248
+ declare function normalizeExtraKey(key: string): string;
249
+ declare function coerceExtraValue(value: string): string | number | boolean;
97
250
  declare function parseExtraArgs(extraArgs: string[]): Record<string, unknown>;
98
251
  declare function printHelp(): void;
99
252
  declare function parseArgs(argv: string[]): {
100
253
  options: CliOptions;
101
254
  extraArgs: string[];
102
255
  } | null;
256
+ declare function resolveSettleGate(options: CliOptions): SettleGate | null;
103
257
  declare function execute(options: CliOptions, extraArgs?: string[]): Promise<void>;
258
+ type PreviewTarget = {
259
+ /** URL of the viewer, showing the document. */
260
+ url: string;
261
+ /** URL the viewer loads the document from. */
262
+ documentUrl: string;
263
+ close: () => Promise<void>;
264
+ };
265
+ /**
266
+ * Serves the rewritten document next to the viewer and returns the URL to open.
267
+ *
268
+ * The viewer page lives in the document's own directory, so the preview shows
269
+ * exactly what the PDF render would lay out.
270
+ */
271
+ declare function startPreview(inputAbs: string, assetBases: AssetBaseMapping[], staticMap: StaticMap, htmlOptions: HtmlRewriteOptions, extraConfig: Record<string, unknown>): Promise<PreviewTarget>;
104
272
 
105
- export { buildPreviewHtml, execute, extractUrlsFromHtml, isHtmlInput, mapAbsoluteUrlToLocal, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseStaticMapping, prepareInputHtmlForBuild, printHelp, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, splitArgsAtDoubleDash, startStaticServer, urlToStaticMapping };
273
+ export { EXPAND_DETAILS_SNIPPET, buildPreviewHtml, buildRuntimeScript, buildSettleGateImage, coerceExtraValue, collectRemoteReferences, collectUnservedVirtualPaths, createAssetBasePathProbe, deriveSitePath, dropRemoteReferencesInDom, dropUnavailableReferencesInDom, execute, extractUrlsFromHtml, injectRuntimeScriptInDom, isHtmlInput, isRemoteUrl, isStaticServerUrl, mapAbsoluteUrlToLocal, normalizeExtraKey, normalizeIgnoreAssetPath, normalizeUrlBase, parseArgs, parseAssetBaseMapping, parseExtraArgs, parseMetaRefreshTarget, parseStaticMapping, prepareInputHtmlForBuild, printHelp, probeRemoteReferences, referencesToProbe, resolveSettleGate, rewriteAbsoluteUrls, rewriteAbsoluteUrlsInDom, rewriteUrlAttributes, rewriteVirtualPathsToServer, rewriteVirtualPathsToServerInDom, shouldIgnoreVirtualPath, siteDirectory, splitArgsAtDoubleDash, startPreview, urlToStaticMapping };
274
+ export type { HtmlRewriteOptions, PreviewTarget, RuntimeScriptOptions };