@seedance3/cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,237 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { open } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { assertMediaAcceptable } from "./checks.js";
5
+ import { CliError } from "./errors.js";
6
+ import { inspectMediaFile } from "./media.js";
7
+ import { retryConnectionFailures, sleep } from "./network.js";
8
+ import { findLocalFiles, fromApiTier, fromApiTierMessage, isSupportedModel, toApiTier, withUploadedUrls, } from "./requests.js";
9
+ export const TERMINAL_STATUSES = new Set(["completed", "failed"]);
10
+ const REQUEST_ID_PATTERN = /^[\w-]{8,120}$/;
11
+ const CREATE_RETRY_DELAYS_MS = [2_000, 6_000];
12
+ const DEFAULT_POLL_MS = 5_000;
13
+ const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
14
+ export function newRequestId() {
15
+ return `cli-${randomUUID()}`;
16
+ }
17
+ function isRetryable(error) {
18
+ if (error instanceof CliError) {
19
+ return (error.code === "service_busy" ||
20
+ error.code === "internal_error" ||
21
+ /^http_5\d\d$/.test(error.code) ||
22
+ // The first attempt with this key is still running on the server.
23
+ (error.code === "idempotency_conflict" &&
24
+ error.message.includes("in progress")));
25
+ }
26
+ // fetch rejects with a TypeError on network failure, and aborts on timeout.
27
+ return (error instanceof TypeError || error?.name === "TimeoutError");
28
+ }
29
+ /**
30
+ * A submit response without the account's remaining credits, which some
31
+ * image routes include. An AI app reading create's output would recite it
32
+ * after every generation; `seedance3 account` shows it when asked.
33
+ */
34
+ function withoutBalance(task) {
35
+ const rest = { ...task };
36
+ delete rest.remaining_credits;
37
+ return rest;
38
+ }
39
+ function withTierInError(error) {
40
+ if (error instanceof CliError) {
41
+ throw new CliError(error.code, fromApiTierMessage(error.message), error.hint, error.details);
42
+ }
43
+ throw error;
44
+ }
45
+ export class SeedanceService {
46
+ api;
47
+ uploader;
48
+ options;
49
+ modelsPromise;
50
+ constructor(api, uploader, options = {}) {
51
+ this.api = api;
52
+ this.uploader = uploader;
53
+ this.options = options;
54
+ }
55
+ sleep(ms) {
56
+ return (this.options.sleep ?? sleep)(ms);
57
+ }
58
+ balance() {
59
+ return this.api.request({
60
+ method: "GET",
61
+ path: "/api/v1/balance",
62
+ });
63
+ }
64
+ /** The public API's models that the CLI can quote and generate with. */
65
+ models() {
66
+ this.modelsPromise ??= this.api
67
+ .request({ method: "GET", path: "/api/v1/models" })
68
+ .then((result) => (result.data ?? []).filter((model) => isSupportedModel(model.id)));
69
+ return this.modelsPromise;
70
+ }
71
+ async endpointFor(model) {
72
+ const entry = (await this.models()).find((item) => item.id === model);
73
+ if (!entry) {
74
+ throw new CliError("invalid_request", `Model "${model}" is not available.`, "See `seedance3 models`.");
75
+ }
76
+ return entry.endpoint;
77
+ }
78
+ /**
79
+ * The request body the API will receive: local files checked, uploaded
80
+ * (or reused from a recent upload) and replaced by their URLs.
81
+ */
82
+ async prepare(request) {
83
+ // Checked before anything is uploaded: a refused tier uploads nothing.
84
+ let body = toApiTier(request.model, request.body);
85
+ const refs = findLocalFiles(request);
86
+ if (refs.length > 0) {
87
+ const media = await Promise.all(refs.map((ref) => inspectMediaFile(ref.path)));
88
+ assertMediaAcceptable(request.model, media);
89
+ body = withUploadedUrls(body, refs, await this.uploader.upload(media));
90
+ }
91
+ return body;
92
+ }
93
+ async quote(request) {
94
+ const body = await this.prepare(request);
95
+ return this.quotePrepared(request.model, body);
96
+ }
97
+ async quotePrepared(model, body) {
98
+ const quote = await this.api
99
+ .request({
100
+ method: "POST",
101
+ path: "/api/v1/quote",
102
+ body: { model, ...body },
103
+ slow: true,
104
+ })
105
+ .catch(withTierInError);
106
+ return fromApiTier(quote);
107
+ }
108
+ /**
109
+ * Submits a generation. With `maxCredits`, the price is checked first and
110
+ * nothing is submitted if it is higher. The request ID makes retries safe:
111
+ * the server answers a repeat with the first task and charges once.
112
+ */
113
+ async create(request, options) {
114
+ if (!REQUEST_ID_PATTERN.test(options.requestId)) {
115
+ throw new CliError("invalid_request", "The request ID must be 8–120 letters, digits, _ or -.");
116
+ }
117
+ const body = await this.prepare(request);
118
+ if (options.maxCredits !== undefined) {
119
+ const quote = await this.quotePrepared(request.model, body);
120
+ if (quote.credits > options.maxCredits) {
121
+ throw new CliError("price_above_limit", `This generation costs ${quote.credits} credits, more than --max-credits ${options.maxCredits}. Nothing was submitted or charged.`, "Show the user the new price and run again only if they accept it.", { credits: quote.credits });
122
+ }
123
+ }
124
+ const endpoint = await this.endpointFor(request.model);
125
+ for (let attempt = 0;; attempt++) {
126
+ try {
127
+ const task = await this.api.request({
128
+ method: "POST",
129
+ path: endpoint,
130
+ body,
131
+ idempotencyKey: options.requestId,
132
+ slow: true,
133
+ });
134
+ return withoutBalance(fromApiTier(task));
135
+ }
136
+ catch (error) {
137
+ const delay = CREATE_RETRY_DELAYS_MS[attempt];
138
+ if (delay === undefined || !isRetryable(error))
139
+ withTierInError(error);
140
+ await this.sleep(delay);
141
+ }
142
+ }
143
+ }
144
+ async task(id) {
145
+ const task = await this.api.request({
146
+ method: "GET",
147
+ path: `/api/v1/tasks/${encodeURIComponent(id)}`,
148
+ });
149
+ return fromApiTier(task);
150
+ }
151
+ async tasks(limit) {
152
+ const query = limit ? `?limit=${limit}` : "";
153
+ const result = await this.api.request({
154
+ method: "GET",
155
+ path: `/api/v1/tasks${query}`,
156
+ });
157
+ return {
158
+ ...result,
159
+ data: (result.data ?? []).map((task) => fromApiTier(task)),
160
+ };
161
+ }
162
+ /** Polls until the task finishes. A timeout leaves the task running. */
163
+ async wait(id, options) {
164
+ const deadline = Date.now() + options.timeoutSeconds * 1000;
165
+ for (;;) {
166
+ const task = await this.task(id);
167
+ options.onPoll?.(task);
168
+ if (TERMINAL_STATUSES.has(task.status))
169
+ return task;
170
+ if (Date.now() >= deadline) {
171
+ throw new CliError("wait_timeout", `Task ${id} is still ${task.status}. It keeps running.`, `Check again with \`seedance3 wait ${id}\`.`, { task });
172
+ }
173
+ await this.sleep(this.options.pollIntervalMs ?? DEFAULT_POLL_MS);
174
+ }
175
+ }
176
+ /**
177
+ * Saves a finished task's result files. Never overwrites: each target must
178
+ * not exist yet. Several results get -1, -2… before the extension.
179
+ */
180
+ async download(id, output) {
181
+ const task = await this.task(id);
182
+ if (task.status !== "completed") {
183
+ throw new CliError("task_not_completed", `Task ${id} is ${task.status}; only a completed task can be downloaded.`);
184
+ }
185
+ const urls = task.result_urls ?? [];
186
+ if (urls.length === 0) {
187
+ throw new CliError("no_results", `Task ${id} has no result files.`);
188
+ }
189
+ const fetchImpl = this.options.fetchImpl ?? fetch;
190
+ const files = [];
191
+ for (const [index, url] of urls.entries()) {
192
+ const target = downloadTarget(id, url, output, index, urls.length);
193
+ // The body is read inside the retry: a connection that drops halfway
194
+ // through a large video starts the file again.
195
+ const bytes = await retryConnectionFailures(async () => {
196
+ const response = await fetchImpl(url, {
197
+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
198
+ });
199
+ if (!response.ok) {
200
+ throw new CliError("download_failed", `Downloading ${url} failed (HTTP ${response.status}).`);
201
+ }
202
+ return Buffer.from(await response.arrayBuffer());
203
+ }, (ms) => this.sleep(ms));
204
+ let handle;
205
+ try {
206
+ handle = await open(target, "wx", 0o644);
207
+ }
208
+ catch (error) {
209
+ if (error.code === "EEXIST") {
210
+ throw new CliError("file_exists", `${target} already exists; it was not overwritten.`, "Choose a new path with --output.");
211
+ }
212
+ throw error;
213
+ }
214
+ try {
215
+ await handle.writeFile(bytes);
216
+ }
217
+ finally {
218
+ await handle.close();
219
+ }
220
+ files.push(path.resolve(target));
221
+ }
222
+ return { task, files };
223
+ }
224
+ }
225
+ export function downloadTarget(id, url, output, index, count) {
226
+ const urlExtension = path.extname(new URL(url).pathname) || ".bin";
227
+ if (!output) {
228
+ return `${id}${count > 1 ? `-${index + 1}` : ""}${urlExtension}`;
229
+ }
230
+ if (count === 1)
231
+ return output;
232
+ const extension = path.extname(output) || urlExtension;
233
+ const stem = path.extname(output)
234
+ ? output.slice(0, -extension.length)
235
+ : output;
236
+ return `${stem}-${index + 1}${extension}`;
237
+ }
@@ -0,0 +1,320 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { CLI_VERSION, siteKey } from "./config.js";
3
+ import { selectVault, } from "./credentials.js";
4
+ import { CliError, SIGN_IN_HINT } from "./errors.js";
5
+ import { authorizationCodeFromPastedUrl, buildAuthorizationUrl, createPkce, discoverAuthServer, exchangeAuthorizationCode, listenForAuthorizationCode, portOf, redirectUriFor, refreshCredentials, registerClient, revokeToken, } from "./oauth.js";
6
+ // Refresh a little before expiry so a token does not lapse mid-request.
7
+ const REFRESH_MARGIN_MS = 60_000;
8
+ // The redirect port registered by a first sign-in without a browser; a
9
+ // later browser sign-in tries it and registers a new port if it is taken.
10
+ const DEFAULT_REDIRECT_PORT = 53682;
11
+ // A sign-in without a browser that waits for its pasted address; the code
12
+ // in that address expires much sooner anyway.
13
+ const PENDING_LOGIN_TTL_MS = 10 * 60 * 1000;
14
+ const DISCONNECT_PATH = "/api/v1/connection/disconnect";
15
+ const BALANCE_PATH = "/api/v1/balance";
16
+ const WEBSITE_CHECK_TIMEOUT_MS = 30_000;
17
+ function signInRequired(message = "You are not signed in.") {
18
+ return new CliError("unauthorized", message, SIGN_IN_HINT);
19
+ }
20
+ /**
21
+ * The CLI's sign-in with one website. The OAuth client registration (not a
22
+ * secret) is kept in a plain config file and reused on every login, so an
23
+ * installation registers once; the tokens live in the credential vault.
24
+ */
25
+ export class Session {
26
+ origin;
27
+ files;
28
+ fetchImpl;
29
+ key;
30
+ vaultPromise;
31
+ constructor(origin, files, fetchImpl = fetch) {
32
+ this.origin = origin;
33
+ this.files = files;
34
+ this.fetchImpl = fetchImpl;
35
+ this.key = siteKey(origin);
36
+ }
37
+ get clientFile() {
38
+ return `client-${this.key}.json`;
39
+ }
40
+ get pendingFile() {
41
+ return `pending-login-${this.key}.json`;
42
+ }
43
+ vault(choice) {
44
+ if (choice) {
45
+ this.vaultPromise = selectVault({
46
+ files: this.files,
47
+ key: this.key,
48
+ choice,
49
+ });
50
+ }
51
+ this.vaultPromise ??= selectVault({ files: this.files, key: this.key });
52
+ return this.vaultPromise;
53
+ }
54
+ async savedClient() {
55
+ const saved = await this.files.readJson(this.clientFile);
56
+ return saved?.metadata?.token_endpoint && saved.registration?.clientId
57
+ ? saved
58
+ : null;
59
+ }
60
+ async credentialStoreKind() {
61
+ return (await this.vault()).kind;
62
+ }
63
+ async isSignedIn() {
64
+ return Boolean(await (await this.vault()).read());
65
+ }
66
+ /** A valid access token, refreshed first when it is about to expire. */
67
+ async accessToken() {
68
+ const credentials = await (await this.vault()).read();
69
+ if (!credentials)
70
+ throw signInRequired();
71
+ if (credentials.expiresAt === undefined ||
72
+ credentials.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
73
+ return credentials.accessToken;
74
+ }
75
+ return this.refresh(credentials.accessToken);
76
+ }
77
+ /**
78
+ * Replaces `staleToken` with a fresh one. Under a lock, and re-reading the
79
+ * vault inside it: if another process refreshed meanwhile, its token is
80
+ * used instead of spending the (single-use) refresh token twice.
81
+ */
82
+ async refresh(staleToken) {
83
+ const saved = await this.savedClient();
84
+ if (!saved)
85
+ throw signInRequired();
86
+ return this.files.withLock(`refresh-${this.key}`, async () => {
87
+ const vault = await this.vault();
88
+ const current = await vault.read();
89
+ if (!current)
90
+ throw signInRequired();
91
+ if (current.accessToken !== staleToken)
92
+ return current.accessToken;
93
+ const refreshed = await refreshCredentials({
94
+ tokenEndpoint: saved.metadata.token_endpoint,
95
+ clientId: saved.registration.clientId,
96
+ credentials: current,
97
+ fetchImpl: this.fetchImpl,
98
+ });
99
+ if (!refreshed) {
100
+ await vault.remove();
101
+ throw signInRequired("Your sign-in has expired or was revoked.");
102
+ }
103
+ await vault.write(refreshed);
104
+ return refreshed.accessToken;
105
+ });
106
+ }
107
+ async login(options) {
108
+ const vault = await this.vault(options.credentialStore);
109
+ if (options.redirectUrl !== undefined) {
110
+ await vault.write(await this.finishPendingLogin(options.redirectUrl));
111
+ return { status: "signed_in" };
112
+ }
113
+ await this.forgetRefusedRegistration();
114
+ const metadata = await discoverAuthServer(this.origin, this.fetchImpl);
115
+ const saved = await this.savedClient();
116
+ const reusable = saved && saved.registration.issuer === metadata.issuer
117
+ ? saved.registration
118
+ : null;
119
+ const credentials = options.noBrowser
120
+ ? await this.loginWithoutBrowser(metadata, reusable, options)
121
+ : await this.browserLogin(metadata, reusable, options);
122
+ if (!credentials)
123
+ return { status: "pending" };
124
+ await vault.write(credentials);
125
+ return { status: "signed_in" };
126
+ }
127
+ async register(metadata, redirectUri) {
128
+ const registration = await registerClient({
129
+ metadata,
130
+ redirectUri,
131
+ fetchImpl: this.fetchImpl,
132
+ });
133
+ await this.files.writeJson(this.clientFile, {
134
+ metadata,
135
+ registration,
136
+ });
137
+ return registration;
138
+ }
139
+ async browserLogin(metadata, reusable, options) {
140
+ const state = randomBytes(16).toString("base64url");
141
+ // The registered redirect URI names a port; reuse it when it is free,
142
+ // otherwise take any free port and register that one.
143
+ let listener = null;
144
+ let client = reusable;
145
+ if (client) {
146
+ listener = await listenForAuthorizationCode({
147
+ port: portOf(client.redirectUri),
148
+ state,
149
+ }).catch(() => null);
150
+ }
151
+ if (!listener) {
152
+ listener = await listenForAuthorizationCode({ port: 0, state });
153
+ client = await this.register(metadata, redirectUriFor(listener.port));
154
+ }
155
+ else {
156
+ await this.files.writeJson(this.clientFile, {
157
+ metadata,
158
+ registration: client,
159
+ });
160
+ }
161
+ try {
162
+ const { verifier, challenge } = createPkce();
163
+ const url = buildAuthorizationUrl({
164
+ metadata,
165
+ client: client,
166
+ state,
167
+ challenge,
168
+ });
169
+ const opened = await options.openBrowser(url);
170
+ options.log(opened
171
+ ? "Opened your browser to sign in. If it did not open, visit:"
172
+ : "Open this URL in your browser to sign in:");
173
+ options.log(url);
174
+ const code = await listener.code;
175
+ return await exchangeAuthorizationCode({
176
+ metadata,
177
+ client: client,
178
+ code,
179
+ verifier,
180
+ fetchImpl: this.fetchImpl,
181
+ });
182
+ }
183
+ finally {
184
+ listener.close();
185
+ }
186
+ }
187
+ /**
188
+ * Sign-in when the browser runs on another device (a remote server): the
189
+ * user opens the link anywhere, allows access, and pastes back the address
190
+ * the browser then ends on, which the local callback could not receive.
191
+ * Without anyone to type (an agent runs the CLI), the attempt is saved and
192
+ * finished by `auth login --redirect-url <address>`.
193
+ */
194
+ async loginWithoutBrowser(metadata, reusable, options) {
195
+ const client = reusable ??
196
+ (await this.register(metadata, redirectUriFor(DEFAULT_REDIRECT_PORT)));
197
+ const state = randomBytes(16).toString("base64url");
198
+ const { verifier, challenge } = createPkce();
199
+ options.log("Open this link in a browser on any device, sign in and allow access:");
200
+ options.log(buildAuthorizationUrl({ metadata, client, state, challenge }));
201
+ options.log("The browser then shows a page that cannot be reached. Copy the whole address from its address bar.");
202
+ // Saved before the prompt: an agent whose terminal looks interactive may
203
+ // be stopped while it waits, and can still finish with --redirect-url.
204
+ await this.files.writeJson(this.pendingFile, {
205
+ clientId: client.clientId,
206
+ redirectUri: client.redirectUri,
207
+ state,
208
+ verifier,
209
+ createdAt: Date.now(),
210
+ });
211
+ options.log("Then finish signing in with: seedance3 auth login --redirect-url '<the address>'");
212
+ // Asked only when someone can type in this terminal.
213
+ const pasted = await options.readLine("Or paste the address here: ");
214
+ return pasted === null ? null : this.finishPendingLogin(pasted);
215
+ }
216
+ async finishPendingLogin(redirectUrl) {
217
+ const pending = await this.files.readJson(this.pendingFile);
218
+ const saved = await this.savedClient();
219
+ if (!pending ||
220
+ !saved ||
221
+ saved.registration.clientId !== pending.clientId ||
222
+ Date.now() - pending.createdAt > PENDING_LOGIN_TTL_MS) {
223
+ throw new CliError("auth_failed", "No sign-in is waiting for this address, or it has expired.", "Start again with `seedance3 auth login --no-browser`.");
224
+ }
225
+ const code = authorizationCodeFromPastedUrl(redirectUrl, pending);
226
+ // The code can be exchanged once; a failed attempt starts over.
227
+ await this.files.remove(this.pendingFile);
228
+ return exchangeAuthorizationCode({
229
+ metadata: saved.metadata,
230
+ client: saved.registration,
231
+ code,
232
+ verifier: pending.verifier,
233
+ fetchImpl: this.fetchImpl,
234
+ });
235
+ }
236
+ /**
237
+ * Signs this computer out. The website disconnects the connection first,
238
+ * so every token issued to it stops working at once: Clerk cannot revoke a
239
+ * JWT access token, which would otherwise keep working until it expires.
240
+ * The tokens are then revoked with the sign-in server too (best effort)
241
+ * and forgotten locally. Returns whether the website confirmed.
242
+ */
243
+ async logout() {
244
+ await this.files.remove(this.pendingFile);
245
+ const vault = await this.vault();
246
+ if (!(await vault.read())) {
247
+ return { wasSignedIn: false, disconnected: false };
248
+ }
249
+ // Refreshed first if it is about to expire; null if it cannot be.
250
+ const accessToken = await this.accessToken().catch(() => null);
251
+ const disconnected = accessToken
252
+ ? await this.disconnect(accessToken)
253
+ : false;
254
+ const credentials = await vault.read();
255
+ const saved = await this.savedClient();
256
+ const endpoint = saved?.metadata.revocation_endpoint;
257
+ if (credentials && saved && endpoint) {
258
+ // The refresh token ends the grant; an opaque access token can be
259
+ // revoked as well, a JWT one cannot (the disconnect covers it).
260
+ const tokens = [credentials.accessToken, credentials.refreshToken].filter((token) => Boolean(token));
261
+ await Promise.all(tokens.map((token) => revokeToken({
262
+ revocationEndpoint: endpoint,
263
+ clientId: saved.registration.clientId,
264
+ token,
265
+ fetchImpl: this.fetchImpl,
266
+ })));
267
+ }
268
+ await vault.remove();
269
+ // A disconnected connection refuses this client registration for good,
270
+ // so the next sign-in registers a new one and starts a new connection.
271
+ if (disconnected)
272
+ await this.files.remove(this.clientFile);
273
+ return { wasSignedIn: true, disconnected };
274
+ }
275
+ /** True when the website disconnected the connection, or the token no longer works. */
276
+ async disconnect(accessToken) {
277
+ const response = await this.askWebsite("POST", DISCONNECT_PATH, accessToken);
278
+ // 401: the token is refused already (disconnected on the website).
279
+ return response ? response.ok || response.status === 401 : false;
280
+ }
281
+ /**
282
+ * Before a sign-in reuses the saved client registration, checks that the
283
+ * website still accepts this computer's connection. Disconnected on the
284
+ * website, it refuses that registration for good, so it is forgotten and
285
+ * the sign-in registers a new one. Kept when the website accepts the
286
+ * token or cannot be reached.
287
+ */
288
+ async forgetRefusedRegistration() {
289
+ if (!(await this.savedClient()))
290
+ return;
291
+ if (!(await (await this.vault()).read()))
292
+ return;
293
+ // Refreshed first if it is about to expire; null if it cannot be.
294
+ const accessToken = await this.accessToken().catch(() => null);
295
+ if (!accessToken)
296
+ return;
297
+ const response = await this.askWebsite("GET", BALANCE_PATH, accessToken);
298
+ if (response?.status === 401)
299
+ await this.files.remove(this.clientFile);
300
+ }
301
+ /** A call to the website with this token; null when it cannot be reached. */
302
+ async askWebsite(method, path, accessToken) {
303
+ try {
304
+ return await this.fetchImpl(new URL(path, this.origin), {
305
+ method,
306
+ headers: {
307
+ accept: "application/json",
308
+ authorization: `Bearer ${accessToken}`,
309
+ "user-agent": `seedance3-cli/${CLI_VERSION}`,
310
+ },
311
+ // Never follow a redirect: it would carry the bearer token elsewhere.
312
+ redirect: "error",
313
+ signal: AbortSignal.timeout(WEBSITE_CHECK_TIMEOUT_MS),
314
+ });
315
+ }
316
+ catch {
317
+ return null;
318
+ }
319
+ }
320
+ }
@@ -0,0 +1,49 @@
1
+ import { CLI_VERSION, PACKAGE_NAME } from "./config.js";
2
+ const CHECK_FILE = "update-check.json";
3
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
4
+ const CHECK_TIMEOUT_MS = 1_500;
5
+ /** True when `candidate` is a newer x.y.z release than `current`. */
6
+ export function isNewerVersion(candidate, current) {
7
+ const parse = (version) => version
8
+ .split("-")[0]
9
+ .split(".")
10
+ .map((part) => Number(part) || 0);
11
+ const a = parse(candidate);
12
+ const b = parse(current);
13
+ for (let index = 0; index < 3; index++) {
14
+ const diff = (a[index] ?? 0) - (b[index] ?? 0);
15
+ if (diff !== 0)
16
+ return diff > 0;
17
+ }
18
+ return false;
19
+ }
20
+ /**
21
+ * At most once a day, asks the npm registry for the latest version and
22
+ * returns a one-line notice when this one is older. Never throws and never
23
+ * waits more than a moment; SEEDANCE3_NO_UPDATE_CHECK turns it off.
24
+ */
25
+ export async function checkForUpdate(params) {
26
+ if ((params.env ?? process.env).SEEDANCE3_NO_UPDATE_CHECK)
27
+ return null;
28
+ try {
29
+ const now = Date.now();
30
+ let record = await params.files.readJson(CHECK_FILE);
31
+ if (!record || now - record.checkedAt > CHECK_INTERVAL_MS) {
32
+ const response = await (params.fetchImpl ?? fetch)(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, { signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) });
33
+ const latest = response.ok
34
+ ? (await response.json()).version
35
+ : undefined;
36
+ record = {
37
+ checkedAt: now,
38
+ ...(typeof latest === "string" ? { latest } : {}),
39
+ };
40
+ await params.files.writeJson(CHECK_FILE, record);
41
+ }
42
+ return record.latest && isNewerVersion(record.latest, CLI_VERSION)
43
+ ? `Seedance3 CLI ${record.latest} is available (you have ${CLI_VERSION}). Update: npm install -g ${PACKAGE_NAME}`
44
+ : null;
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }