@clipwright/cli 0.86.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/wait.js ADDED
@@ -0,0 +1,120 @@
1
+ import { closeSync, openSync, rmSync, renameSync, writeFileSync } from "node:fs";
2
+ import { FAILED_STATE, isTerminal, RUN_WAIT_MAX_SECONDS } from "@clipwright/core";
3
+ import { ClipwrightApiError } from "@clipwright/sdk";
4
+ import { Option } from "commander";
5
+ import { commandLine, fail, note } from "./output.js";
6
+ export const READ_COMMAND = {
7
+ run: "get-run", film: "get-film-run", trend: "get-trend-search", analysis: "get-reference-analysis", creator: "get-creator-profile",
8
+ };
9
+ export const DEFAULT_WAIT_SECONDS = 600;
10
+ const POLL_MS = 5_000;
11
+ export function withWaitOptions(command, output) {
12
+ command
13
+ .option("--wait", "wait until it succeeds or fails, then print it")
14
+ .addOption(new Option("--timeout <seconds>", `how long --wait waits (default ${DEFAULT_WAIT_SECONDS}); the work goes on after it`)
15
+ .argParser(parseSeconds));
16
+ if (output)
17
+ command.option("--output <path>", "wait, then save the delivered file here");
18
+ return command;
19
+ }
20
+ function parseSeconds(raw) {
21
+ const parsed = Number.parseInt(raw, 10);
22
+ if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(parsed)) {
23
+ fail({ code: "invalid_value", message: `--timeout expects a whole number of seconds, 1 or more, got ${raw}`,
24
+ fix: ["Pass --timeout a whole number of seconds, for example --timeout 900."] });
25
+ }
26
+ return parsed;
27
+ }
28
+ function reader(sdk, kind, id, waitSeconds) {
29
+ switch (kind) {
30
+ case "run": return sdk.getRun(id, { wait_seconds: waitSeconds });
31
+ case "film": return sdk.getFilmRun(id);
32
+ case "trend": return sdk.getTrendSearch(id, { wait_seconds: waitSeconds });
33
+ case "analysis": return sdk.getReferenceAnalysis(id, { wait_seconds: waitSeconds });
34
+ case "creator": return sdk.getCreatorProfile(id, { wait_seconds: waitSeconds });
35
+ }
36
+ }
37
+ const DEADLINE = Symbol("deadline");
38
+ async function readBefore(read, ms) {
39
+ let timer;
40
+ const expired = new Promise((resolve) => { timer = setTimeout(() => resolve(DEADLINE), ms); });
41
+ try {
42
+ return await Promise.race([read, expired]);
43
+ }
44
+ finally {
45
+ clearTimeout(timer);
46
+ }
47
+ }
48
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
49
+ export async function waitUntilDone(sdk, kind, id, first, timeoutSeconds = DEFAULT_WAIT_SECONDS) {
50
+ const deadline = Date.now() + timeoutSeconds * 1000;
51
+ let current = first;
52
+ let seen = current.state;
53
+ let quick = false;
54
+ while (!isTerminal(current.state)) {
55
+ const left = deadline - Date.now();
56
+ if (left <= 0) {
57
+ const resume = commandLine([READ_COMMAND[kind], id, "--wait"]);
58
+ fail({ code: "wait_timeout", retryable: true, resume, details: { id, state: current.state },
59
+ message: `${id} is still ${current.state} after ${timeoutSeconds} s; it goes on without this command`,
60
+ fix: [`Run ${resume} to keep waiting; nothing was cancelled and nothing more is charged.`] });
61
+ }
62
+ const serverWait = Math.min(RUN_WAIT_MAX_SECONDS, Math.floor(left / 1000));
63
+ if (kind === "film" || serverWait < 1 || quick)
64
+ await sleep(Math.min(POLL_MS, left));
65
+ const asked = Date.now();
66
+ try {
67
+ const answer = await readBefore(reader(sdk, kind, id, Math.max(serverWait, 0)), Math.max(deadline - Date.now(), 0));
68
+ if (answer === DEADLINE)
69
+ continue;
70
+ current = answer;
71
+ quick = Date.now() - asked < 1_000;
72
+ }
73
+ catch (error) {
74
+ if (!(error instanceof ClipwrightApiError) || !error.retryable)
75
+ throw error;
76
+ await sleep(Math.min(Math.max(POLL_MS, (error.retryAfterSeconds ?? 0) * 1000), Math.max(deadline - Date.now(), 0)));
77
+ continue;
78
+ }
79
+ if (current.state !== seen) {
80
+ seen = current.state;
81
+ note(`state: ${current.state}`);
82
+ }
83
+ }
84
+ return current;
85
+ }
86
+ export function failIfFailed(id, read, again) {
87
+ if (read.state !== FAILED_STATE)
88
+ return;
89
+ const reason = typeof read.error === "string" ? read.error : read.error !== null && typeof read.error === "object" &&
90
+ "message" in read.error ? String(read.error.message) : "it failed";
91
+ fail({ code: "run_failed", message: `${id} failed: ${reason}`, run: read,
92
+ details: { id, credits_charged: read.credits_charged ?? null }, fix: [again] });
93
+ }
94
+ export async function saveFile(url, path, resume) {
95
+ const part = `${path}.part-${process.pid}`;
96
+ let created = false;
97
+ try {
98
+ const response = await fetch(url, { signal: AbortSignal.timeout(300_000) });
99
+ if (!response.ok)
100
+ throw new Error(`HTTP ${response.status}`);
101
+ const bytes = new Uint8Array(await response.arrayBuffer());
102
+ const fd = openSync(part, "wx");
103
+ created = true;
104
+ try {
105
+ writeFileSync(fd, bytes);
106
+ }
107
+ finally {
108
+ closeSync(fd);
109
+ }
110
+ renameSync(part, path);
111
+ }
112
+ catch (error) {
113
+ if (created)
114
+ rmSync(part, { force: true });
115
+ fail({ code: "download_failed", retryable: true, resume,
116
+ message: `the file could not be saved to ${path}: ${error instanceof Error ? error.message : String(error)}`,
117
+ fix: [`Run ${resume} to read a fresh link and save it again; the delivered file is kept for 7 days.`] });
118
+ }
119
+ note(`saved ${path}`);
120
+ }
package/dist/workflows.js CHANGED
@@ -24,7 +24,8 @@ function readFile(path) {
24
24
  return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, used)));
25
25
  }
26
26
  catch (cause) {
27
- throw new WorkflowFileError(`${path}: cannot read workflow JSON. ${cause instanceof Error ? cause.message : String(cause)} Nothing was sent.`, cause);
27
+ const reason = cause instanceof SyntaxError ? 'It is not JSON.' : cause instanceof Error ? cause.message : String(cause);
28
+ throw new WorkflowFileError(`${path}: cannot read workflow JSON. ${reason} Nothing was sent.`, cause);
28
29
  }
29
30
  finally {
30
31
  if (fd !== undefined)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipwright/cli",
3
- "version": "0.86.0",
3
+ "version": "0.87.0",
4
4
  "description": "Command-line client for the Clipwright UGC video API",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,8 +32,8 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "commander": "^15.0.0",
35
- "@clipwright/core": "0.86.0",
36
- "@clipwright/sdk": "0.86.0"
35
+ "@clipwright/core": "0.87.0",
36
+ "@clipwright/sdk": "0.87.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/node": "^26.1.1"