@bluemoonfoundry/daz-ts 0.0.0-stage → 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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +377 -2
  3. package/dist/animation.d.ts +129 -0
  4. package/dist/animation.js +276 -0
  5. package/dist/batch.d.ts +118 -0
  6. package/dist/batch.js +186 -0
  7. package/dist/bone.d.ts +50 -0
  8. package/dist/bone.js +66 -0
  9. package/dist/camera.d.ts +61 -0
  10. package/dist/camera.js +120 -0
  11. package/dist/cinematics.d.ts +188 -0
  12. package/dist/cinematics.js +165 -0
  13. package/dist/client.d.ts +399 -0
  14. package/dist/client.js +769 -0
  15. package/dist/dforce.d.ts +15 -0
  16. package/dist/dforce.js +36 -0
  17. package/dist/element.d.ts +51 -0
  18. package/dist/element.js +141 -0
  19. package/dist/exceptions.d.ts +124 -0
  20. package/dist/exceptions.js +173 -0
  21. package/dist/geometry.d.ts +81 -0
  22. package/dist/geometry.js +433 -0
  23. package/dist/index.d.ts +50 -0
  24. package/dist/index.js +36 -0
  25. package/dist/light.d.ts +24 -0
  26. package/dist/light.js +40 -0
  27. package/dist/lighting.d.ts +120 -0
  28. package/dist/lighting.js +107 -0
  29. package/dist/material.d.ts +27 -0
  30. package/dist/material.js +63 -0
  31. package/dist/materials.d.ts +107 -0
  32. package/dist/materials.js +165 -0
  33. package/dist/math3.d.ts +204 -0
  34. package/dist/math3.js +502 -0
  35. package/dist/modifier.d.ts +14 -0
  36. package/dist/modifier.js +24 -0
  37. package/dist/morph.d.ts +11 -0
  38. package/dist/morph.js +24 -0
  39. package/dist/node.d.ts +196 -0
  40. package/dist/node.js +447 -0
  41. package/dist/polling.d.ts +24 -0
  42. package/dist/polling.js +50 -0
  43. package/dist/pose.d.ts +82 -0
  44. package/dist/pose.js +295 -0
  45. package/dist/poses.d.ts +54 -0
  46. package/dist/poses.js +40 -0
  47. package/dist/property.d.ts +64 -0
  48. package/dist/property.js +125 -0
  49. package/dist/render.d.ts +242 -0
  50. package/dist/render.js +811 -0
  51. package/dist/renderApi.d.ts +124 -0
  52. package/dist/renderApi.js +235 -0
  53. package/dist/result.d.ts +15 -0
  54. package/dist/result.js +1 -0
  55. package/dist/scene.d.ts +154 -0
  56. package/dist/scene.js +584 -0
  57. package/dist/sceneEvents.d.ts +63 -0
  58. package/dist/sceneEvents.js +102 -0
  59. package/dist/sceneState.d.ts +167 -0
  60. package/dist/sceneState.js +430 -0
  61. package/dist/scriptBuilder.d.ts +41 -0
  62. package/dist/scriptBuilder.js +72 -0
  63. package/dist/shotGeometry.d.ts +49 -0
  64. package/dist/shotGeometry.js +76 -0
  65. package/dist/skeleton.d.ts +120 -0
  66. package/dist/skeleton.js +561 -0
  67. package/dist/timeline.d.ts +24 -0
  68. package/dist/timeline.js +39 -0
  69. package/dist/undo.d.ts +24 -0
  70. package/dist/undo.js +45 -0
  71. package/dist/version.d.ts +31 -0
  72. package/dist/version.js +36 -0
  73. package/dist/viewport.d.ts +58 -0
  74. package/dist/viewport.js +239 -0
  75. package/package.json +52 -4
package/dist/client.js ADDED
@@ -0,0 +1,769 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { Readable } from "node:stream";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { ArtifactError, AuthenticationError, ConnectionError, ConcurrencyLimitError, DazBusyError, DazError, DazTimeoutError, ScriptRuntimeError, ScriptSyntaxError, StudioBusyError, } from "./exceptions.js";
7
+ import { buildOperationsScript } from "./batch.js";
8
+ import { evaluateServerVersion } from "./version.js";
9
+ const TOKEN_FILE = path.join(os.homedir(), ".daz3d", "dazscriptserver_token.txt");
10
+ const DEFAULT_HOST = "127.0.0.1";
11
+ const DEFAULT_PORT = 18811;
12
+ function loadToken() {
13
+ try {
14
+ return fs.readFileSync(TOKEN_FILE, "utf-8").trim();
15
+ }
16
+ catch {
17
+ return "";
18
+ }
19
+ }
20
+ function parseRetryAfter(headers) {
21
+ const raw = headers.get("Retry-After");
22
+ const value = raw !== null ? Number.parseFloat(raw) : NaN;
23
+ return Number.isFinite(value) ? value : 2.0;
24
+ }
25
+ /**
26
+ * Build an AuthenticationError for a 401/403 response, keeping the server's
27
+ * `ErrorResponse` fields (`error_code`, `detail`, `retryable`) when present.
28
+ */
29
+ async function authenticationError(resp) {
30
+ const status = resp.status;
31
+ const text = await resp.text();
32
+ let data = {};
33
+ try {
34
+ const parsed = JSON.parse(text);
35
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
36
+ data = parsed;
37
+ }
38
+ }
39
+ catch {
40
+ // Non-JSON body (proxy, early httplib rejection): fall back to the raw text.
41
+ }
42
+ const error = typeof data.error === "string" && data.error ? data.error : text.slice(0, 200);
43
+ const detail = data.detail === undefined || data.detail === null ? "" : typeof data.detail === "string" ? data.detail : JSON.stringify(data.detail);
44
+ return new AuthenticationError(`HTTP ${status}: ${error}`, status, typeof data.error_code === "string" ? data.error_code : "", detail, data.retryable === true);
45
+ }
46
+ /**
47
+ * Check the response status and raise an exception for errors, or return the parsed body for caller reuse.
48
+ * Callers must use the returned value instead of re-reading the response body, since Node's fetch only allows one read.
49
+ * @returns undefined if status < 400, or the parsed JSON body if >= 400 and no exception was thrown.
50
+ */
51
+ async function raiseForError(resp) {
52
+ const status = resp.status;
53
+ if (status === 401 || status === 403) {
54
+ throw await authenticationError(resp);
55
+ }
56
+ if (status < 400) {
57
+ return undefined;
58
+ }
59
+ // An intermediary (proxy, 502 gateway) or an early httplib rejection can
60
+ // send a non-JSON body; read it as text so it still maps to a DazError.
61
+ const text = await resp.text();
62
+ let data;
63
+ try {
64
+ const parsed = JSON.parse(text);
65
+ data = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
66
+ }
67
+ catch {
68
+ throw new DazError(`HTTP ${status}: ${text.slice(0, 200) || resp.statusText}`);
69
+ }
70
+ const errorCode = data.error_code ?? "";
71
+ const errorMsg = data.error ?? `HTTP ${status}`;
72
+ const retryAfter = parseRetryAfter(resp.headers);
73
+ if (errorCode === "STUDIO_BUSY") {
74
+ throw new StudioBusyError(errorMsg, data.detail ?? errorMsg, retryAfter);
75
+ }
76
+ if (errorCode === "CONCURRENT_LIMIT_EXCEEDED") {
77
+ throw new ConcurrencyLimitError(errorMsg, errorMsg, retryAfter);
78
+ }
79
+ return data;
80
+ }
81
+ /** Throw ArtifactError (or AuthenticationError/busy errors) for a rejected artifact request. */
82
+ async function throwArtifactError(resp) {
83
+ if (resp.status < 400)
84
+ return;
85
+ if (resp.status === 416) {
86
+ throw new ArtifactError("Requested range is outside the artifact (HTTP 416)", 416);
87
+ }
88
+ const data = await raiseForError(resp);
89
+ const code = data?.error_code ?? "";
90
+ const msg = data?.error ?? `HTTP ${resp.status}`;
91
+ throw new ArtifactError(msg, resp.status, code);
92
+ }
93
+ /** Base name safe to join under a download directory (no separators, no `..`). */
94
+ export function safeArtifactFilename(name) {
95
+ const base = name.replace(/\\/g, "/").split("/").pop() ?? "";
96
+ // eslint-disable-next-line no-control-regex
97
+ const cleaned = base.replace(/[:*?"<>|\x00-\x1f]/g, "_");
98
+ return cleaned.replace(/[. ]/g, "") === "" ? "artifact" : cleaned;
99
+ }
100
+ async function mapResponse(resp, script = "") {
101
+ const errData = await raiseForError(resp);
102
+ const data = errData ?? (await resp.json());
103
+ const requestId = data.request_id ?? "";
104
+ if (data.success === false) {
105
+ const errorMsg = data.error ?? "Script failed";
106
+ const output = data.output ?? [];
107
+ if (errorMsg.includes("SyntaxError")) {
108
+ throw new ScriptSyntaxError(errorMsg, script, requestId, output);
109
+ }
110
+ throw new ScriptRuntimeError(errorMsg, script, requestId, output);
111
+ }
112
+ return {
113
+ value: data.result ?? null,
114
+ output: data.output ?? [],
115
+ requestId,
116
+ success: true,
117
+ error: "",
118
+ durationMs: data.duration_ms ?? 0,
119
+ };
120
+ }
121
+ function sleep(seconds) {
122
+ return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
123
+ }
124
+ /** Parse one SSE event block (lines already split on LF). */
125
+ function parseSseBlock(rawEvent) {
126
+ let eventName = "message";
127
+ const dataLines = [];
128
+ for (const line of rawEvent.split("\n")) {
129
+ if (line.startsWith(":") || line === "") {
130
+ continue;
131
+ }
132
+ if (line.startsWith("event:")) {
133
+ eventName = line.slice("event:".length).trim();
134
+ }
135
+ else if (line.startsWith("data:")) {
136
+ dataLines.push(line.slice("data:".length).trim());
137
+ }
138
+ }
139
+ return dataLines.length > 0 ? { event: eventName, data: dataLines.join("\n") } : null;
140
+ }
141
+ /**
142
+ * Parse a Server-Sent-Events HTTP response body into `{event, data}` pairs.
143
+ *
144
+ * Lines starting with `:` are keepalive comments and are skipped. An event
145
+ * block with no explicit `event:` line defaults to `"message"`, matching
146
+ * the SSE specification. Lines may end in LF, CRLF or CR, as the
147
+ * specification allows; DazScriptServer itself sends LF. An unterminated
148
+ * event at the end of the stream is discarded, as the specification requires.
149
+ *
150
+ * Stopping early (`break`, `return`, or a thrown error) cancels the body, so
151
+ * the connection closes instead of staying open until the server ends it.
152
+ */
153
+ export async function* parseSseStream(response) {
154
+ const body = response.body;
155
+ if (!body) {
156
+ return;
157
+ }
158
+ const reader = body.getReader();
159
+ const decoder = new TextDecoder();
160
+ let buffer = "";
161
+ try {
162
+ for (;;) {
163
+ const { done, value } = await reader.read();
164
+ if (done) {
165
+ buffer += decoder.decode();
166
+ }
167
+ else {
168
+ buffer += decoder.decode(value, { stream: true });
169
+ }
170
+ // Normalize CRLF/CR to LF. Mid-stream a trailing CR is held back: it may
171
+ // be the first half of a CRLF split across chunks. At the end it can't be.
172
+ const heldCr = !done && buffer.endsWith("\r");
173
+ buffer = (heldCr ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, "\n") + (heldCr ? "\r" : "");
174
+ let boundary;
175
+ while ((boundary = buffer.indexOf("\n\n")) !== -1) {
176
+ const parsed = parseSseBlock(buffer.slice(0, boundary));
177
+ buffer = buffer.slice(boundary + 2);
178
+ if (parsed !== null) {
179
+ yield parsed;
180
+ }
181
+ }
182
+ if (done) {
183
+ break;
184
+ }
185
+ }
186
+ }
187
+ finally {
188
+ // No-op if the stream already ended; otherwise closes the connection.
189
+ await reader.cancel().catch(() => { });
190
+ reader.releaseLock();
191
+ }
192
+ }
193
+ /** The final {@link RequestStatus} values; a request in one of these never changes again. */
194
+ export const FINAL_REQUEST_STATUSES = new Set([
195
+ "completed",
196
+ "failed",
197
+ "cancelled",
198
+ "completed_after_cancel_request",
199
+ "completed_after_stale",
200
+ ]);
201
+ /**
202
+ * HTTP client for the DAZ Studio Script Server.
203
+ *
204
+ * Handles authentication, request serialization, and response mapping for
205
+ * all server endpoints. The token is loaded automatically from
206
+ * `~/.daz3d/dazscriptserver_token.txt` when `token` is omitted.
207
+ *
208
+ * Unlike dazpy (which needs separate `DazClient`/`AsyncDazClient` classes
209
+ * for Python's sync/async split), a single `DazClient` covers both cases
210
+ * via `async`/`await`.
211
+ */
212
+ export class DazClient {
213
+ baseUrl;
214
+ token;
215
+ timeoutMs;
216
+ constructor(options = {}) {
217
+ const { host = DEFAULT_HOST, port = DEFAULT_PORT, token = null, timeoutMs = 30_000 } = options;
218
+ this.baseUrl = `http://${host}:${port}`;
219
+ this.token = token !== null ? token : loadToken();
220
+ this.timeoutMs = timeoutMs;
221
+ }
222
+ get headers() {
223
+ return this.token ? { "X-API-Token": this.token } : {};
224
+ }
225
+ /**
226
+ * `fetch` with `timeoutMs` (default: the client's) bounding the whole
227
+ * exchange, body included: the body is read into memory before the timer is
228
+ * cleared, so callers' `resp.json()`/`resp.text()` can't hang afterwards.
229
+ * Pass `stream: true` to get the live body back instead (only
230
+ * time-to-headers is bounded then), for downloads that shouldn't be buffered.
231
+ */
232
+ async fetchWithTimeout(url, init, { timeoutMs = this.timeoutMs, stream = false } = {}) {
233
+ const controller = new AbortController();
234
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
235
+ try {
236
+ const resp = await fetch(url, { ...init, signal: controller.signal });
237
+ if (stream) {
238
+ return resp;
239
+ }
240
+ // These statuses can't carry a body; new Response() throws if given one.
241
+ const body = resp.status === 204 || resp.status === 205 || resp.status === 304 ? null : await resp.arrayBuffer();
242
+ return new Response(body, { status: resp.status, statusText: resp.statusText, headers: resp.headers });
243
+ }
244
+ catch (e) {
245
+ if (e instanceof DOMException && e.name === "AbortError") {
246
+ throw new DazTimeoutError(`Request timed out after ${timeoutMs / 1000}s`);
247
+ }
248
+ const message = e instanceof Error ? e.message : String(e);
249
+ throw new ConnectionError(`Cannot reach DAZ Studio at ${this.baseUrl}: ${message}`);
250
+ }
251
+ finally {
252
+ clearTimeout(timer);
253
+ }
254
+ }
255
+ post(pathname, payload) {
256
+ return this.fetchWithTimeout(`${this.baseUrl}${pathname}`, {
257
+ method: "POST",
258
+ headers: { ...this.headers, "Content-Type": "application/json" },
259
+ body: JSON.stringify(payload),
260
+ });
261
+ }
262
+ get(pathname, params, timeoutMs) {
263
+ const url = new URL(`${this.baseUrl}${pathname}`);
264
+ if (params) {
265
+ for (const [k, v] of Object.entries(params)) {
266
+ url.searchParams.set(k, v);
267
+ }
268
+ }
269
+ return this.fetchWithTimeout(url.toString(), { method: "GET", headers: this.headers }, { timeoutMs });
270
+ }
271
+ async delete_(pathname) {
272
+ try {
273
+ return await this.fetchWithTimeout(`${this.baseUrl}${pathname}`, { method: "DELETE", headers: this.headers });
274
+ }
275
+ catch {
276
+ return null;
277
+ }
278
+ }
279
+ async withBusyRetry(fn, retryOnBusy, maxWait) {
280
+ if (!retryOnBusy) {
281
+ return fn();
282
+ }
283
+ const deadline = Date.now() + maxWait * 1000;
284
+ let backoff = 1.0;
285
+ for (;;) {
286
+ try {
287
+ return await fn();
288
+ }
289
+ catch (e) {
290
+ if (!(e instanceof DazBusyError)) {
291
+ throw e;
292
+ }
293
+ const remainingMs = deadline - Date.now();
294
+ if (remainingMs <= 0) {
295
+ throw e;
296
+ }
297
+ await sleep(Math.min(backoff, remainingMs / 1000));
298
+ backoff = Math.min(backoff + 1.0, 5.0);
299
+ }
300
+ }
301
+ }
302
+ /**
303
+ * Execute a DazScript string synchronously.
304
+ *
305
+ * @param script - DazScript source code to execute.
306
+ * @param args - Optional value passed into the script as `getArguments()[0]`. Must be JSON-serializable.
307
+ */
308
+ async execute(script, args, opts = {}) {
309
+ const { retryOnBusy = false, maxWait = 30.0 } = opts;
310
+ const payload = { script };
311
+ if (args !== undefined) {
312
+ payload.args = args;
313
+ }
314
+ return this.withBusyRetry(async () => mapResponse(await this.post("/execute", payload), script), retryOnBusy, maxWait);
315
+ }
316
+ /**
317
+ * Execute a `.dsa` script file that resides on the DAZ Studio host.
318
+ *
319
+ * @param scriptFile - Absolute path to the `.dsa` file on the server host.
320
+ * @param args - Optional argument passed to the script.
321
+ */
322
+ async executeFile(scriptFile, args, opts = {}) {
323
+ const { retryOnBusy = false, maxWait = 30.0 } = opts;
324
+ const payload = { scriptFile };
325
+ if (args !== undefined) {
326
+ payload.args = args;
327
+ }
328
+ return this.withBusyRetry(async () => mapResponse(await this.post("/execute", payload)), retryOnBusy, maxWait);
329
+ }
330
+ /**
331
+ * Submit a script for asynchronous execution and return immediately.
332
+ *
333
+ * @returns The server-assigned `requestId`. Use it with {@link getRequestStatus}
334
+ * or {@link getRequestResult} to poll for the outcome.
335
+ */
336
+ async executeAsyncSubmit(script, args, opts = {}) {
337
+ const { retryOnBusy = false, maxWait = 30.0 } = opts;
338
+ const payload = { script };
339
+ if (args !== undefined) {
340
+ payload.args = args;
341
+ }
342
+ return this.withBusyRetry(async () => {
343
+ const resp = await this.post("/execute/async", payload);
344
+ const data = (await raiseForError(resp)) ?? (await resp.json());
345
+ return data.request_id ?? "";
346
+ }, retryOnBusy, maxWait);
347
+ }
348
+ /**
349
+ * Submit a host-side `.dsa` file for asynchronous execution.
350
+ *
351
+ * The file is loaded by DAZ Studio when the queued job starts, preserving
352
+ * its filename for `getScriptFileName()` and relative `include()` calls.
353
+ */
354
+ async executeFileAsyncSubmit(scriptFile, args, opts = {}) {
355
+ const { retryOnBusy = false, maxWait = 30.0 } = opts;
356
+ const payload = { scriptFile };
357
+ if (args !== undefined) {
358
+ payload.args = args;
359
+ }
360
+ return this.withBusyRetry(async () => {
361
+ const resp = await this.post("/execute/async", payload);
362
+ const data = (await raiseForError(resp)) ?? (await resp.json());
363
+ return data.request_id ?? "";
364
+ }, retryOnBusy, maxWait);
365
+ }
366
+ /**
367
+ * Submit multiple operations as one async request (one queue slot, one script).
368
+ *
369
+ * @param operations - `{bodyLines, resultExpression}` pairs — same shape as {@link Batch.addOperation}'s arguments.
370
+ * @returns The server-assigned `requestId`. Poll it like any other async
371
+ * request; the result's `result` field is a dict keyed `"_r0"`, `"_r1"`, ... in submission order.
372
+ */
373
+ async executeBatchAsync(operations, args) {
374
+ const pairs = operations.map((op) => [op.bodyLines, op.resultExpression]);
375
+ const script = buildOperationsScript(pairs);
376
+ return this.executeAsyncSubmit(script, args);
377
+ }
378
+ /**
379
+ * Return the current status of an async request.
380
+ *
381
+ * @returns A dict with at least a `status` key: a {@link RequestStatus}, or
382
+ * `"not_found"`. `cancel_requested` and `stale` are not final: a running
383
+ * script can't be interrupted, so once it returns the status changes to its
384
+ * real outcome.
385
+ */
386
+ async getRequestStatus(requestId) {
387
+ const resp = await this.get(`/requests/${requestId}/status`);
388
+ if (resp.status === 404) {
389
+ return { status: "not_found" };
390
+ }
391
+ return (await raiseForError(resp)) ?? (await resp.json());
392
+ }
393
+ /**
394
+ * Fetch the result of a completed async request.
395
+ *
396
+ * @param wait - If `true`, the server long-polls until the request completes or `waitTimeout` is reached.
397
+ * @param waitTimeout - Maximum seconds the server should wait (only relevant when `wait` is `true`).
398
+ */
399
+ async getRequestResult(requestId, wait = false, waitTimeout = 30) {
400
+ const params = {};
401
+ if (wait) {
402
+ params.wait = "true";
403
+ params.timeout = String(waitTimeout);
404
+ }
405
+ const resp = await this.get(`/requests/${requestId}/result`, Object.keys(params).length ? params : undefined, wait ? (waitTimeout + 10) * 1000 : undefined);
406
+ if (resp.status === 404) {
407
+ return { status: "not_found" };
408
+ }
409
+ return (await raiseForError(resp)) ?? (await resp.json());
410
+ }
411
+ /**
412
+ * List all tracked async requests (script and render) with their status.
413
+ *
414
+ * @param status - Optional filter: any {@link RequestStatus} (e.g. `"running"`, `"cancel_requested"`).
415
+ */
416
+ async listRequests(status) {
417
+ const resp = await this.get("/requests", status ? { status } : undefined);
418
+ if (resp.status === 401 || resp.status === 403) {
419
+ throw await authenticationError(resp);
420
+ }
421
+ return (await resp.json());
422
+ }
423
+ /**
424
+ * Cancel a script or render request and return the server's response.
425
+ *
426
+ * Render requests (`rnd-` IDs) go to `POST /render/{id}/cancel`; others to
427
+ * `DELETE /requests/{id}`. A queued request comes back `cancelled`; a
428
+ * running one comes back `cancel_requested` (or `stale`), so poll it for
429
+ * the real outcome.
430
+ *
431
+ * @throws {DazError} If the server rejects the cancel (e.g. unknown request).
432
+ */
433
+ async cancelRequestDetail(requestId) {
434
+ const resp = requestId.startsWith("rnd-")
435
+ ? await this.post(`/render/${requestId}/cancel`, {})
436
+ : await this.delete_(`/requests/${requestId}`);
437
+ if (resp === null) {
438
+ throw new ConnectionError(`Could not reach the server to cancel ${requestId}`);
439
+ }
440
+ const errData = await raiseForError(resp);
441
+ if (errData !== undefined) {
442
+ throw new DazError(errData.error ?? `HTTP ${resp.status}`);
443
+ }
444
+ return (await resp.json());
445
+ }
446
+ /**
447
+ * Cancel a queued or running async request.
448
+ *
449
+ * @returns `true` if the server accepted the cancel, `false` otherwise. A
450
+ * queued request is cancelled at once; a running one only becomes
451
+ * `cancel_requested` (scripts can't be interrupted), so poll the request
452
+ * for its real outcome.
453
+ */
454
+ async cancelRequest(requestId) {
455
+ const resp = await this.delete_(`/requests/${requestId}`);
456
+ return resp !== null && resp.status === 200;
457
+ }
458
+ // ── Render ──────────────────────────────────────────────────────────────
459
+ /** Submit a render job and return immediately. */
460
+ async renderSubmit(outputPath, opts = {}) {
461
+ const { figure, morphs, figures, width, height, camera, engine, iraySamples, resetMorphs, retryOnBusy = false, maxWait = 30.0 } = opts;
462
+ const payload = { output_path: outputPath };
463
+ if (width && height) {
464
+ payload.width = width;
465
+ payload.height = height;
466
+ }
467
+ if (camera)
468
+ payload.camera = camera;
469
+ if (engine)
470
+ payload.engine = engine;
471
+ if (iraySamples)
472
+ payload.iray_samples = iraySamples;
473
+ if (resetMorphs)
474
+ payload.reset_morphs = true;
475
+ if (figures !== undefined) {
476
+ payload.figures = figures;
477
+ }
478
+ else if (figure) {
479
+ payload.figure = figure;
480
+ if (morphs)
481
+ payload.morphs = morphs;
482
+ }
483
+ return this.withBusyRetry(async () => {
484
+ const resp = await this.post("/render", payload);
485
+ return (await raiseForError(resp)) ?? (await resp.json());
486
+ }, retryOnBusy, maxWait);
487
+ }
488
+ /** Submit a batch render job (multiple variants sharing optional defaults) and return immediately. */
489
+ async renderBatchSubmit(variants, base, opts = {}) {
490
+ const { retryOnBusy = false, maxWait = 30.0 } = opts;
491
+ const payload = { variants };
492
+ if (base)
493
+ payload.base = base;
494
+ return this.withBusyRetry(async () => {
495
+ const resp = await this.post("/render/batch", payload);
496
+ return (await raiseForError(resp)) ?? (await resp.json());
497
+ }, retryOnBusy, maxWait);
498
+ }
499
+ /** Submit an animation render job spanning a frame range and return immediately. */
500
+ async renderAnimationSubmit(outputPath, startFrame, endFrame, opts = {}) {
501
+ const { framePadding = 4, width, height, camera, engine, retryOnBusy = false, maxWait = 30.0 } = opts;
502
+ const payload = {
503
+ output_path: outputPath,
504
+ start_frame: startFrame,
505
+ end_frame: endFrame,
506
+ frame_padding: framePadding,
507
+ };
508
+ if (width && height) {
509
+ payload.width = width;
510
+ payload.height = height;
511
+ }
512
+ if (camera)
513
+ payload.camera = camera;
514
+ if (engine)
515
+ payload.engine = engine;
516
+ return this.withBusyRetry(async () => {
517
+ const resp = await this.post("/render/animation", payload);
518
+ return (await raiseForError(resp)) ?? (await resp.json());
519
+ }, retryOnBusy, maxWait);
520
+ }
521
+ /** Cancel a queued or running render job. */
522
+ async cancelRender(requestId) {
523
+ try {
524
+ const resp = await this.fetchWithTimeout(`${this.baseUrl}/render/${requestId}/cancel`, {
525
+ method: "POST",
526
+ headers: this.headers,
527
+ });
528
+ return resp.status === 200;
529
+ }
530
+ catch {
531
+ return false;
532
+ }
533
+ }
534
+ /**
535
+ * Open an SSE stream. The timeout and the caller's signal stay attached to
536
+ * the returned body, so they bound reading the stream, not just connecting.
537
+ */
538
+ async openStream(url, opts) {
539
+ const { timeoutMs, signal } = opts;
540
+ const controller = new AbortController();
541
+ const onAbort = () => controller.abort(signal?.reason);
542
+ let timer;
543
+ // Runs once the stream is finished with, however it ends, so neither the
544
+ // timer nor a listener on a long-lived caller signal outlives it.
545
+ const cleanup = () => {
546
+ clearTimeout(timer);
547
+ signal?.removeEventListener("abort", onAbort);
548
+ };
549
+ if (signal) {
550
+ if (signal.aborted) {
551
+ controller.abort(signal.reason);
552
+ }
553
+ else {
554
+ signal.addEventListener("abort", onAbort, { once: true });
555
+ }
556
+ }
557
+ if (timeoutMs !== undefined) {
558
+ timer = setTimeout(() => controller.abort(new DazTimeoutError(`Stream timed out after ${timeoutMs / 1000}s`)), timeoutMs);
559
+ // Don't keep the process alive just to abort a stream nobody is reading.
560
+ timer.unref?.();
561
+ }
562
+ let resp;
563
+ try {
564
+ resp = await fetch(url, { headers: this.headers, signal: controller.signal });
565
+ }
566
+ catch (e) {
567
+ cleanup();
568
+ if (e instanceof DazTimeoutError || (signal?.aborted && e === signal.reason)) {
569
+ throw e;
570
+ }
571
+ const message = e instanceof Error ? e.message : String(e);
572
+ throw new ConnectionError(`Cannot reach DAZ Studio at ${this.baseUrl}: ${message}`);
573
+ }
574
+ if (resp.status === 401 || resp.status === 403) {
575
+ cleanup();
576
+ throw await authenticationError(resp);
577
+ }
578
+ if (resp.status !== 200 || !resp.body) {
579
+ cleanup();
580
+ await resp.body?.cancel();
581
+ return null;
582
+ }
583
+ const reader = resp.body.getReader();
584
+ const body = new ReadableStream({
585
+ async pull(c) {
586
+ try {
587
+ const { done, value } = await reader.read();
588
+ if (done) {
589
+ cleanup();
590
+ c.close();
591
+ }
592
+ else {
593
+ c.enqueue(value);
594
+ }
595
+ }
596
+ catch (e) {
597
+ cleanup();
598
+ c.error(e);
599
+ }
600
+ },
601
+ async cancel(reason) {
602
+ cleanup();
603
+ await reader.cancel(reason);
604
+ },
605
+ });
606
+ return new Response(body, { status: resp.status, statusText: resp.statusText, headers: resp.headers });
607
+ }
608
+ /**
609
+ * Open the SSE progress stream for a render request.
610
+ *
611
+ * @returns The raw streaming `Response` on success, or `null` if the server
612
+ * answers with any other non-auth status (e.g. 404: no such render, or a
613
+ * server without the endpoint), so callers can fall back to polling. Pass
614
+ * the result to {@link parseSseStream} to consume it, and let the body
615
+ * drain or cancel the reader.
616
+ * @throws {AuthenticationError} On HTTP 401/403.
617
+ * @throws {ConnectionError} If the server can't be reached.
618
+ * @throws {DazTimeoutError} If `opts.timeoutMs` elapses (also from reads of the body).
619
+ */
620
+ async streamRenderProgress(requestId, opts = {}) {
621
+ return this.openStream(`${this.baseUrl}/render/${requestId}/progress`, opts);
622
+ }
623
+ /**
624
+ * Open the SSE stream for general scene-change events (`GET /scene/events`).
625
+ *
626
+ * @param categories - Optional subset of event categories to subscribe to
627
+ * (`"node"`, `"skeleton"`, `"light"`, `"camera"`, `"selection"`, `"scene"`,
628
+ * `"time"`, `"render"`). Omit to subscribe to all categories.
629
+ * @param opts - Stream lifetime / abort signal. With no `timeoutMs` the
630
+ * stream stays open until the caller stops reading — the server sends a
631
+ * keepalive comment every 15 seconds.
632
+ * @returns The raw streaming `Response`, or `null` on a non-auth, non-200 status.
633
+ * @throws {AuthenticationError} On HTTP 401/403.
634
+ * @throws {ConnectionError} If the server can't be reached.
635
+ * @throws {DazTimeoutError} If `opts.timeoutMs` elapses (also from reads of the body).
636
+ */
637
+ async streamSceneEvents(categories, opts = {}) {
638
+ const url = new URL(`${this.baseUrl}/scene/events`);
639
+ if (categories && categories.length > 0) {
640
+ url.searchParams.set("filter", categories.join(","));
641
+ }
642
+ return this.openStream(url.toString(), opts);
643
+ }
644
+ // ── Server health ───────────────────────────────────────────────────────
645
+ /** Return the server status dict from `GET /status`. */
646
+ async status() {
647
+ const resp = await this.get("/status");
648
+ if (resp.status === 401 || resp.status === 403) {
649
+ throw await authenticationError(resp);
650
+ }
651
+ return (await resp.json());
652
+ }
653
+ /**
654
+ * Check the plugin's version (from `GET /status`) against
655
+ * {@link MIN_SERVER_VERSION}. daz-ts never runs this on its own, so call it
656
+ * once after connecting if you want to warn users about an old plugin.
657
+ * Throws only what {@link status} throws: an incompatible plugin comes back
658
+ * as `compatible: false` with upgrade advice in `message`.
659
+ */
660
+ async checkServerVersion() {
661
+ return evaluateServerVersion(this.baseUrl, await this.status());
662
+ }
663
+ /** Return the health check dict from `GET /health`. */
664
+ async health() {
665
+ const resp = await this.get("/health");
666
+ if (resp.status === 401 || resp.status === 403) {
667
+ throw await authenticationError(resp);
668
+ }
669
+ return (await resp.json());
670
+ }
671
+ /** Return the metrics dict from `GET /metrics`. */
672
+ async metrics() {
673
+ const resp = await this.get("/metrics");
674
+ if (resp.status === 401 || resp.status === 403) {
675
+ throw await authenticationError(resp);
676
+ }
677
+ return (await resp.json());
678
+ }
679
+ /**
680
+ * Return the server's capabilities document from `GET /capabilities`:
681
+ * versions, routes, feature flags, current limits and the render engines
682
+ * registered right now. Servers that predate the endpoint answer 404, which
683
+ * throws a `DazError`; 401/403 throw `AuthenticationError`, and 503 before
684
+ * the server has a snapshot throws `StudioBusyError`.
685
+ */
686
+ /**
687
+ * List the files an async job declared (`GET /artifacts/{id}`): outputs
688
+ * from its `reportFile` plus the image(s) a render job wrote, each with
689
+ * size, content type and availability. Use with {@link downloadArtifact}
690
+ * when the client can't see DAZ Studio's filesystem.
691
+ */
692
+ async listArtifacts(requestId) {
693
+ const resp = await this.get(`/artifacts/${encodeURIComponent(requestId)}`);
694
+ await throwArtifactError(resp);
695
+ return (await resp.json());
696
+ }
697
+ async downloadArtifact(requestId, artifactId, destOrOpts, maybeOpts) {
698
+ const dest = typeof destOrOpts === "string" ? destOrOpts : undefined;
699
+ const opts = (typeof destOrOpts === "string" ? maybeOpts : destOrOpts) ?? {};
700
+ const headers = { ...this.headers };
701
+ if (opts.range) {
702
+ const [start, end] = opts.range;
703
+ if (!Number.isInteger(start) || start < 0 || (end !== undefined && (!Number.isInteger(end) || end < start))) {
704
+ throw new RangeError(`invalid range [${start}, ${end}]`);
705
+ }
706
+ headers.Range = `bytes=${start}-${end ?? ""}`;
707
+ }
708
+ const url = `${this.baseUrl}/artifacts/${encodeURIComponent(requestId)}/${encodeURIComponent(String(artifactId))}`;
709
+ // Artifacts can be large: stream the body rather than buffering it, so
710
+ // the client timeout covers only time-to-headers here.
711
+ const resp = await this.fetchWithTimeout(url, { method: "GET", headers }, { stream: true });
712
+ await throwArtifactError(resp);
713
+ if (dest === undefined) {
714
+ return Buffer.from(await resp.arrayBuffer());
715
+ }
716
+ if (!resp.body) {
717
+ await fs.promises.writeFile(dest, Buffer.alloc(0));
718
+ }
719
+ else {
720
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
721
+ await pipeline(Readable.fromWeb(resp.body), fs.createWriteStream(dest));
722
+ }
723
+ return dest;
724
+ }
725
+ /**
726
+ * Download every available artifact of a job into `destDir`, named
727
+ * `<artifact_id>_<filename>` so equal base names can't collide. Returns the
728
+ * written paths in manifest order.
729
+ */
730
+ async downloadArtifacts(requestId, destDir) {
731
+ await fs.promises.mkdir(destDir, { recursive: true });
732
+ const written = [];
733
+ for (const entry of (await this.listArtifacts(requestId)).artifacts ?? []) {
734
+ if (!entry.available)
735
+ continue;
736
+ const aid = String(entry.artifact_id);
737
+ const name = safeArtifactFilename(entry.filename || "artifact");
738
+ written.push(await this.downloadArtifact(requestId, aid, path.join(destDir, `${aid}_${name}`)));
739
+ }
740
+ return written;
741
+ }
742
+ async capabilities() {
743
+ const resp = await this.get("/capabilities");
744
+ const errData = await raiseForError(resp);
745
+ if (errData) {
746
+ const msg = errData.error ?? `HTTP ${resp.status}`;
747
+ throw new DazError(`capabilities failed (${resp.status}): ${msg}`);
748
+ }
749
+ return (await resp.json());
750
+ }
751
+ /**
752
+ * Save a copy of the scene to `path` without changing the scene's current
753
+ * file or dirty state (like "Save a Copy As..."). See dazpy's
754
+ * `DazScene.save_copy` for the copy-vs-serialize tradeoff this makes
755
+ * server-side.
756
+ */
757
+ async sceneSaveCopy(path) {
758
+ const resp = await this.post("/scene/save-copy", { path });
759
+ if (resp.status === 401 || resp.status === 403) {
760
+ throw await authenticationError(resp);
761
+ }
762
+ if (!resp.ok) {
763
+ const body = (await resp.json().catch(() => ({})));
764
+ const msg = body.error ?? body.detail ?? `HTTP ${resp.status}`;
765
+ throw new DazError(`sceneSaveCopy failed (${resp.status}): ${msg}`);
766
+ }
767
+ return (await resp.json());
768
+ }
769
+ }