ducjs 4.0.4 → 4.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.
Files changed (122) hide show
  1. package/dist/duc_locator_wasm.d.ts +48 -0
  2. package/dist/duc_locator_wasm.js +296 -0
  3. package/dist/duc_locator_wasm_bg.wasm +0 -0
  4. package/dist/duc_locator_wasm_bg.wasm.d.ts +13 -0
  5. package/dist/ducjs_wasi.wasm +0 -0
  6. package/dist/ducjs_wasm.d.ts +14 -2
  7. package/dist/ducjs_wasm.js +96 -8
  8. package/dist/ducjs_wasm_bg.wasm +0 -0
  9. package/dist/ducjs_wasm_bg.wasm.d.ts +6 -2
  10. package/dist/index.d.ts +4 -1
  11. package/dist/index.js +4 -1
  12. package/dist/locator-runtime.d.ts +4 -0
  13. package/dist/locator-runtime.js +7 -0
  14. package/dist/restore/index.d.ts +1 -0
  15. package/dist/restore/index.js +1 -0
  16. package/dist/restore/restoreDataState.d.ts +13 -24
  17. package/dist/restore/restoreDataState.js +49 -83
  18. package/dist/restore/restoreElements.d.ts +10 -15
  19. package/dist/restore/restoreElements.js +128 -125
  20. package/dist/restore/updateModelCode.d.ts +11 -0
  21. package/dist/restore/updateModelCode.js +63 -0
  22. package/dist/thumbnails/bounds.d.ts +21 -0
  23. package/dist/thumbnails/bounds.js +84 -0
  24. package/dist/thumbnails/browserRunner.d.ts +60 -0
  25. package/dist/thumbnails/browserRunner.js +446 -0
  26. package/dist/thumbnails/cameraPresets.d.ts +47 -0
  27. package/dist/thumbnails/cameraPresets.js +222 -0
  28. package/dist/thumbnails/cli.d.ts +2 -0
  29. package/dist/thumbnails/cli.js +102 -0
  30. package/dist/thumbnails/index.d.ts +11 -0
  31. package/dist/thumbnails/index.js +11 -0
  32. package/dist/thumbnails/lib/clientBundle.min.js +10427 -0
  33. package/dist/thumbnails/lib/clientEntry.d.ts +3 -0
  34. package/dist/thumbnails/lib/clientEntry.js +8 -0
  35. package/dist/thumbnails/lib/clippingUtils.d.ts +10 -0
  36. package/dist/thumbnails/lib/clippingUtils.js +3 -0
  37. package/dist/thumbnails/lib/defaultModelColor.d.ts +3 -0
  38. package/dist/thumbnails/lib/defaultModelColor.js +22 -0
  39. package/dist/thumbnails/lib/index.d.ts +12 -0
  40. package/dist/thumbnails/lib/index.js +12 -0
  41. package/dist/thumbnails/lib/mapViewerStateToOptions.d.ts +34 -0
  42. package/dist/thumbnails/lib/mapViewerStateToOptions.js +69 -0
  43. package/dist/thumbnails/lib/offscreen-dxf-thumbnail.d.ts +16 -0
  44. package/dist/thumbnails/lib/offscreen-dxf-thumbnail.js +173 -0
  45. package/dist/thumbnails/lib/offscreen-model-thumbnail.d.ts +16 -0
  46. package/dist/thumbnails/lib/offscreen-model-thumbnail.js +209 -0
  47. package/dist/thumbnails/lib/parametricClip.d.ts +18 -0
  48. package/dist/thumbnails/lib/parametricClip.js +177 -0
  49. package/dist/thumbnails/lib/parametricShapes.d.ts +1 -0
  50. package/dist/thumbnails/lib/parametricShapes.js +75 -0
  51. package/dist/thumbnails/lib/parametricViewerState.d.ts +26 -0
  52. package/dist/thumbnails/lib/parametricViewerState.js +198 -0
  53. package/dist/thumbnails/lib/thumbnail-camera-fit.d.ts +6 -0
  54. package/dist/thumbnails/lib/thumbnail-camera-fit.js +292 -0
  55. package/dist/thumbnails/lib/thumbnail-capture.d.ts +23 -0
  56. package/dist/thumbnails/lib/thumbnail-capture.js +161 -0
  57. package/dist/thumbnails/lib/thumbnail-visibility.d.ts +12 -0
  58. package/dist/thumbnails/lib/thumbnail-visibility.js +97 -0
  59. package/dist/thumbnails/lib/viewerGrid.d.ts +13 -0
  60. package/dist/thumbnails/lib/viewerGrid.js +57 -0
  61. package/dist/thumbnails/modelCache.d.ts +56 -0
  62. package/dist/thumbnails/modelCache.js +165 -0
  63. package/dist/thumbnails/modelOutputArtifact.d.ts +19 -0
  64. package/dist/thumbnails/modelOutputArtifact.js +87 -0
  65. package/dist/thumbnails/render.d.ts +45 -0
  66. package/dist/thumbnails/render.js +162 -0
  67. package/dist/thumbnails/templates.d.ts +16 -0
  68. package/dist/thumbnails/templates.js +786 -0
  69. package/dist/thumbnails/tessellator.d.ts +33 -0
  70. package/dist/thumbnails/tessellator.js +349 -0
  71. package/dist/thumbnails/types.d.ts +233 -0
  72. package/dist/thumbnails/types.js +1 -0
  73. package/dist/thumbnails/worker.d.ts +10 -0
  74. package/dist/thumbnails/worker.js +119 -0
  75. package/dist/transform.d.ts +1 -1
  76. package/dist/transform.js +20 -22
  77. package/dist/types/elements/index.d.ts +22 -28
  78. package/dist/types/elements/index.js +0 -1
  79. package/dist/types/geometry.types.d.ts +5 -5
  80. package/dist/types/index.d.ts +13 -59
  81. package/dist/types/index.js +0 -1
  82. package/dist/types/issues.types.d.ts +1 -2
  83. package/dist/utils/bounds.d.ts +10 -11
  84. package/dist/utils/bounds.js +105 -84
  85. package/dist/utils/constants.d.ts +5 -7
  86. package/dist/utils/constants.js +10 -15
  87. package/dist/utils/elements/freedrawElement.js +6 -3
  88. package/dist/utils/elements/index.d.ts +2 -6
  89. package/dist/utils/elements/index.js +4 -9
  90. package/dist/utils/elements/linearElement.d.ts +12 -14
  91. package/dist/utils/elements/linearElement.js +81 -66
  92. package/dist/utils/elements/newElement.d.ts +37 -22
  93. package/dist/utils/elements/newElement.js +70 -64
  94. package/dist/utils/elements/textElement.d.ts +34 -35
  95. package/dist/utils/elements/textElement.js +79 -83
  96. package/dist/utils/index.d.ts +1 -1
  97. package/dist/utils/index.js +1 -1
  98. package/dist/utils/locator.d.ts +43 -0
  99. package/dist/utils/locator.js +112 -0
  100. package/dist/utils/math/bbox.d.ts +1 -2
  101. package/dist/utils/math/geometry.js +5 -4
  102. package/dist/utils/math/index.d.ts +13 -17
  103. package/dist/utils/math/index.js +53 -41
  104. package/dist/utils/math/random.js +7 -2
  105. package/dist/utils/normalize.d.ts +5 -5
  106. package/dist/utils/normalize.js +15 -10
  107. package/dist/utils/shape.d.ts +3 -4
  108. package/dist/utils/shape.js +64 -48
  109. package/dist/utils/state/index.d.ts +3 -4
  110. package/dist/utils/state/index.js +8 -23
  111. package/dist/wasi.js +38 -12
  112. package/package.json +23 -9
  113. package/dist/technical/index.d.ts +0 -2
  114. package/dist/technical/index.js +0 -2
  115. package/dist/technical/measurements.d.ts +0 -31
  116. package/dist/technical/measurements.js +0 -64
  117. package/dist/technical/scopes.d.ts +0 -261
  118. package/dist/technical/scopes.js +0 -676
  119. package/dist/types/typeChecks.d.ts +0 -5
  120. package/dist/types/typeChecks.js +0 -10
  121. package/dist/utils/traverse.d.ts +0 -30
  122. package/dist/utils/traverse.js +0 -124
@@ -0,0 +1,63 @@
1
+ const PYTHON_IDENTIFIER_PATTERN = /^[A-Za-z_]\w*$/u;
2
+ export const getEncodedPythonModelModuleName = (elementId) => {
3
+ const encodedId = Array.from(new TextEncoder().encode(elementId))
4
+ .map((byte) => byte.toString(16).padStart(2, "0"))
5
+ .join("");
6
+ return `element_${encodedId || "00"}`;
7
+ };
8
+ export const getPythonModelModuleName = (elementId) => (PYTHON_IDENTIFIER_PATTERN.test(elementId)
9
+ ? elementId
10
+ : getEncodedPythonModelModuleName(elementId));
11
+ const escapeRegex = (value) => (value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
12
+ /**
13
+ * Updates Python code referencing model element IDs when IDs are restored or duplicated.
14
+ * Replaces references in:
15
+ * - `from duc_model.<id_or_module> import ...`
16
+ * - `import duc_model.<id_or_module>`
17
+ * - `duc_model.<id_or_module>`
18
+ * - `from duc_model import <id_or_module>`
19
+ */
20
+ export const updateModelCodeElementIds = (code, idMap) => {
21
+ if (!code || typeof code !== "string") {
22
+ return code;
23
+ }
24
+ const entries = [];
25
+ const entriesIterable = idMap instanceof Map ? idMap.entries() : Object.entries(idMap);
26
+ for (const [oldId, newId] of entriesIterable) {
27
+ if (!oldId || !newId || oldId === newId) {
28
+ continue;
29
+ }
30
+ const oldModuleName = getPythonModelModuleName(oldId);
31
+ const newModuleName = getPythonModelModuleName(newId);
32
+ const oldEncoded = getEncodedPythonModelModuleName(oldId);
33
+ const targets = new Set();
34
+ targets.add(oldId);
35
+ targets.add(oldModuleName);
36
+ targets.add(oldEncoded);
37
+ entries.push({
38
+ targets: Array.from(targets).sort((a, b) => b.length - a.length),
39
+ replacement: newModuleName,
40
+ });
41
+ }
42
+ if (entries.length === 0) {
43
+ return code;
44
+ }
45
+ let updatedCode = code;
46
+ for (const { targets, replacement } of entries) {
47
+ for (const target of targets) {
48
+ const escaped = escapeRegex(target);
49
+ const boundary = /^\w+$/.test(target) ? "\\b" : "(?=[^A-Za-z0-9_-]|$)";
50
+ // 1. Replace `duc_model.<target>`
51
+ const ducModelRegex = new RegExp(`(duc_model\\.)(?:${escaped})${boundary}`, "g");
52
+ updatedCode = updatedCode.replace(ducModelRegex, `$1${replacement}`);
53
+ // 2. Replace `from duc_model import ...` items
54
+ const fromImportRegex = /(from\s+duc_model\s+import\s+)([^#\n\r]+)/g;
55
+ updatedCode = updatedCode.replace(fromImportRegex, (_full, prefix, importedList) => {
56
+ const itemRegex = new RegExp(`(^|[,\\s])${escaped}(\\b|(?=[\\s,]|$))`, "g");
57
+ const replacedList = importedList.replace(itemRegex, `$1${replacement}$2`);
58
+ return `${prefix}${replacedList}`;
59
+ });
60
+ }
61
+ }
62
+ return updatedCode;
63
+ };
@@ -0,0 +1,21 @@
1
+ import type { DucModelElement } from "../types/elements";
2
+ /**
3
+ * Check if a color is grayscale (neutral color from white to grey to black or transparent).
4
+ * Returns true if the color has no actual chromatic hue.
5
+ * Directly mirrors packages/core/canvas/utils/thumbnailGenerator.ts.
6
+ */
7
+ export declare const isGrayscaleColor: (color: string) => boolean;
8
+ /**
9
+ * Determines the effective background color for thumbnail generation.
10
+ * If none provided (or "transparent"), defaults to "transparent".
11
+ * If an explicit background color is provided, preserves that color.
12
+ */
13
+ export declare const resolveThumbnailBackground: (backgroundColor?: string) => string;
14
+ /**
15
+ * Calculates updated element dimensions preserving the aspect ratio of the generated thumbnail.
16
+ * Directly mirrors packages/client/ui/blocks/core/three/lib/model-thumbnail-bounds.ts.
17
+ */
18
+ export declare const getModelThumbnailBoundsUpdate: (element: DucModelElement, thumbnailWidth: number, thumbnailHeight: number) => {
19
+ width: number;
20
+ height: number;
21
+ } | null;
@@ -0,0 +1,84 @@
1
+ const THUMBNAIL_RATIO_EPSILON = 1e-3;
2
+ /**
3
+ * Check if a color is grayscale (neutral color from white to grey to black or transparent).
4
+ * Returns true if the color has no actual chromatic hue.
5
+ * Directly mirrors packages/core/canvas/utils/thumbnailGenerator.ts.
6
+ */
7
+ export const isGrayscaleColor = (color) => {
8
+ if (!color || color === "transparent" || color === "rgba(0,0,0,0)")
9
+ return true;
10
+ let r, g, b;
11
+ if (color.startsWith("#")) {
12
+ const hex = color.slice(1);
13
+ if (hex.length === 3) {
14
+ r = parseInt(hex[0] + hex[0], 16);
15
+ g = parseInt(hex[1] + hex[1], 16);
16
+ b = parseInt(hex[2] + hex[2], 16);
17
+ }
18
+ else if (hex.length === 6 || hex.length === 8) {
19
+ r = parseInt(hex.slice(0, 2), 16);
20
+ g = parseInt(hex.slice(2, 4), 16);
21
+ b = parseInt(hex.slice(4, 6), 16);
22
+ }
23
+ else {
24
+ return true;
25
+ }
26
+ }
27
+ else if (color.startsWith("rgb")) {
28
+ const match = color.match(/\d+/g);
29
+ if (!match || match.length < 3)
30
+ return true;
31
+ r = parseInt(match[0], 10);
32
+ g = parseInt(match[1], 10);
33
+ b = parseInt(match[2], 10);
34
+ }
35
+ else {
36
+ return true;
37
+ }
38
+ const tolerance = 10;
39
+ return (Math.abs(r - g) <= tolerance &&
40
+ Math.abs(g - b) <= tolerance &&
41
+ Math.abs(r - b) <= tolerance);
42
+ };
43
+ /**
44
+ * Determines the effective background color for thumbnail generation.
45
+ * If none provided (or "transparent"), defaults to "transparent".
46
+ * If an explicit background color is provided, preserves that color.
47
+ */
48
+ export const resolveThumbnailBackground = (backgroundColor) => {
49
+ if (!backgroundColor || backgroundColor.trim() === "" || backgroundColor === "transparent") {
50
+ return "transparent";
51
+ }
52
+ return backgroundColor.trim();
53
+ };
54
+ /**
55
+ * Calculates updated element dimensions preserving the aspect ratio of the generated thumbnail.
56
+ * Directly mirrors packages/client/ui/blocks/core/three/lib/model-thumbnail-bounds.ts.
57
+ */
58
+ export const getModelThumbnailBoundsUpdate = (element, thumbnailWidth, thumbnailHeight) => {
59
+ if (!(thumbnailWidth > 0) || !(thumbnailHeight > 0))
60
+ return null;
61
+ const currentWidth = element.width;
62
+ const currentHeight = element.height;
63
+ const absoluteWidth = Math.abs(currentWidth);
64
+ const absoluteHeight = Math.abs(currentHeight);
65
+ if (!(absoluteWidth > 0) || !(absoluteHeight > 0))
66
+ return null;
67
+ const currentRatio = absoluteWidth / absoluteHeight;
68
+ const thumbnailRatio = thumbnailWidth / thumbnailHeight;
69
+ if (!Number.isFinite(currentRatio) || !Number.isFinite(thumbnailRatio))
70
+ return null;
71
+ if (Math.abs(currentRatio - thumbnailRatio) <= THUMBNAIL_RATIO_EPSILON)
72
+ return null;
73
+ const longEdge = Math.max(absoluteWidth, absoluteHeight);
74
+ const nextWidth = thumbnailRatio >= 1 ? longEdge : longEdge * thumbnailRatio;
75
+ const nextHeight = thumbnailRatio >= 1 ? longEdge / thumbnailRatio : longEdge;
76
+ if (!(nextWidth > 0) || !(nextHeight > 0))
77
+ return null;
78
+ const signedWidth = currentWidth < 0 ? -nextWidth : nextWidth;
79
+ const signedHeight = currentHeight < 0 ? -nextHeight : nextHeight;
80
+ return {
81
+ width: signedWidth,
82
+ height: signedHeight,
83
+ };
84
+ };
@@ -0,0 +1,60 @@
1
+ export type BrowserRendererMode = "auto" | "gpu" | "cpu";
2
+ export interface BrowserRunnerOptions {
3
+ executablePath?: string;
4
+ userDataDir?: string;
5
+ useSoftwareRenderer?: boolean;
6
+ mode?: BrowserRendererMode;
7
+ timeoutMs?: number;
8
+ }
9
+ export interface CaptureHtmlResult {
10
+ data: Uint8Array;
11
+ base64: string;
12
+ width: number;
13
+ height: number;
14
+ renderer?: string;
15
+ isGpu?: boolean;
16
+ }
17
+ /**
18
+ * Resolves the path to a Chrome or Chromium executable on the system.
19
+ */
20
+ export declare function resolveBrowserExecutable(customPath?: string): string | null;
21
+ /**
22
+ * Headless Chromium runner managing persistent browser lifecycle and CDP commands.
23
+ */
24
+ export declare class HeadlessBrowserRunner {
25
+ private executablePath;
26
+ private userDataDir?;
27
+ private browserProcess;
28
+ private ws;
29
+ private wsUrl;
30
+ private nextMessageId;
31
+ private pendingCallbacks;
32
+ private mode;
33
+ private useSoftwareRenderer;
34
+ private isShuttingDown;
35
+ private isAutoUserDataDir;
36
+ private sessionExceptions;
37
+ constructor(options?: BrowserRunnerOptions);
38
+ /**
39
+ * Spawns the headless browser process and establishes the CDP WebSocket connection.
40
+ */
41
+ start(): Promise<void>;
42
+ private sendCdp;
43
+ /**
44
+ * Captures a screenshot from an HTML document string, gracefully falling back from GPU to CPU in auto mode.
45
+ */
46
+ captureHtml(html: string, width: number, height: number, format?: "png" | "jpeg" | "webp", timeoutMs?: number): Promise<CaptureHtmlResult>;
47
+ private executeCaptureHtml;
48
+ /**
49
+ * Terminates the browser process and closes WebSocket connections.
50
+ */
51
+ stop(): Promise<void>;
52
+ }
53
+ /**
54
+ * Gets or creates a singleton persistent headless browser runner based on acceleration preference.
55
+ */
56
+ export declare function getSharedBrowserRunner(options?: BrowserRunnerOptions): HeadlessBrowserRunner;
57
+ /**
58
+ * Shuts down all cached shared browser runners.
59
+ */
60
+ export declare function shutdownAllBrowserRunners(): Promise<void>;
@@ -0,0 +1,446 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { spawn } from "child_process";
11
+ import fs from "fs";
12
+ import os from "os";
13
+ import path from "path";
14
+ const COMMON_EXECUTABLE_PATHS = [
15
+ // macOS
16
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
17
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
18
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
19
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
20
+ // Linux
21
+ "/usr/bin/google-chrome",
22
+ "/usr/bin/google-chrome-stable",
23
+ "/usr/bin/chromium",
24
+ "/usr/bin/chromium-browser",
25
+ "/snap/bin/chromium",
26
+ // Windows
27
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
28
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
29
+ ];
30
+ /**
31
+ * Resolves the path to a Chrome or Chromium executable on the system.
32
+ */
33
+ export function resolveBrowserExecutable(customPath) {
34
+ if (customPath && fs.existsSync(customPath)) {
35
+ return customPath;
36
+ }
37
+ const envPath = process.env.CHROME_PATH ||
38
+ process.env.CHROMIUM_PATH ||
39
+ process.env.GOOGLE_CHROME_BIN;
40
+ if (envPath && fs.existsSync(envPath)) {
41
+ return envPath;
42
+ }
43
+ for (const candidate of COMMON_EXECUTABLE_PATHS) {
44
+ if (fs.existsSync(candidate)) {
45
+ return candidate;
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+ /**
51
+ * Headless Chromium runner managing persistent browser lifecycle and CDP commands.
52
+ */
53
+ export class HeadlessBrowserRunner {
54
+ constructor(options = {}) {
55
+ this.browserProcess = null;
56
+ this.ws = null;
57
+ this.wsUrl = null;
58
+ this.nextMessageId = 1;
59
+ this.pendingCallbacks = new Map();
60
+ this.isShuttingDown = false;
61
+ this.isAutoUserDataDir = false;
62
+ this.sessionExceptions = new Map();
63
+ const resolved = resolveBrowserExecutable(options.executablePath);
64
+ if (!resolved) {
65
+ throw new Error("Could not find a Chrome or Chromium executable. Set CHROME_PATH or install Chrome.");
66
+ }
67
+ this.executablePath = resolved;
68
+ this.userDataDir = options.userDataDir;
69
+ if (!this.userDataDir) {
70
+ try {
71
+ this.userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "duc-chrome-profile-"));
72
+ this.isAutoUserDataDir = true;
73
+ }
74
+ catch (_a) {
75
+ // Fall back to undefined if tempdir fails
76
+ }
77
+ }
78
+ if (options.mode === "cpu" || options.useSoftwareRenderer === true) {
79
+ this.mode = "cpu";
80
+ this.useSoftwareRenderer = true;
81
+ }
82
+ else if (options.mode === "gpu" || options.useSoftwareRenderer === false) {
83
+ this.mode = "gpu";
84
+ this.useSoftwareRenderer = false;
85
+ }
86
+ else {
87
+ this.mode = "auto";
88
+ this.useSoftwareRenderer = false;
89
+ }
90
+ }
91
+ /**
92
+ * Spawns the headless browser process and establishes the CDP WebSocket connection.
93
+ */
94
+ start() {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
97
+ return;
98
+ }
99
+ const args = [
100
+ "--headless=new",
101
+ "--remote-debugging-port=0",
102
+ "--hide-scrollbars",
103
+ "--no-first-run",
104
+ "--no-default-browser-check",
105
+ "--disable-notifications",
106
+ "--disable-extensions",
107
+ "--disable-component-update",
108
+ "--deny-permission-prompts",
109
+ "--disable-background-networking",
110
+ "--disable-background-timer-throttling",
111
+ "--disable-client-side-phishing-detection",
112
+ "--disable-default-apps",
113
+ "--disable-popup-blocking",
114
+ "--disable-prompt-on-repost",
115
+ "--disable-sync",
116
+ "--disable-translate",
117
+ "--metrics-recording-only",
118
+ "--no-sandbox",
119
+ "--disable-setuid-sandbox",
120
+ "--disable-dev-shm-usage",
121
+ "--allow-file-access-from-files",
122
+ "--disable-web-security",
123
+ "about:blank",
124
+ ];
125
+ if (this.userDataDir)
126
+ args.push(`--user-data-dir=${this.userDataDir}`);
127
+ if (this.useSoftwareRenderer) {
128
+ args.push("--disable-gpu", "--use-gl=angle", "--use-angle=swiftshader");
129
+ }
130
+ else {
131
+ args.push("--enable-webgl", "--ignore-gpu-blocklist", "--enable-gpu-rasterization", "--use-gl=angle");
132
+ }
133
+ this.browserProcess = spawn(this.executablePath, args, {
134
+ stdio: ["ignore", "ignore", "pipe"],
135
+ });
136
+ const browserPid = this.browserProcess.pid;
137
+ const cleanup = () => {
138
+ if (!this.isShuttingDown && this.browserProcess) {
139
+ this.stop().catch(() => { });
140
+ }
141
+ };
142
+ process.once("exit", cleanup);
143
+ process.once("SIGINT", cleanup);
144
+ process.once("SIGTERM", cleanup);
145
+ // Wait for DevTools WebSocket URL from stderr
146
+ const wsUrl = yield new Promise((resolve, reject) => {
147
+ var _a, _b, _c, _d;
148
+ let stderrBuffer = "";
149
+ const timeout = setTimeout(() => {
150
+ reject(new Error(`Timed out waiting for Chrome DevTools websocket URL. Stderr: ${stderrBuffer.slice(0, 500)}`));
151
+ }, 10000);
152
+ const onData = (data) => {
153
+ var _a, _b;
154
+ stderrBuffer += data.toString();
155
+ const match = stderrBuffer.match(/DevTools listening on (ws:\/\/127\.0\.0\.1:\d+\/devtools\/browser\/[a-zA-Z0-9-]+)/);
156
+ if (match) {
157
+ clearTimeout(timeout);
158
+ (_b = (_a = this.browserProcess) === null || _a === void 0 ? void 0 : _a.stderr) === null || _b === void 0 ? void 0 : _b.removeListener("data", onData);
159
+ resolve(match[1]);
160
+ }
161
+ };
162
+ (_b = (_a = this.browserProcess) === null || _a === void 0 ? void 0 : _a.stderr) === null || _b === void 0 ? void 0 : _b.on("data", onData);
163
+ (_c = this.browserProcess) === null || _c === void 0 ? void 0 : _c.once("error", (err) => {
164
+ clearTimeout(timeout);
165
+ reject(err);
166
+ });
167
+ (_d = this.browserProcess) === null || _d === void 0 ? void 0 : _d.once("exit", (code) => {
168
+ clearTimeout(timeout);
169
+ reject(new Error(`Chrome exited prematurely with code ${code}. Stderr: ${stderrBuffer.slice(0, 500)}`));
170
+ });
171
+ });
172
+ this.wsUrl = wsUrl;
173
+ // Connect WebSocket
174
+ yield new Promise((resolve, reject) => {
175
+ this.ws = new WebSocket(wsUrl);
176
+ this.ws.onopen = () => resolve();
177
+ this.ws.onerror = (evt) => reject(new Error(`WebSocket connection failed: ${evt}`));
178
+ this.ws.onmessage = (evt) => {
179
+ var _a;
180
+ try {
181
+ const res = JSON.parse(evt.data.toString());
182
+ if (res.id && this.pendingCallbacks.has(res.id)) {
183
+ const cb = this.pendingCallbacks.get(res.id);
184
+ this.pendingCallbacks.delete(res.id);
185
+ cb(res);
186
+ }
187
+ if (res.method === "Runtime.exceptionThrown" && res.params) {
188
+ const details = res.params.exceptionDetails;
189
+ const desc = ((_a = details === null || details === void 0 ? void 0 : details.exception) === null || _a === void 0 ? void 0 : _a.description) || (details === null || details === void 0 ? void 0 : details.text) || "Unknown page exception";
190
+ this.sessionExceptions.set(res.sessionId || "", desc);
191
+ }
192
+ if (res.method === "Runtime.consoleAPICalled" && res.params) {
193
+ const args = (res.params.args || []).map((a) => { var _a, _b; return (_b = (_a = a.value) !== null && _a !== void 0 ? _a : a.description) !== null && _b !== void 0 ? _b : ""; }).join(" ");
194
+ process.stderr.write(`[BrowserConsole] ${args}\n`);
195
+ }
196
+ }
197
+ catch (_b) {
198
+ // Ignore unparseable frames
199
+ }
200
+ };
201
+ });
202
+ });
203
+ }
204
+ sendCdp(method, params = {}, sessionId) {
205
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
206
+ throw new Error("CDP WebSocket is not connected.");
207
+ }
208
+ const id = this.nextMessageId++;
209
+ const message = { id, method, params };
210
+ if (sessionId) {
211
+ message.sessionId = sessionId;
212
+ }
213
+ return new Promise((resolve, reject) => {
214
+ this.pendingCallbacks.set(id, (res) => {
215
+ var _a;
216
+ if (res.error) {
217
+ reject(new Error(`CDP error (${res.error.code}): ${res.error.message}`));
218
+ }
219
+ else {
220
+ resolve((_a = res.result) !== null && _a !== void 0 ? _a : {});
221
+ }
222
+ });
223
+ this.ws.send(JSON.stringify(message));
224
+ });
225
+ }
226
+ /**
227
+ * Captures a screenshot from an HTML document string, gracefully falling back from GPU to CPU in auto mode.
228
+ */
229
+ captureHtml(html_1, width_1, height_1) {
230
+ return __awaiter(this, arguments, void 0, function* (html, width, height, format = "png", timeoutMs = 45000) {
231
+ try {
232
+ return yield this.executeCaptureHtml(html, width, height, format, timeoutMs);
233
+ }
234
+ catch (err) {
235
+ if (this.mode === "auto" && !this.useSoftwareRenderer) {
236
+ process.stderr.write(`[BrowserRunner] GPU rendering failed (${err.message}). Falling back to CPU SwiftShader software renderer.\n`);
237
+ yield this.stop();
238
+ this.useSoftwareRenderer = true;
239
+ return yield this.executeCaptureHtml(html, width, height, format, timeoutMs);
240
+ }
241
+ throw err;
242
+ }
243
+ });
244
+ }
245
+ executeCaptureHtml(html_1, width_1, height_1) {
246
+ return __awaiter(this, arguments, void 0, function* (html, width, height, format = "png", timeoutMs = 45000) {
247
+ var _a;
248
+ yield this.start();
249
+ // Write HTML to temporary file
250
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "duc-thumb-"));
251
+ const htmlFile = path.join(tempDir, "index.html");
252
+ fs.writeFileSync(htmlFile, html, "utf8");
253
+ try {
254
+ // Create new page target
255
+ const { targetId } = (yield this.sendCdp("Target.createTarget", {
256
+ url: `file://${htmlFile}`,
257
+ }));
258
+ const { sessionId } = (yield this.sendCdp("Target.attachToTarget", {
259
+ targetId,
260
+ flatten: true,
261
+ }));
262
+ try {
263
+ yield this.sendCdp("Page.enable", {}, sessionId);
264
+ yield this.sendCdp("Runtime.enable", {}, sessionId);
265
+ yield this.sendCdp("Emulation.setDeviceMetricsOverride", {
266
+ width,
267
+ height,
268
+ deviceScaleFactor: 1,
269
+ mobile: false,
270
+ }, sessionId);
271
+ // Wait for rendering to complete
272
+ const start = Date.now();
273
+ let ready = false;
274
+ let actualWidth = width;
275
+ let actualHeight = height;
276
+ let glRenderer;
277
+ let isGpu;
278
+ while (Date.now() - start < timeoutMs) {
279
+ const evalRes = (yield this.sendCdp("Runtime.evaluate", {
280
+ expression: `(() => {
281
+ if (window.__thumbnailError) return { status: "error", error: window.__thumbnailError };
282
+ if (window.__thumbnailReady === true) {
283
+ return {
284
+ status: "ready",
285
+ width: window.__thumbnailWidth || ${width},
286
+ height: window.__thumbnailHeight || ${height},
287
+ base64: window.__thumbnailBase64 || null,
288
+ renderer: window.__thumbnailRenderer || null,
289
+ isGpu: window.__thumbnailIsGpu ?? null
290
+ };
291
+ }
292
+ return { status: "waiting" };
293
+ })()`,
294
+ returnByValue: true,
295
+ }, sessionId));
296
+ const resVal = (_a = evalRes === null || evalRes === void 0 ? void 0 : evalRes.result) === null || _a === void 0 ? void 0 : _a.value;
297
+ if ((resVal === null || resVal === void 0 ? void 0 : resVal.status) === "ready") {
298
+ ready = true;
299
+ if (resVal.width && resVal.height) {
300
+ actualWidth = resVal.width;
301
+ actualHeight = resVal.height;
302
+ }
303
+ if (resVal.renderer)
304
+ glRenderer = resVal.renderer;
305
+ if (resVal.isGpu !== null && resVal.isGpu !== undefined)
306
+ isGpu = resVal.isGpu;
307
+ if (resVal.base64) {
308
+ const binary = Uint8Array.from(Buffer.from(resVal.base64, "base64"));
309
+ return {
310
+ data: binary,
311
+ base64: resVal.base64,
312
+ width: actualWidth,
313
+ height: actualHeight,
314
+ renderer: glRenderer,
315
+ isGpu: isGpu !== null && isGpu !== void 0 ? isGpu : !this.useSoftwareRenderer,
316
+ };
317
+ }
318
+ break;
319
+ }
320
+ if ((resVal === null || resVal === void 0 ? void 0 : resVal.status) === "error") {
321
+ throw new Error(`Renderer error in browser page: ${resVal.error}`);
322
+ }
323
+ const sessionErr = this.sessionExceptions.get(sessionId);
324
+ if (sessionErr) {
325
+ throw new Error(`Renderer script error in browser page: ${sessionErr}`);
326
+ }
327
+ yield new Promise((r) => setTimeout(r, 100));
328
+ }
329
+ if (!ready) {
330
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for thumbnail render completion.`);
331
+ }
332
+ if (actualWidth !== width || actualHeight !== height) {
333
+ yield this.sendCdp("Emulation.setDeviceMetricsOverride", {
334
+ width: actualWidth,
335
+ height: actualHeight,
336
+ deviceScaleFactor: 1,
337
+ mobile: false,
338
+ }, sessionId).catch(() => { });
339
+ }
340
+ // Capture screenshot
341
+ const screenshotRes = (yield this.sendCdp("Page.captureScreenshot", {
342
+ format,
343
+ clip: {
344
+ x: 0,
345
+ y: 0,
346
+ width: actualWidth,
347
+ height: actualHeight,
348
+ scale: 1,
349
+ },
350
+ }, sessionId));
351
+ const base64 = screenshotRes.data;
352
+ const binary = Uint8Array.from(Buffer.from(base64, "base64"));
353
+ return {
354
+ data: binary,
355
+ base64,
356
+ width: actualWidth,
357
+ height: actualHeight,
358
+ renderer: glRenderer,
359
+ isGpu: isGpu !== null && isGpu !== void 0 ? isGpu : !this.useSoftwareRenderer,
360
+ };
361
+ }
362
+ finally {
363
+ this.sessionExceptions.delete(sessionId);
364
+ yield this.sendCdp("Target.closeTarget", { targetId }).catch(() => { });
365
+ }
366
+ }
367
+ finally {
368
+ try {
369
+ fs.rmSync(tempDir, { recursive: true, force: true });
370
+ }
371
+ catch (_b) {
372
+ // Best-effort temp dir cleanup
373
+ }
374
+ }
375
+ });
376
+ }
377
+ /**
378
+ * Terminates the browser process and closes WebSocket connections.
379
+ */
380
+ stop() {
381
+ return __awaiter(this, void 0, void 0, function* () {
382
+ this.isShuttingDown = true;
383
+ try {
384
+ if (this.ws) {
385
+ this.ws.close();
386
+ this.ws = null;
387
+ }
388
+ if (this.browserProcess && !this.browserProcess.killed) {
389
+ this.browserProcess.kill("SIGKILL");
390
+ this.browserProcess = null;
391
+ }
392
+ if (this.isAutoUserDataDir && this.userDataDir) {
393
+ try {
394
+ fs.rmSync(this.userDataDir, { recursive: true, force: true });
395
+ }
396
+ catch (_a) { }
397
+ }
398
+ }
399
+ catch (_b) {
400
+ // Best-effort cleanup
401
+ }
402
+ });
403
+ }
404
+ }
405
+ let sharedGpuRunner = null;
406
+ let sharedCpuRunner = null;
407
+ let sharedAutoRunner = null;
408
+ /**
409
+ * Gets or creates a singleton persistent headless browser runner based on acceleration preference.
410
+ */
411
+ export function getSharedBrowserRunner(options) {
412
+ var _a;
413
+ const mode = (_a = options === null || options === void 0 ? void 0 : options.mode) !== null && _a !== void 0 ? _a : ((options === null || options === void 0 ? void 0 : options.useSoftwareRenderer) === true
414
+ ? "cpu"
415
+ : (options === null || options === void 0 ? void 0 : options.useSoftwareRenderer) === false
416
+ ? "gpu"
417
+ : "auto");
418
+ if (mode === "cpu") {
419
+ if (!sharedCpuRunner) {
420
+ sharedCpuRunner = new HeadlessBrowserRunner(Object.assign(Object.assign({}, options), { mode: "cpu", useSoftwareRenderer: true }));
421
+ }
422
+ return sharedCpuRunner;
423
+ }
424
+ if (mode === "gpu") {
425
+ if (!sharedGpuRunner) {
426
+ sharedGpuRunner = new HeadlessBrowserRunner(Object.assign(Object.assign({}, options), { mode: "gpu", useSoftwareRenderer: false }));
427
+ }
428
+ return sharedGpuRunner;
429
+ }
430
+ if (!sharedAutoRunner) {
431
+ sharedAutoRunner = new HeadlessBrowserRunner(Object.assign(Object.assign({}, options), { mode: "auto" }));
432
+ }
433
+ return sharedAutoRunner;
434
+ }
435
+ /**
436
+ * Shuts down all cached shared browser runners.
437
+ */
438
+ export function shutdownAllBrowserRunners() {
439
+ return __awaiter(this, void 0, void 0, function* () {
440
+ const runners = [sharedGpuRunner, sharedCpuRunner, sharedAutoRunner].filter(Boolean);
441
+ sharedGpuRunner = null;
442
+ sharedCpuRunner = null;
443
+ sharedAutoRunner = null;
444
+ yield Promise.all(runners.map((r) => r.stop()));
445
+ });
446
+ }