@open-document/core 0.14.0 → 0.14.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.
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-cNpYUpF6.js";
1
+ import { r as createViteConfig } from "./session-BSbrC5gK.js";
2
2
  import path from "node:path";
3
3
  import { build as build$1, mergeConfig } from "vite";
4
4
  //#region src/cli/build.ts
@@ -1,6 +1,6 @@
1
- import { M as listDocIds } from "./config-cNpYUpF6.js";
2
- import { n as closeRenderSession, t as checkLayout } from "./ops-raK6424A.js";
3
- import { t as cliContext } from "./context-BPApOW9n.js";
1
+ import { R as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-BSbrC5gK.js";
2
+ import "./ops-Dux5HlkH.js";
3
+ import { t as cliContext } from "./context-C-osJW5f.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/check.ts
6
6
  function line(finding) {
package/dist/cli/bin.js CHANGED
@@ -143,39 +143,39 @@ async function run(argv) {
143
143
  program.name("open-doc").description("Author documents — we handle the Vite/React stack, pagination, and export.").version(version, "-v, --version", "print version").helpOption("-h, --help", "show help").showHelpAfterError(chalk.dim("(run `open-doc --help` for usage)"));
144
144
  program.command("dev").description("Start the dev server").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").option("--no-skills-check", "skip the built-in skills drift check").option("--mcp", "serve an MCP endpoint at /mcp (requires @open-document/mcp)").action(async (flags) => {
145
145
  if (flags.skillsCheck !== false) await runSkillsDriftCheck(resolveBuiltinSkillsDir());
146
- const { dev } = await import("../dev-DrnOvsX3.js");
146
+ const { dev } = await import("../dev-CC4PrIOC.js");
147
147
  await dev(flags);
148
148
  });
149
149
  program.command("build").description("Build a static site").option("--out-dir <dir>", "output directory (defaults to `dist`)").action(async (flags) => {
150
- const { build } = await import("../build-CyBlmrjS.js");
150
+ const { build } = await import("../build-I0cgoERP.js");
151
151
  await build(flags);
152
152
  });
153
153
  program.command("preview").description("Preview the production build").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").action(async (flags) => {
154
- const { preview } = await import("../preview-B8Vw9QCh.js");
154
+ const { preview } = await import("../preview-7eqn9Wzf.js");
155
155
  await preview(flags);
156
156
  });
157
157
  program.command("export [docIds...]").description("Render documents headlessly to PDF, HTML, PNG, or DOCX").addOption(new Option("-f, --format <format>", "output format").choices([...EXPORT_FORMATS])).option("-o, --out-dir <dir>", "directory to write into (defaults to `out`)").option("--all", "export every document under docs/").option("--each", "one copy per row of the document's `records`").option("--name <pattern>", "with --each: file name, e.g. \"certificate-{name}\" ({#} is the row number)").action(async (docIds, flags) => {
158
- const { exportDocs } = await import("../export-DeVtL8aX.js");
158
+ const { exportDocs } = await import("../export-KrajVJO7.js");
159
159
  await exportDocs(docIds, flags);
160
160
  });
161
161
  program.command("diff <docId>").description("Show what changed in a document since a git revision, page by page").option("-s, --since <rev>", "revision to compare against (defaults to HEAD)").option("-o, --out-dir <dir>", "directory to write the report into (defaults to `out`)").option("--json", "print the result as JSON").action(async (docId, flags) => {
162
- const { diffDoc } = await import("../diff-BPMD2Knh.js");
162
+ const { diffDoc } = await import("../diff-DhutD4TJ.js");
163
163
  await diffDoc(docId, flags);
164
164
  });
165
165
  program.command("check [docIds...]").description("Report layout faults — clipped content, blank sheets, stranded headings").option("--json", "print the full report as JSON").action(async (docIds, flags) => {
166
- const { checkDocs } = await import("../check-DUKDEem-.js");
166
+ const { checkDocs } = await import("../check-Dys96QSL.js");
167
167
  await checkDocs(docIds, flags);
168
168
  });
169
169
  program.command("templates").description("List the templates a new document can start from").option("--json", "print them as JSON").action(async (flags) => {
170
- const { printTemplates } = await import("../templates-D9jAFJ8R.js");
170
+ const { printTemplates } = await import("../templates-s-VLTSRc.js");
171
171
  await printTemplates(flags);
172
172
  });
173
173
  program.command("new [docId]").description("Create a document under docs/ from a template (see `open-doc templates`)").option("-t, --template <name>", "template to start from (defaults to blank)").option("--title <title>", "title of the new document").action(async (docId, flags) => {
174
- const { newDoc } = await import("../templates-D9jAFJ8R.js");
174
+ const { newDoc } = await import("../templates-s-VLTSRc.js");
175
175
  await newDoc(docId, flags);
176
176
  });
177
177
  program.command("import <file>").description("Turn a Markdown file into a document under docs/").option("--id <id>", "document id (defaults to a slug of the title)").option("--title <title>", "override the title").option("--subtitle <subtitle>", "subtitle, also used as the cover eyebrow").option("--lang <tag>", "language of the text, e.g. zh-Hant-TW (detected for CJK when omitted)").option("--author <author>", "author line on the cover").option("--theme <theme>", "theme id to back-link from meta.theme").addOption(new Option("--page-size <size>", "page size").choices(PAGE_SIZE_NAMES)).addOption(new Option("--orientation <orientation>", "page orientation").choices(ORIENTATIONS)).option("--no-cover", "skip the title page").option("--contents", "add a self-filling contents page").action(async (file, flags) => {
178
- const { importDoc } = await import("../import-WAgWsuOv.js");
178
+ const { importDoc } = await import("../import-Yv34za3L.js");
179
179
  await importDoc(file, flags);
180
180
  });
181
181
  program.command("sync:skills").description("Sync built-in skills from @open-document/core into this workspace").option("--dry-run", "show what would change without writing").action(async (flags) => {
@@ -1,6 +1,6 @@
1
1
  import { n as readCoreVersion } from "./package-version-C89gtYSk.js";
2
2
  import { n as loadUserConfig } from "./open-doc-plugin-DnX5usgI.js";
3
- import { R as makeContext } from "./config-cNpYUpF6.js";
3
+ import { W as makeContext } from "./session-BSbrC5gK.js";
4
4
  //#region src/cli/context.ts
5
5
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
6
6
  async function cliContext(userCwd = process.cwd()) {
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-cNpYUpF6.js";
1
+ import { r as createViteConfig } from "./session-BSbrC5gK.js";
2
2
  import { createServer, mergeConfig } from "vite";
3
3
  //#region src/cli/dev.ts
4
4
  async function dev(opts = {}) {
@@ -1,5 +1,5 @@
1
- import { a as diffDocument } from "./ops-raK6424A.js";
2
- import { t as cliContext } from "./context-BPApOW9n.js";
1
+ import { t as diffDocument } from "./ops-Dux5HlkH.js";
2
+ import { t as cliContext } from "./context-C-osJW5f.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/cli/diff.ts
5
5
  const MARK = {
@@ -1,7 +1,7 @@
1
1
  import { r as EXPORT_FORMATS } from "./sdk-CqNZzbkz.js";
2
- import { M as listDocIds } from "./config-cNpYUpF6.js";
3
- import { n as closeRenderSession, r as exportDocument } from "./ops-raK6424A.js";
4
- import { t as cliContext } from "./context-BPApOW9n.js";
2
+ import { C as exportDocument, R as listDocIds, S as closeRenderSession } from "./session-BSbrC5gK.js";
3
+ import "./ops-Dux5HlkH.js";
4
+ import { t as cliContext } from "./context-C-osJW5f.js";
5
5
  import chalk from "chalk";
6
6
  //#region src/cli/export.ts
7
7
  const FORMATS = EXPORT_FORMATS;
@@ -1,6 +1,6 @@
1
- import { y as importMarkdown } from "./config-cNpYUpF6.js";
2
- import "./ops-raK6424A.js";
3
- import { t as cliContext } from "./context-BPApOW9n.js";
1
+ import { T as importMarkdown } from "./session-BSbrC5gK.js";
2
+ import "./ops-Dux5HlkH.js";
3
+ import { t as cliContext } from "./context-C-osJW5f.js";
4
4
  import chalk from "chalk";
5
5
  import path from "node:path";
6
6
  //#region src/cli/import.ts
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as ORIENTATIONS, o as PAGE_SIZE_NAMES, r as EXPORT_FORMATS } from "../sdk-CqNZzbkz.js";
2
- import { A as docDir, C as revertChange, D as OpsError, E as withFileLock, F as renameDocument, I as resolveEntry, L as writeDocument, M as listDocIds, N as listDocuments, O as createDocument, P as readDocument, R as makeContext, S as readChanges, T as hashSource, _ as readTheme, a as writeText, b as slugify, c as listTemplates, d as deleteAsset, f as fileDocument, g as listThemes, h as listFolders, i as writeEdits, j as duplicateDocument, k as deleteDocument, l as suggestDocId, m as listAssets, n as addComment, o as writeTexts, p as findAssetUsages, r as readText, s as createFromTemplate, u as createFolder, v as writeAsset, w as assertExpectedSource, x as listRevisions, y as importMarkdown } from "../config-cNpYUpF6.js";
3
- import { a as diffDocument, i as renderDocPage, n as closeRenderSession, r as exportDocument, t as checkLayout } from "../ops-raK6424A.js";
2
+ import { A as assertExpectedSource, B as readDocument, C as exportDocument, D as listRevisions, E as slugify, F as deleteDocument, H as resolveEntry, I as docDir, L as duplicateDocument, M as withFileLock, N as OpsError, O as readChanges, P as createDocument, R as listDocIds, S as closeRenderSession, T as importMarkdown, U as writeDocument, V as renameDocument, W as makeContext, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as hashSource, k as revertChange, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as renderDocPage, x as checkLayout, y as readTheme, z as listDocuments } from "../session-BSbrC5gK.js";
3
+ import { t as diffDocument } from "../ops-Dux5HlkH.js";
4
4
  export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, readChanges, readDocument, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, slugify, suggestDocId, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
@@ -1,261 +1,9 @@
1
- import { D as OpsError, I as resolveEntry, t as createViteConfig } from "./config-cNpYUpF6.js";
1
+ import { H as resolveEntry, N as OpsError, n as createRenderSession, t as RenderUnavailableError } from "./session-BSbrC5gK.js";
2
2
  import path from "node:path";
3
3
  import fs from "node:fs/promises";
4
- import { createServer, mergeConfig } from "vite";
5
4
  import { execFile } from "node:child_process";
6
5
  import { promisify } from "node:util";
7
6
  import { Buffer } from "node:buffer";
8
- //#region src/render/session.ts
9
- var RenderUnavailableError = class extends Error {
10
- constructor(message) {
11
- super(message);
12
- this.name = "RenderUnavailableError";
13
- }
14
- };
15
- const INSTALL_HINT = "Headless rendering needs Playwright. Install it in this workspace:\n pnpm add -D playwright && pnpm exec playwright install chromium";
16
- async function loadPlaywright() {
17
- try {
18
- return await import("playwright");
19
- } catch {
20
- throw new RenderUnavailableError(INSTALL_HINT);
21
- }
22
- }
23
- const DEFAULT_TIMEOUT = 6e4;
24
- const PRINT_PAGE_SELECTOR = "#od-print-root .od-print-page";
25
- async function bootServer(userCwd) {
26
- const base = await createViteConfig({
27
- userCwd,
28
- headless: true
29
- });
30
- const config = mergeConfig(base, {
31
- logLevel: "silent",
32
- server: {
33
- port: 0,
34
- strictPort: false,
35
- open: false
36
- }
37
- });
38
- const server = await createServer(config);
39
- await server.listen();
40
- const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
41
- if (!origin) {
42
- await server.close();
43
- throw new Error("Could not determine the dev server URL");
44
- }
45
- return {
46
- server,
47
- origin
48
- };
49
- }
50
- async function createRenderSession(opts) {
51
- const { chromium } = await loadPlaywright();
52
- const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT;
53
- let server = null;
54
- let origin = opts.origin?.replace(/\/$/, "") ?? "";
55
- if (!origin) {
56
- const booted = await bootServer(opts.userCwd);
57
- server = booted.server;
58
- origin = booted.origin;
59
- }
60
- let browser;
61
- try {
62
- browser = await chromium.launch({ headless: true });
63
- } catch (err) {
64
- await server?.close();
65
- throw new RenderUnavailableError(`${INSTALL_HINT}\n\nChromium failed to launch: ${err.message}`);
66
- }
67
- return {
68
- origin,
69
- async open(docId) {
70
- const page = await browser.newPage({
71
- viewport: {
72
- width: 1280,
73
- height: 1024
74
- },
75
- ...opts.deviceScaleFactor !== void 0 ? { deviceScaleFactor: opts.deviceScaleFactor } : {}
76
- });
77
- const errors = [];
78
- page.on("pageerror", (err) => errors.push(String(err?.message ?? err)));
79
- await page.goto(`${origin}/d/${encodeURIComponent(docId)}`, {
80
- waitUntil: "load",
81
- timeout
82
- });
83
- try {
84
- await page.waitForFunction("globalThis.__openDoc ? globalThis.__openDoc.status().ready : false", void 0, { timeout });
85
- } catch {
86
- await page.close();
87
- const detail = errors.length ? `\n${errors.join("\n")}` : "";
88
- throw new Error(`Document "${docId}" never finished rendering.${detail}`);
89
- }
90
- const status = await page.evaluate("globalThis.__openDoc.status()");
91
- const renderer = {
92
- status,
93
- diagnose: () => page.evaluate("globalThis.__openDoc.diagnose()"),
94
- async pdf() {
95
- await page.evaluate("globalThis.__openDoc.preparePrint()");
96
- try {
97
- return await page.pdf({
98
- printBackground: true,
99
- preferCSSPageSize: true,
100
- outline: true,
101
- tagged: true
102
- });
103
- } finally {
104
- await page.evaluate("globalThis.__openDoc.releasePrint()");
105
- }
106
- },
107
- async screenshot(pageNumber) {
108
- if (pageNumber < 1 || pageNumber > status.pageCount) throw new Error(`page ${pageNumber} is out of range — "${docId}" has ${status.pageCount}`);
109
- await page.evaluate("globalThis.__openDoc.preparePrint()");
110
- await page.emulateMedia({ media: "print" });
111
- try {
112
- const sheet = await page.$(`${PRINT_PAGE_SELECTOR}:nth-child(${pageNumber})`);
113
- if (!sheet) throw new Error(`page ${pageNumber} did not render`);
114
- return await sheet.screenshot({ type: "png" });
115
- } finally {
116
- await page.emulateMedia({ media: null });
117
- await page.evaluate("globalThis.__openDoc.releasePrint()");
118
- }
119
- },
120
- async sheets() {
121
- await page.evaluate("globalThis.__openDoc.preparePrint()");
122
- await page.emulateMedia({ media: "print" });
123
- try {
124
- const out = [];
125
- for (let n = 1; n <= status.pageCount; n++) {
126
- const selector = `${PRINT_PAGE_SELECTOR}:nth-child(${n})`;
127
- const sheet = await page.$(selector);
128
- if (!sheet) throw new Error(`page ${n} did not render`);
129
- const png = await sheet.screenshot({ type: "png" });
130
- const text = await page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
131
- out.push({
132
- png,
133
- text
134
- });
135
- }
136
- return out;
137
- } finally {
138
- await page.emulateMedia({ media: null });
139
- await page.evaluate("globalThis.__openDoc.releasePrint()");
140
- }
141
- },
142
- html: () => page.evaluate("globalThis.__openDoc.htmlBundle()"),
143
- docx: () => page.evaluate("globalThis.__openDoc.docxBundle()"),
144
- async setRecord(index, pattern) {
145
- const { name } = await page.evaluate(`globalThis.__openDoc.setRecord(${JSON.stringify(index)}, ${pattern === void 0 ? "undefined" : JSON.stringify(pattern)})`);
146
- await page.waitForFunction(`(() => { const s = globalThis.__openDoc.status(); return s.ready && s.record === ${JSON.stringify(index)}; })()`, void 0, { timeout });
147
- renderer.status = await page.evaluate("globalThis.__openDoc.status()");
148
- return name;
149
- },
150
- close: () => page.close()
151
- };
152
- return renderer;
153
- },
154
- async compareImages(before, after) {
155
- const page = await browser.newPage();
156
- try {
157
- const toUrl = (png) => `data:image/png;base64,${Buffer.from(png).toString("base64")}`;
158
- return await page.evaluate(compareInBrowser, {
159
- a: toUrl(before),
160
- b: toUrl(after),
161
- cell: DIFF_CELL
162
- });
163
- } finally {
164
- await page.close();
165
- }
166
- },
167
- async close() {
168
- await browser.close();
169
- await server?.close();
170
- }
171
- };
172
- }
173
- /** Changed pixels are gathered into cells this many px square before boxing. */
174
- const DIFF_CELL = 12;
175
- /**
176
- * Runs in the page. The browser decodes both PNGs, so nothing on the Node side
177
- * has to: draw each onto white, mark every cell where a pixel moved by more
178
- * than antialiasing does, and box the clusters of marked cells. Clusters
179
- * within two cells of each other join, so one edited paragraph is one box.
180
- */
181
- async function compareInBrowser({ a, b, cell }) {
182
- const load = async (src) => {
183
- const image = new Image();
184
- image.src = src;
185
- await image.decode();
186
- return image;
187
- };
188
- const [x, y] = await Promise.all([load(a), load(b)]);
189
- const width = Math.max(x.naturalWidth, y.naturalWidth);
190
- const height = Math.max(x.naturalHeight, y.naturalHeight);
191
- const pixels = (image) => {
192
- const canvas = document.createElement("canvas");
193
- canvas.width = width;
194
- canvas.height = height;
195
- const g = canvas.getContext("2d");
196
- if (!g) throw new Error("no 2D canvas");
197
- g.fillStyle = "#ffffff";
198
- g.fillRect(0, 0, width, height);
199
- g.drawImage(image, 0, 0);
200
- return g.getImageData(0, 0, width, height).data;
201
- };
202
- const p = pixels(x);
203
- const q = pixels(y);
204
- const cols = Math.ceil(width / cell);
205
- const rows = Math.ceil(height / cell);
206
- const hot = new Uint8Array(cols * rows);
207
- let changed = 0;
208
- for (let i = 0; i < p.length; i += 4) {
209
- if (Math.abs((p[i] ?? 0) - (q[i] ?? 0)) + Math.abs((p[i + 1] ?? 0) - (q[i + 1] ?? 0)) + Math.abs((p[i + 2] ?? 0) - (q[i + 2] ?? 0)) <= 48) continue;
210
- changed++;
211
- const px = i / 4 % width;
212
- const py = Math.floor(i / 4 / width);
213
- hot[Math.floor(py / cell) * cols + Math.floor(px / cell)] = 1;
214
- }
215
- const seen = new Uint8Array(cols * rows);
216
- const boxes = [];
217
- for (let start = 0; start < hot.length; start++) {
218
- if (!hot[start] || seen[start]) continue;
219
- let minC = cols;
220
- let maxC = 0;
221
- let minR = rows;
222
- let maxR = 0;
223
- const stack = [start];
224
- seen[start] = 1;
225
- while (stack.length > 0) {
226
- const at = stack.pop();
227
- const c = at % cols;
228
- const r = Math.floor(at / cols);
229
- minC = Math.min(minC, c);
230
- maxC = Math.max(maxC, c);
231
- minR = Math.min(minR, r);
232
- maxR = Math.max(maxR, r);
233
- for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) {
234
- const nr = r + dr;
235
- const nc = c + dc;
236
- if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
237
- const next = nr * cols + nc;
238
- if (hot[next] && !seen[next]) {
239
- seen[next] = 1;
240
- stack.push(next);
241
- }
242
- }
243
- }
244
- boxes.push({
245
- x: minC * cell,
246
- y: minR * cell,
247
- width: Math.min(width, (maxC + 1) * cell) - minC * cell,
248
- height: Math.min(height, (maxR + 1) * cell) - minR * cell
249
- });
250
- }
251
- return {
252
- width,
253
- height,
254
- changed: changed / (width * height),
255
- boxes
256
- };
257
- }
258
- //#endregion
259
7
  //#region src/ops/diff-pages.ts
260
8
  /** Longest common subsequence over two lists, as pairs of matching indices. */
261
9
  function lcs(a, b, same) {
@@ -650,172 +398,4 @@ async function diffDocument(ctx, docId, opts = {}) {
650
398
  }
651
399
  }
652
400
  //#endregion
653
- //#region src/ops/layout.ts
654
- /**
655
- * Chromium and a Vite server are expensive to start, and an agent checking its
656
- * work calls these back to back. One session is kept warm and closed once
657
- * nobody has asked for a while.
658
- */
659
- const IDLE_MS = 12e4;
660
- let shared = null;
661
- let pending = null;
662
- let idleTimer = null;
663
- let leases = 0;
664
- function armIdleClose() {
665
- if (idleTimer) clearTimeout(idleTimer);
666
- idleTimer = setTimeout(() => {
667
- if (leases > 0) return;
668
- const current = shared;
669
- shared = null;
670
- idleTimer = null;
671
- current?.session.close().catch(() => {});
672
- }, IDLE_MS);
673
- idleTimer.unref?.();
674
- }
675
- async function acquire(ctx) {
676
- if (shared && shared.origin === ctx.serverOrigin) return shared.session;
677
- if (!pending) {
678
- const origin = ctx.serverOrigin;
679
- pending = createRenderSession({
680
- userCwd: ctx.userCwd,
681
- origin,
682
- deviceScaleFactor: 2
683
- }).then((session) => {
684
- shared = {
685
- session,
686
- origin
687
- };
688
- return session;
689
- }).finally(() => {
690
- pending = null;
691
- });
692
- }
693
- return pending;
694
- }
695
- async function withDoc(ctx, docId, fn) {
696
- if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
697
- let session;
698
- try {
699
- session = await acquire(ctx);
700
- } catch (err) {
701
- if (err instanceof RenderUnavailableError) throw new OpsError(501, err.message);
702
- throw new OpsError(500, err.message);
703
- }
704
- leases++;
705
- let renderer = null;
706
- try {
707
- renderer = await session.open(docId);
708
- return await fn(renderer);
709
- } catch (err) {
710
- if (err instanceof OpsError) throw err;
711
- throw new OpsError(422, err.message);
712
- } finally {
713
- await renderer?.close().catch(() => {});
714
- leases--;
715
- armIdleClose();
716
- }
717
- }
718
- /** Closes the warm browser. Call before the process exits so nothing lingers. */
719
- async function closeRenderSession() {
720
- if (idleTimer) clearTimeout(idleTimer);
721
- idleTimer = null;
722
- const current = shared;
723
- shared = null;
724
- await current?.session.close().catch(() => {});
725
- }
726
- /**
727
- * Renders the document headlessly at true page size and reports what is wrong
728
- * with the layout — the part of a document an agent writing React cannot see.
729
- */
730
- async function checkLayout(ctx, docId) {
731
- return withDoc(ctx, docId, async (renderer) => {
732
- const report = await renderer.diagnose();
733
- return {
734
- docId: report.docId || docId,
735
- title: report.title,
736
- pageCount: report.pageCount,
737
- errors: report.findings.filter((f) => f.severity === "error").length,
738
- warnings: report.findings.filter((f) => f.severity === "warn").length,
739
- findings: report.findings
740
- };
741
- });
742
- }
743
- async function renderDocPage(ctx, docId, page) {
744
- return withDoc(ctx, docId, async (renderer) => {
745
- const bytes = await renderer.screenshot(page);
746
- return {
747
- docId,
748
- page,
749
- pageCount: renderer.status.pageCount,
750
- mimeType: "image/png",
751
- base64: Buffer.from(bytes).toString("base64")
752
- };
753
- });
754
- }
755
- function resolveOutDir(ctx, outDir) {
756
- const resolved = path.resolve(ctx.userCwd, outDir);
757
- if (resolved !== ctx.userCwd && !resolved.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${outDir}`);
758
- return resolved;
759
- }
760
- /**
761
- * Writes the document's files. With `each`, a document that exports
762
- * `records` is laid out and written once per row — `name` (or
763
- * `meta.recordName`) names each row's files.
764
- */
765
- async function exportDocument(ctx, docId, opts = {}) {
766
- const format = opts.format ?? "pdf";
767
- const dir = resolveOutDir(ctx, opts.outDir ?? "out");
768
- return withDoc(ctx, docId, async (renderer) => {
769
- await fs.mkdir(dir, { recursive: true });
770
- const written = [];
771
- const taken = /* @__PURE__ */ new Set();
772
- const write = async (name, bytes) => {
773
- const file = path.join(dir, name);
774
- await fs.writeFile(file, bytes);
775
- written.push(path.relative(ctx.userCwd, file));
776
- };
777
- const free = (base) => {
778
- let name = base;
779
- for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
780
- taken.add(name);
781
- return name;
782
- };
783
- const writeCopy = async (base) => {
784
- if (format === "pdf") await write(`${base}.pdf`, await renderer.pdf());
785
- else if (format === "html" || format === "docx") {
786
- const bundle = format === "html" ? await renderer.html() : await renderer.docx();
787
- if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
788
- await write(`${base}${path.extname(bundle.filename)}`, Buffer.from(bundle.base64, "base64"));
789
- } else {
790
- const width = String(renderer.status.pageCount).length;
791
- for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${base}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
792
- }
793
- };
794
- if (!opts.each) {
795
- await writeCopy(docId);
796
- return {
797
- docId,
798
- format,
799
- pageCount: renderer.status.pageCount,
800
- files: written
801
- };
802
- }
803
- const records = renderer.status.records;
804
- if (records === 0) throw new OpsError(422, `${docId} has no records — export \`records\` (rows from a .csv) to write one copy per row`);
805
- let pageCount = 0;
806
- for (let index = 0; index < records; index++) {
807
- const name = await renderer.setRecord(index, opts.name);
808
- pageCount += renderer.status.pageCount;
809
- await writeCopy(free(name));
810
- }
811
- return {
812
- docId,
813
- format,
814
- pageCount,
815
- files: written,
816
- records
817
- };
818
- });
819
- }
820
- //#endregion
821
- export { diffDocument as a, renderDocPage as i, closeRenderSession as n, exportDocument as r, checkLayout as t };
401
+ export { diffDocument as t };
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-cNpYUpF6.js";
1
+ import { r as createViteConfig } from "./session-BSbrC5gK.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {