@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.
package/dist/upload.js ADDED
@@ -0,0 +1,203 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { CliError } from "./errors.js";
5
+ import { retryConnectionFailures, sleep } from "./network.js";
6
+ // The Seedance workspace's upload path: /api/s3/sts/generation-batch signs
7
+ // direct uploads, then /api/assets/recent/register-batch files them under
8
+ // the user's Recent assets, as lib/client/generation-input-upload.ts does.
9
+ const SIGN_PATH = "/api/s3/sts/generation-batch";
10
+ const REGISTER_PATH = "/api/assets/recent/register-batch";
11
+ const PURPOSE = "seedance25";
12
+ const PREFIX_BY_KIND = {
13
+ image: "/seedance-images",
14
+ video: "/seedance-videos",
15
+ audio: "/seedance-audio",
16
+ };
17
+ const MAX_FILES_PER_BATCH = 50;
18
+ const MAX_CONCURRENT_PUTS = 4;
19
+ const PUT_TIMEOUT_MS = 10 * 60 * 1000;
20
+ // The website retries Recent registration the same way
21
+ // (lib/client/generation-input-upload.ts): a short pause, then once more.
22
+ const REGISTRATION_RETRY_DELAYS_MS = [100, 500];
23
+ const TRANSIENT_REGISTRATION_CODES = new Set([
24
+ "OBJECT_NOT_FOUND",
25
+ "VERIFY_FAILED",
26
+ ]);
27
+ // A file uploaded for a quote is reused by the create that follows, so it is
28
+ // not uploaded twice. Kept well inside the time the website keeps an
29
+ // unreferenced upload.
30
+ const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
31
+ function safeUploadKey(fileName) {
32
+ const extension = path
33
+ .extname(fileName)
34
+ .slice(1)
35
+ .toLowerCase()
36
+ .replace(/[^a-z0-9]/g, "")
37
+ .slice(0, 10);
38
+ return extension ? `${randomUUID()}.${extension}` : randomUUID();
39
+ }
40
+ async function mapWithConcurrency(values, concurrency, operation) {
41
+ const results = new Array(values.length);
42
+ let cursor = 0;
43
+ await Promise.all(Array.from({ length: Math.min(concurrency, values.length) }, async () => {
44
+ while (cursor < values.length) {
45
+ const index = cursor++;
46
+ results[index] = await operation(values[index], index);
47
+ }
48
+ }));
49
+ return results;
50
+ }
51
+ function isRetryableRequestError(error) {
52
+ if (error instanceof CliError) {
53
+ return error.code === "rate_limited" || /^http_5\d\d$/.test(error.code);
54
+ }
55
+ // fetch rejects with a TypeError on network failure, and aborts on timeout.
56
+ return (error instanceof TypeError || error?.name === "TimeoutError");
57
+ }
58
+ export class Uploader {
59
+ api;
60
+ files;
61
+ cacheName;
62
+ log;
63
+ fetchImpl;
64
+ sleep;
65
+ constructor(api, files, cacheName, log, options = {}) {
66
+ this.api = api;
67
+ this.files = files;
68
+ this.cacheName = cacheName;
69
+ this.log = log;
70
+ this.fetchImpl = options.fetchImpl ?? fetch;
71
+ this.sleep = options.sleep ?? sleep;
72
+ }
73
+ /** Public https URLs for the files, in order, uploading what is not cached. */
74
+ async upload(media) {
75
+ if (media.length === 0)
76
+ return [];
77
+ const contents = await Promise.all(media.map((file) => readFile(file.path)));
78
+ const hashes = contents.map((bytes) => createHash("sha256").update(bytes).digest("hex"));
79
+ const now = Date.now();
80
+ const cache = await this.readCache(now);
81
+ const urls = hashes.map((hash) => cache[hash]?.url);
82
+ const pending = media
83
+ .map((file, index) => ({ file, index }))
84
+ .filter(({ index }) => !urls[index])
85
+ // The same file twice in one request is uploaded once.
86
+ .filter(({ index }, position, all) => all.findIndex((entry) => hashes[entry.index] === hashes[index]) ===
87
+ position);
88
+ for (let start = 0; start < pending.length; start += MAX_FILES_PER_BATCH) {
89
+ const batch = pending.slice(start, start + MAX_FILES_PER_BATCH);
90
+ this.log(`Uploading ${batch.map(({ file }) => file.fileName).join(", ")}…`);
91
+ const uploaded = await this.uploadBatch(batch.map(({ file }) => file), batch.map(({ index }) => contents[index]));
92
+ batch.forEach(({ index }, position) => {
93
+ cache[hashes[index]] = { url: uploaded[position], uploadedAt: now };
94
+ });
95
+ }
96
+ if (pending.length > 0) {
97
+ // Only spares a re-upload later; the URLs are good either way.
98
+ await this.files.writeJson(this.cacheName, cache).catch(() => undefined);
99
+ }
100
+ return hashes.map((hash) => cache[hash].url);
101
+ }
102
+ async readCache(now) {
103
+ const saved = (await this.files.readJson(this.cacheName)) ?? {};
104
+ return Object.fromEntries(Object.entries(saved).filter(([, entry]) => typeof entry?.url === "string" &&
105
+ now - entry.uploadedAt < CACHE_TTL_MS));
106
+ }
107
+ async uploadBatch(media, contents) {
108
+ const signed = await this.api.request({
109
+ method: "POST",
110
+ path: SIGN_PATH,
111
+ body: {
112
+ purpose: PURPOSE,
113
+ files: media.map((file) => ({
114
+ key: safeUploadKey(file.fileName),
115
+ fileName: file.fileName,
116
+ fileType: file.mimeType,
117
+ fileSize: file.size,
118
+ prefix: PREFIX_BY_KIND[file.kind],
119
+ })),
120
+ },
121
+ });
122
+ const signatures = signed.data?.files;
123
+ if (!Array.isArray(signatures) || signatures.length !== media.length) {
124
+ throw new CliError("upload_failed", "The upload could not be prepared.");
125
+ }
126
+ await mapWithConcurrency(media, MAX_CONCURRENT_PUTS, async (file, index) => {
127
+ const signature = signatures[index];
128
+ // A repeated PUT writes the same object again, so it is safe to retry.
129
+ const response = await retryConnectionFailures(() => this.fetchImpl(signature.putUrl, {
130
+ method: "PUT",
131
+ body: contents[index],
132
+ headers: { "content-type": signature.contentType },
133
+ signal: AbortSignal.timeout(PUT_TIMEOUT_MS),
134
+ }), this.sleep);
135
+ if (!response.ok) {
136
+ throw new CliError("upload_failed", `Uploading ${file.fileName} failed (HTTP ${response.status}).`, "Retry the command.");
137
+ }
138
+ });
139
+ await this.register(media, signatures);
140
+ return signatures.map((signature) => signature.completedUrl);
141
+ }
142
+ /**
143
+ * Files the uploads under Recent assets on the website. Best effort, like
144
+ * the website's own registration: the URLs already work for generation,
145
+ * so a file that cannot be registered is reported, not treated as an error.
146
+ */
147
+ async register(media, signatures) {
148
+ let pending = media.map((file, index) => ({
149
+ file,
150
+ signature: signatures[index],
151
+ }));
152
+ for (let attempt = 0;; attempt++) {
153
+ let retry;
154
+ try {
155
+ const result = await this.api.request({
156
+ method: "POST",
157
+ path: REGISTER_PATH,
158
+ body: {
159
+ purpose: PURPOSE,
160
+ items: pending.map(({ file, signature }) => ({
161
+ key: signature.key,
162
+ fileName: file.fileName,
163
+ fileType: signature.contentType,
164
+ fileSize: file.size,
165
+ ...(file.width && file.height
166
+ ? { width: file.width, height: file.height }
167
+ : {}),
168
+ ...(file.durationSeconds !== undefined
169
+ ? { durationMs: Math.round(file.durationSeconds * 1000) }
170
+ : {}),
171
+ })),
172
+ },
173
+ });
174
+ const failed = result.data?.failed ?? [];
175
+ const failedWith = (key, transient) => failed.some((failure) => failure.key === key &&
176
+ TRANSIENT_REGISTRATION_CODES.has(failure.code) === transient);
177
+ this.reportUnregistered(pending.filter(({ signature }) => failedWith(signature.key, false)));
178
+ retry = pending.filter(({ signature }) => failedWith(signature.key, true));
179
+ }
180
+ catch (error) {
181
+ if (!isRetryableRequestError(error)) {
182
+ this.reportUnregistered(pending);
183
+ return;
184
+ }
185
+ retry = pending;
186
+ }
187
+ if (retry.length === 0)
188
+ return;
189
+ const delay = REGISTRATION_RETRY_DELAYS_MS[attempt];
190
+ if (delay === undefined) {
191
+ this.reportUnregistered(retry);
192
+ return;
193
+ }
194
+ await this.sleep(delay);
195
+ pending = retry;
196
+ }
197
+ }
198
+ reportUnregistered(entries) {
199
+ if (entries.length === 0)
200
+ return;
201
+ this.log(`Note: ${entries.map(({ file }) => file.fileName).join(", ")} uploaded but could not be added to Recent assets. Generation is not affected.`);
202
+ }
203
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@seedance3/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Generate Seedance videos and AI images with your Seedance 3.0 AI account from the terminal",
5
+ "homepage": "https://www.seedances3.com/mcp",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "type": "module",
8
+ "bin": {
9
+ "seedance3": "dist/cli.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "os": [
19
+ "darwin",
20
+ "linux"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.build.json",
24
+ "typecheck": "tsc -p tsconfig.json --noEmit",
25
+ "test": "node --import tsx --test test/*.test.ts",
26
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^22.20.0",
30
+ "tsx": "^4.20.6",
31
+ "typescript": "^5.9.3"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }