post-upload 0.0.0-stage → 1.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.
- package/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +525 -2
- package/dist/cli.js +297 -0
- package/dist/index.d.mts +660 -0
- package/dist/index.d.ts +660 -0
- package/dist/index.js +1034 -0
- package/dist/index.mjs +984 -0
- package/package.json +96 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,984 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { readFileSync, createWriteStream } from "fs";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import { open, stat, mkdtemp, rm } from "fs/promises";
|
|
5
|
+
import { tmpdir } from "os";
|
|
6
|
+
import { basename, extname, join } from "path";
|
|
7
|
+
|
|
8
|
+
// src/errors.ts
|
|
9
|
+
var PostUploadError = class extends Error {
|
|
10
|
+
constructor(message, status, code = null, body = null) {
|
|
11
|
+
super(message);
|
|
12
|
+
/** Seconds from the response's `Retry-After` header (e.g. on 429), if any. */
|
|
13
|
+
this.retryAfter = null;
|
|
14
|
+
this.name = "PostUploadError";
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.body = body;
|
|
18
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var IndReelForgeError = PostUploadError;
|
|
22
|
+
var InReelForgeError = PostUploadError;
|
|
23
|
+
|
|
24
|
+
// src/version.ts
|
|
25
|
+
var VERSION = "1.2.0";
|
|
26
|
+
|
|
27
|
+
// src/types.ts
|
|
28
|
+
var PLATFORMS = [
|
|
29
|
+
"instagram",
|
|
30
|
+
"youtube",
|
|
31
|
+
"tiktok",
|
|
32
|
+
"facebook",
|
|
33
|
+
"x",
|
|
34
|
+
"linkedin",
|
|
35
|
+
"threads",
|
|
36
|
+
"pinterest",
|
|
37
|
+
"reddit",
|
|
38
|
+
"bluesky",
|
|
39
|
+
"google_business",
|
|
40
|
+
"discord",
|
|
41
|
+
"telegram",
|
|
42
|
+
"slack",
|
|
43
|
+
"mastodon",
|
|
44
|
+
"wordpress",
|
|
45
|
+
"devto",
|
|
46
|
+
"hashnode",
|
|
47
|
+
"lemmy",
|
|
48
|
+
"nostr",
|
|
49
|
+
"whop",
|
|
50
|
+
"listmonk"
|
|
51
|
+
];
|
|
52
|
+
var CREDENTIAL_PLATFORMS = {
|
|
53
|
+
discord: ["webhook_url"],
|
|
54
|
+
telegram: ["bot_token", "chat_id"],
|
|
55
|
+
slack: ["webhook_url"],
|
|
56
|
+
mastodon: ["instance_url", "access_token"],
|
|
57
|
+
wordpress: ["site_url", "username", "app_password"],
|
|
58
|
+
devto: ["api_key"],
|
|
59
|
+
hashnode: ["access_token", "publication_id"],
|
|
60
|
+
lemmy: ["instance_url", "username", "password", "community"],
|
|
61
|
+
nostr: ["nsec"],
|
|
62
|
+
whop: ["api_key"],
|
|
63
|
+
listmonk: ["base_url", "api_user", "api_token", "list_ids"]
|
|
64
|
+
};
|
|
65
|
+
var CHUNKED_THRESHOLD_BYTES = 95 * 1024 * 1024;
|
|
66
|
+
var MAX_VIDEO_BYTES = 500 * 1024 * 1024;
|
|
67
|
+
|
|
68
|
+
// src/client.ts
|
|
69
|
+
var DEFAULT_BASE_URL = "https://api.post-upload.com";
|
|
70
|
+
var MIN_PART_TIMEOUT_MS = 3e5;
|
|
71
|
+
var DEFAULT_MAX_RETRIES = 5;
|
|
72
|
+
var MAX_PHOTOS = 10;
|
|
73
|
+
var VIDEO_MIME = {
|
|
74
|
+
".mp4": "video/mp4",
|
|
75
|
+
".m4v": "video/mp4",
|
|
76
|
+
".mov": "video/quicktime",
|
|
77
|
+
".avi": "video/x-msvideo",
|
|
78
|
+
".webm": "video/webm",
|
|
79
|
+
".mkv": "video/x-matroska"
|
|
80
|
+
};
|
|
81
|
+
function guessVideoMime(filename) {
|
|
82
|
+
return VIDEO_MIME[extname(filename).toLowerCase()] || "video/mp4";
|
|
83
|
+
}
|
|
84
|
+
function sleep(ms) {
|
|
85
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
86
|
+
}
|
|
87
|
+
function isBytes(v) {
|
|
88
|
+
return v instanceof Uint8Array;
|
|
89
|
+
}
|
|
90
|
+
function isStreamLike(v) {
|
|
91
|
+
return !!v && typeof v === "object" && typeof v[Symbol.asyncIterator] === "function";
|
|
92
|
+
}
|
|
93
|
+
async function fileReader(path) {
|
|
94
|
+
const size = (await stat(path)).size;
|
|
95
|
+
const handle = await open(path, "r");
|
|
96
|
+
return {
|
|
97
|
+
size,
|
|
98
|
+
async read(index, chunkSize) {
|
|
99
|
+
const start = index * chunkSize;
|
|
100
|
+
const length = Math.max(0, Math.min(chunkSize, size - start));
|
|
101
|
+
const buf = Buffer.alloc(length);
|
|
102
|
+
let off = 0;
|
|
103
|
+
while (off < length) {
|
|
104
|
+
const { bytesRead } = await handle.read(buf, off, length - off, start + off);
|
|
105
|
+
if (bytesRead === 0) throw new Error(`Unexpected end of file reading ${path}`);
|
|
106
|
+
off += bytesRead;
|
|
107
|
+
}
|
|
108
|
+
return buf;
|
|
109
|
+
},
|
|
110
|
+
close: () => handle.close()
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function bufferReader(bytes) {
|
|
114
|
+
return {
|
|
115
|
+
size: bytes.byteLength,
|
|
116
|
+
async read(index, chunkSize) {
|
|
117
|
+
const start = index * chunkSize;
|
|
118
|
+
return bytes.subarray(start, Math.min(start + chunkSize, bytes.byteLength));
|
|
119
|
+
},
|
|
120
|
+
close: async () => {
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function streamReader(stream, size) {
|
|
125
|
+
const it = stream[Symbol.asyncIterator]();
|
|
126
|
+
let pending = [];
|
|
127
|
+
let pendingBytes = 0;
|
|
128
|
+
let next = 0;
|
|
129
|
+
return {
|
|
130
|
+
size,
|
|
131
|
+
async read(index, chunkSize) {
|
|
132
|
+
if (index !== next) throw new Error("Stream parts must be read in order");
|
|
133
|
+
next++;
|
|
134
|
+
const want = Math.min(chunkSize, size - index * chunkSize);
|
|
135
|
+
while (pendingBytes < want) {
|
|
136
|
+
const r = await it.next();
|
|
137
|
+
if (r.done) break;
|
|
138
|
+
const c = typeof r.value === "string" ? Buffer.from(r.value) : r.value;
|
|
139
|
+
pending.push(c);
|
|
140
|
+
pendingBytes += c.byteLength;
|
|
141
|
+
}
|
|
142
|
+
if (pendingBytes < want) {
|
|
143
|
+
throw new TypeError(`The stream ended after ${index * chunkSize + pendingBytes} bytes, but size is ${size}`);
|
|
144
|
+
}
|
|
145
|
+
const all = Buffer.concat(pending);
|
|
146
|
+
const part = all.subarray(0, want);
|
|
147
|
+
const rest = all.subarray(want);
|
|
148
|
+
pending = rest.byteLength ? [rest] : [];
|
|
149
|
+
pendingBytes = rest.byteLength;
|
|
150
|
+
return part;
|
|
151
|
+
},
|
|
152
|
+
close: async () => {
|
|
153
|
+
if (typeof it.return === "function") await it.return().catch(() => void 0);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
async function spoolToTempFile(stream) {
|
|
158
|
+
const dir = await mkdtemp(join(tmpdir(), "post-upload-"));
|
|
159
|
+
const path = join(dir, "upload.bin");
|
|
160
|
+
const cleanup = () => rm(dir, { recursive: true, force: true });
|
|
161
|
+
try {
|
|
162
|
+
const out = createWriteStream(path);
|
|
163
|
+
const done = new Promise((resolve, reject) => {
|
|
164
|
+
out.on("error", reject);
|
|
165
|
+
out.on("finish", () => resolve());
|
|
166
|
+
});
|
|
167
|
+
for await (const chunk of stream) {
|
|
168
|
+
if (!out.write(chunk)) await new Promise((r) => out.once("drain", r));
|
|
169
|
+
}
|
|
170
|
+
out.end();
|
|
171
|
+
await done;
|
|
172
|
+
return { path, cleanup };
|
|
173
|
+
} catch (err) {
|
|
174
|
+
await cleanup();
|
|
175
|
+
throw err;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function collect(stream) {
|
|
179
|
+
const parts = [];
|
|
180
|
+
for await (const c of stream) parts.push(typeof c === "string" ? Buffer.from(c) : c);
|
|
181
|
+
return Buffer.concat(parts);
|
|
182
|
+
}
|
|
183
|
+
function qs(query) {
|
|
184
|
+
if (!query) return "";
|
|
185
|
+
const params = new URLSearchParams();
|
|
186
|
+
for (const [k, v] of Object.entries(query)) {
|
|
187
|
+
if (v !== void 0 && v !== null && v !== "") params.append(k, String(v));
|
|
188
|
+
}
|
|
189
|
+
const s = params.toString();
|
|
190
|
+
return s ? `?${s}` : "";
|
|
191
|
+
}
|
|
192
|
+
function seg(value) {
|
|
193
|
+
return encodeURIComponent(String(value));
|
|
194
|
+
}
|
|
195
|
+
function requireArg(value, name) {
|
|
196
|
+
if (value === void 0 || value === null || value === "") {
|
|
197
|
+
throw new TypeError(`${name} is required`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async function fileBlob(path) {
|
|
201
|
+
const openAsBlob2 = fs.openAsBlob;
|
|
202
|
+
if (typeof openAsBlob2 === "function") return openAsBlob2(path);
|
|
203
|
+
return new Blob([readFileSync(path)]);
|
|
204
|
+
}
|
|
205
|
+
function appendOption(form, key, value) {
|
|
206
|
+
if (value === void 0 || value === null) return;
|
|
207
|
+
if (Array.isArray(value)) {
|
|
208
|
+
for (const v of value) form.append(key, String(v));
|
|
209
|
+
} else if (typeof value === "object") {
|
|
210
|
+
form.append(key, JSON.stringify(value));
|
|
211
|
+
} else {
|
|
212
|
+
form.append(key, String(value));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
var PostUpload = class {
|
|
216
|
+
/**
|
|
217
|
+
* @param config Options object, or just the API key (`new PostUpload('key')`,
|
|
218
|
+
* optionally followed by the other options).
|
|
219
|
+
*/
|
|
220
|
+
constructor(config, options = {}) {
|
|
221
|
+
if (typeof config === "string") config = { ...options, apiKey: config };
|
|
222
|
+
if (!config || !config.apiKey) throw new Error("API key is required");
|
|
223
|
+
this.apiKey = config.apiKey;
|
|
224
|
+
this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
225
|
+
this.timeout = config.timeout || 12e4;
|
|
226
|
+
const f = config.fetch || globalThis.fetch;
|
|
227
|
+
if (typeof f !== "function") {
|
|
228
|
+
throw new Error("No fetch implementation available. Use Node.js >= 18 or pass `fetch` in the config.");
|
|
229
|
+
}
|
|
230
|
+
this.fetchImpl = f;
|
|
231
|
+
this.extraHeaders = config.headers || {};
|
|
232
|
+
this.retryBaseDelayMs = config.retryBaseDelayMs ?? 1e3;
|
|
233
|
+
}
|
|
234
|
+
// ── Core request ──────────────────────────────────────────────────────────
|
|
235
|
+
async request(path, opts = {}) {
|
|
236
|
+
const controller = new AbortController();
|
|
237
|
+
const timeout = opts.timeout ?? this.timeout;
|
|
238
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
239
|
+
const headers = {
|
|
240
|
+
"User-Agent": `post-upload-node/${VERSION}`,
|
|
241
|
+
Accept: "application/json",
|
|
242
|
+
...this.extraHeaders,
|
|
243
|
+
Authorization: `Apikey ${this.apiKey}`,
|
|
244
|
+
...opts.headers
|
|
245
|
+
};
|
|
246
|
+
let body;
|
|
247
|
+
if (opts.form) {
|
|
248
|
+
body = opts.form;
|
|
249
|
+
} else if (opts.raw) {
|
|
250
|
+
headers["Content-Type"] = "application/octet-stream";
|
|
251
|
+
body = opts.raw;
|
|
252
|
+
} else if (opts.json !== void 0) {
|
|
253
|
+
headers["Content-Type"] = "application/json";
|
|
254
|
+
body = JSON.stringify(opts.json);
|
|
255
|
+
}
|
|
256
|
+
let res;
|
|
257
|
+
try {
|
|
258
|
+
res = await this.fetchImpl(`${this.baseUrl}${path}${qs(opts.query)}`, {
|
|
259
|
+
method: opts.method || "GET",
|
|
260
|
+
headers,
|
|
261
|
+
body,
|
|
262
|
+
signal: controller.signal
|
|
263
|
+
});
|
|
264
|
+
} catch (err) {
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
if (err?.name === "AbortError") {
|
|
267
|
+
throw new PostUploadError(`Request timed out after ${timeout} ms`, 408, "TIMEOUT");
|
|
268
|
+
}
|
|
269
|
+
throw new PostUploadError(
|
|
270
|
+
`Connection failed: ${err?.message || String(err)}`,
|
|
271
|
+
0,
|
|
272
|
+
"NETWORK_ERROR"
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
const text = await res.text();
|
|
277
|
+
let parsed = text;
|
|
278
|
+
if (text) {
|
|
279
|
+
try {
|
|
280
|
+
parsed = JSON.parse(text);
|
|
281
|
+
} catch {
|
|
282
|
+
}
|
|
283
|
+
} else {
|
|
284
|
+
parsed = {};
|
|
285
|
+
}
|
|
286
|
+
if (!res.ok) {
|
|
287
|
+
const obj = parsed && typeof parsed === "object" ? parsed : null;
|
|
288
|
+
const message = obj && (obj.error_description || obj.error || obj.message) || (typeof parsed === "string" && parsed.trim() ? parsed.trim().slice(0, 300) : `HTTP ${res.status}`);
|
|
289
|
+
const code = obj && (obj.error_code || obj.code) || null;
|
|
290
|
+
const error = new PostUploadError(String(message), res.status, code ? String(code) : null, obj ?? parsed);
|
|
291
|
+
const retryAfterRaw = res.headers.get("retry-after");
|
|
292
|
+
const retryAfter = Number(retryAfterRaw);
|
|
293
|
+
if (retryAfterRaw !== null && retryAfterRaw.trim() !== "" && Number.isFinite(retryAfter) && retryAfter >= 0) {
|
|
294
|
+
error.retryAfter = retryAfter;
|
|
295
|
+
}
|
|
296
|
+
throw error;
|
|
297
|
+
}
|
|
298
|
+
return parsed;
|
|
299
|
+
} catch (err) {
|
|
300
|
+
if (err instanceof PostUploadError) throw err;
|
|
301
|
+
if (err?.name === "AbortError") {
|
|
302
|
+
throw new PostUploadError(`Request timed out after ${timeout} ms`, 408, "TIMEOUT");
|
|
303
|
+
}
|
|
304
|
+
throw err;
|
|
305
|
+
} finally {
|
|
306
|
+
clearTimeout(timer);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
buildForm(options) {
|
|
310
|
+
requireArg(options.user, "user");
|
|
311
|
+
const form = new FormData();
|
|
312
|
+
form.append("user", options.user);
|
|
313
|
+
for (const p of options.platforms || []) form.append("platform[]", p);
|
|
314
|
+
if (options.title) form.append("title", options.title);
|
|
315
|
+
if (options.description) form.append("description", options.description);
|
|
316
|
+
if (options.firstComment) form.append("first_comment", options.firstComment);
|
|
317
|
+
if (options.schedule) form.append("schedule", options.schedule);
|
|
318
|
+
if (options.timezone) form.append("timezone", options.timezone);
|
|
319
|
+
if (options.addToQueue !== void 0) form.append("add_to_queue", String(options.addToQueue));
|
|
320
|
+
if (options.asyncUpload !== void 0) form.append("async_upload", String(options.asyncUpload));
|
|
321
|
+
if (options.requestId) form.append("request_id", options.requestId);
|
|
322
|
+
if (options.instagramTitle) form.append("instagram_title", options.instagramTitle);
|
|
323
|
+
if (options.youtubeTitle) form.append("youtube_title", options.youtubeTitle);
|
|
324
|
+
if (options.youtubeDescription) form.append("youtube_description", options.youtubeDescription);
|
|
325
|
+
if (options.youtubeTags) form.append("youtube_tags", options.youtubeTags.join(","));
|
|
326
|
+
if (options.youtubePrivacy) form.append("youtube_privacy", options.youtubePrivacy);
|
|
327
|
+
for (const [k, v] of Object.entries(options.platformOptions || {})) appendOption(form, k, v);
|
|
328
|
+
return form;
|
|
329
|
+
}
|
|
330
|
+
idemHeaders(key) {
|
|
331
|
+
return key ? { "Idempotency-Key": key } : void 0;
|
|
332
|
+
}
|
|
333
|
+
async uploadVideo(sourceOrOptions, maybeOptions) {
|
|
334
|
+
let options;
|
|
335
|
+
if (maybeOptions !== void 0 || typeof sourceOrOptions === "string" || isBytes(sourceOrOptions) || isStreamLike(sourceOrOptions)) {
|
|
336
|
+
const source = sourceOrOptions;
|
|
337
|
+
options = { ...maybeOptions };
|
|
338
|
+
if (typeof source === "string") {
|
|
339
|
+
if (/^https?:\/\//i.test(source)) options.videoUrl = source;
|
|
340
|
+
else options.videoPath = source;
|
|
341
|
+
} else {
|
|
342
|
+
options.video = source;
|
|
343
|
+
}
|
|
344
|
+
} else {
|
|
345
|
+
options = sourceOrOptions;
|
|
346
|
+
}
|
|
347
|
+
const given = [options.videoPath, options.video, options.videoUrl, options.stagedFileId].filter(
|
|
348
|
+
(v) => v !== void 0 && v !== null && v !== ""
|
|
349
|
+
);
|
|
350
|
+
if (given.length === 0) {
|
|
351
|
+
throw new TypeError("uploadVideo requires `videoPath`, `video`, `videoUrl` or `stagedFileId`");
|
|
352
|
+
}
|
|
353
|
+
if (given.length > 1) {
|
|
354
|
+
throw new TypeError("uploadVideo takes only one of `videoPath`, `video`, `videoUrl` or `stagedFileId`");
|
|
355
|
+
}
|
|
356
|
+
const form = this.buildForm(options);
|
|
357
|
+
let stagedFileId = options.stagedFileId;
|
|
358
|
+
const local = options.videoPath ?? options.video;
|
|
359
|
+
if (local !== void 0 && await this.shouldChunk(local, options)) {
|
|
360
|
+
const done = await this.uploadLargeFile(local, {
|
|
361
|
+
filename: options.filename,
|
|
362
|
+
mimeType: options.mimeType,
|
|
363
|
+
size: options.size,
|
|
364
|
+
onProgress: options.onProgress,
|
|
365
|
+
maxRetries: options.maxRetries
|
|
366
|
+
});
|
|
367
|
+
stagedFileId = done.staged_file_id;
|
|
368
|
+
}
|
|
369
|
+
if (stagedFileId) {
|
|
370
|
+
form.append("staged_file_id", stagedFileId);
|
|
371
|
+
} else if (options.videoPath) {
|
|
372
|
+
form.append("video", await fileBlob(options.videoPath), basename(options.videoPath));
|
|
373
|
+
} else if (options.video !== void 0) {
|
|
374
|
+
const name = options.filename || "video.mp4";
|
|
375
|
+
const type = options.mimeType || guessVideoMime(name);
|
|
376
|
+
const bytes = isBytes(options.video) ? options.video : await collect(options.video);
|
|
377
|
+
form.append("video", new Blob([bytes], { type }), name);
|
|
378
|
+
} else {
|
|
379
|
+
form.append("video", options.videoUrl);
|
|
380
|
+
}
|
|
381
|
+
return this.request("/api/upload", {
|
|
382
|
+
method: "POST",
|
|
383
|
+
form,
|
|
384
|
+
headers: this.idemHeaders(options.idempotencyKey)
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
async shouldChunk(source, options) {
|
|
388
|
+
const mode = options.chunked ?? "auto";
|
|
389
|
+
if (mode === true) return true;
|
|
390
|
+
if (mode === false) return false;
|
|
391
|
+
let size;
|
|
392
|
+
if (typeof source === "string") size = (await stat(source)).size;
|
|
393
|
+
else if (isBytes(source)) size = source.byteLength;
|
|
394
|
+
else size = options.size;
|
|
395
|
+
return size !== void 0 && size > CHUNKED_THRESHOLD_BYTES;
|
|
396
|
+
}
|
|
397
|
+
// ── Chunked upload (large videos, up to 500 MB) ───────────────────────────
|
|
398
|
+
/**
|
|
399
|
+
* Start a chunked upload session (`POST /api/upload/chunked/init`). Send every part with
|
|
400
|
+
* {@link uploadPart}, then call {@link completeUploadSession}. Most callers want
|
|
401
|
+
* {@link uploadLargeFile} or `uploadVideo`, which do all of this.
|
|
402
|
+
*/
|
|
403
|
+
async createUploadSession(options) {
|
|
404
|
+
requireArg(options?.filename, "filename");
|
|
405
|
+
if (!Number.isInteger(options.size) || options.size <= 0) {
|
|
406
|
+
throw new TypeError("size must be a positive number of bytes");
|
|
407
|
+
}
|
|
408
|
+
return this.request("/api/upload/chunked/init", {
|
|
409
|
+
method: "POST",
|
|
410
|
+
json: {
|
|
411
|
+
filename: options.filename,
|
|
412
|
+
size: options.size,
|
|
413
|
+
mime_type: options.mime_type || guessVideoMime(options.filename)
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Send one part (`PUT /api/upload/chunked/:id/:index`). Every part must be exactly the
|
|
419
|
+
* session's `chunk_size` bytes except the last. Single attempt; re-sending an index replaces it.
|
|
420
|
+
*/
|
|
421
|
+
async uploadPart(sessionId, index, bytes) {
|
|
422
|
+
requireArg(sessionId, "sessionId");
|
|
423
|
+
if (!Number.isInteger(index) || index < 0) throw new TypeError("index must be a non-negative integer");
|
|
424
|
+
if (!isBytes(bytes)) throw new TypeError("bytes must be a Buffer or Uint8Array");
|
|
425
|
+
return this.request(`/api/upload/chunked/${seg(sessionId)}/${index}`, {
|
|
426
|
+
method: "PUT",
|
|
427
|
+
raw: bytes,
|
|
428
|
+
timeout: Math.max(this.timeout, MIN_PART_TIMEOUT_MS)
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
/** Assemble the parts (`POST /api/upload/chunked/:id/complete`); returns the `staged_file_id`. */
|
|
432
|
+
async completeUploadSession(sessionId) {
|
|
433
|
+
requireArg(sessionId, "sessionId");
|
|
434
|
+
return this.request(`/api/upload/chunked/${seg(sessionId)}/complete`, {
|
|
435
|
+
method: "POST",
|
|
436
|
+
timeout: Math.max(this.timeout, MIN_PART_TIMEOUT_MS)
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
/** Parts received so far (`GET /api/upload/chunked/:id`), to resume an interrupted upload. */
|
|
440
|
+
async getUploadSession(sessionId) {
|
|
441
|
+
requireArg(sessionId, "sessionId");
|
|
442
|
+
return this.request(`/api/upload/chunked/${seg(sessionId)}`);
|
|
443
|
+
}
|
|
444
|
+
/** Cancel a chunked upload and delete its parts (`DELETE /api/upload/chunked/:id`). */
|
|
445
|
+
async abortUploadSession(sessionId) {
|
|
446
|
+
requireArg(sessionId, "sessionId");
|
|
447
|
+
return this.request(`/api/upload/chunked/${seg(sessionId)}`, { method: "DELETE" });
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Send a large video with the chunked upload endpoints: init → parts (sequential, retried on
|
|
451
|
+
* 429 / 5xx / network errors) → complete. Resolves with the `staged_file_id` to post with
|
|
452
|
+
* `uploadVideo({ stagedFileId })` (usable once, within 6 hours). The session is cancelled if a
|
|
453
|
+
* step fails for good.
|
|
454
|
+
*
|
|
455
|
+
* `source` is a file path, a Buffer / Uint8Array, or a readable stream. Files are read part by
|
|
456
|
+
* part; a stream with `size` is read part by part, and a stream without `size` is first written
|
|
457
|
+
* to a temporary file (deleted afterwards).
|
|
458
|
+
*/
|
|
459
|
+
async uploadLargeFile(source, options = {}) {
|
|
460
|
+
let reader;
|
|
461
|
+
let cleanup;
|
|
462
|
+
let filename = options.filename;
|
|
463
|
+
if (typeof source === "string") {
|
|
464
|
+
reader = await fileReader(source);
|
|
465
|
+
filename ||= basename(source);
|
|
466
|
+
} else if (isBytes(source)) {
|
|
467
|
+
reader = bufferReader(source);
|
|
468
|
+
} else if (isStreamLike(source)) {
|
|
469
|
+
if (options.size !== void 0) {
|
|
470
|
+
if (!Number.isInteger(options.size) || options.size <= 0) {
|
|
471
|
+
throw new TypeError("size must be a positive number of bytes");
|
|
472
|
+
}
|
|
473
|
+
reader = streamReader(source, options.size);
|
|
474
|
+
} else {
|
|
475
|
+
const spooled = await spoolToTempFile(source);
|
|
476
|
+
cleanup = spooled.cleanup;
|
|
477
|
+
reader = await fileReader(spooled.path);
|
|
478
|
+
}
|
|
479
|
+
} else {
|
|
480
|
+
throw new TypeError("source must be a file path, a Buffer / Uint8Array or a readable stream");
|
|
481
|
+
}
|
|
482
|
+
const name = filename || "video.mp4";
|
|
483
|
+
const attempts = Math.max(1, options.maxRetries ?? DEFAULT_MAX_RETRIES);
|
|
484
|
+
try {
|
|
485
|
+
if (reader.size <= 0) throw new TypeError("The file is empty");
|
|
486
|
+
const session = await this.withRetry(
|
|
487
|
+
() => this.createUploadSession({ filename: name, size: reader.size, mime_type: options.mimeType || guessVideoMime(name) }),
|
|
488
|
+
attempts,
|
|
489
|
+
// 5 sessions already in progress: waiting won't help.
|
|
490
|
+
(err) => err.code !== "TOO_MANY_CHUNKED_UPLOADS"
|
|
491
|
+
);
|
|
492
|
+
const id = session.upload_session_id;
|
|
493
|
+
try {
|
|
494
|
+
const chunkSize = session.chunk_size;
|
|
495
|
+
const totalParts = session.total_chunks ?? Math.ceil(reader.size / chunkSize);
|
|
496
|
+
let uploadedBytes = 0;
|
|
497
|
+
for (let index = 0; index < totalParts; index++) {
|
|
498
|
+
const bytes = await reader.read(index, chunkSize);
|
|
499
|
+
await this.withRetry(() => this.uploadPart(id, index, bytes), attempts);
|
|
500
|
+
uploadedBytes += bytes.byteLength;
|
|
501
|
+
const progress = { uploadedBytes, totalBytes: reader.size, part: index + 1, totalParts };
|
|
502
|
+
options.onProgress?.(progress);
|
|
503
|
+
}
|
|
504
|
+
return await this.withRetry(() => this.completeUploadSession(id), attempts);
|
|
505
|
+
} catch (err) {
|
|
506
|
+
await this.abortUploadSession(id).catch(() => void 0);
|
|
507
|
+
throw err;
|
|
508
|
+
}
|
|
509
|
+
} finally {
|
|
510
|
+
await reader.close().catch(() => void 0);
|
|
511
|
+
if (cleanup) await cleanup().catch(() => void 0);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/** Retry `fn` on network errors, timeouts, 429 and 5xx (honouring Retry-After), up to `attempts` tries. */
|
|
515
|
+
async withRetry(fn, attempts, alsoRequire = () => true) {
|
|
516
|
+
for (let attempt = 1; ; attempt++) {
|
|
517
|
+
try {
|
|
518
|
+
return await fn();
|
|
519
|
+
} catch (err) {
|
|
520
|
+
const retryable = err instanceof PostUploadError && (err.status === 0 || err.status === 408 || err.status === 429 || err.status >= 500 && err.status !== 501) && err.code !== "INSUFFICIENT_STORAGE" && alsoRequire(err);
|
|
521
|
+
if (!retryable || attempt >= attempts) throw err;
|
|
522
|
+
const backoff = Math.min(3e4, this.retryBaseDelayMs * 2 ** (attempt - 1));
|
|
523
|
+
const delay = err.retryAfter != null ? Math.min(err.retryAfter * 1e3, 12e4) : backoff + Math.random() * backoff * 0.2;
|
|
524
|
+
await sleep(delay);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
/** Upload photos / a carousel (local files via `photoPaths` and/or public URLs via `photoUrls`; max 10). */
|
|
529
|
+
async uploadPhotos(options) {
|
|
530
|
+
const paths = options.photoPaths || [];
|
|
531
|
+
const urls = options.photoUrls || [];
|
|
532
|
+
if (paths.length + urls.length === 0) {
|
|
533
|
+
throw new TypeError("uploadPhotos requires `photoPaths` or `photoUrls`");
|
|
534
|
+
}
|
|
535
|
+
if (paths.length + urls.length > MAX_PHOTOS) {
|
|
536
|
+
throw new TypeError(`uploadPhotos accepts at most ${MAX_PHOTOS} photos`);
|
|
537
|
+
}
|
|
538
|
+
const form = this.buildForm(options);
|
|
539
|
+
for (const p of paths) form.append("photos[]", await fileBlob(p), basename(p));
|
|
540
|
+
for (const u of urls) form.append("photo_urls[]", u);
|
|
541
|
+
return this.request("/api/upload_photos", {
|
|
542
|
+
method: "POST",
|
|
543
|
+
form,
|
|
544
|
+
headers: this.idemHeaders(options.idempotencyKey)
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
/** Publish a text-only post (`text` or `title`). */
|
|
548
|
+
async uploadText(options) {
|
|
549
|
+
const text = options.text ?? options.title;
|
|
550
|
+
if (!text) throw new TypeError("uploadText requires `text` (or `title`)");
|
|
551
|
+
const form = this.buildForm({ ...options, title: void 0 });
|
|
552
|
+
form.append("text", text);
|
|
553
|
+
return this.request("/api/upload_text", {
|
|
554
|
+
method: "POST",
|
|
555
|
+
form,
|
|
556
|
+
headers: this.idemHeaders(options.idempotencyKey)
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
/** Publish a LinkedIn document post (PDF, PPT, PPTX, DOC, DOCX). */
|
|
560
|
+
async uploadDocument(options) {
|
|
561
|
+
requireArg(options.user, "user");
|
|
562
|
+
requireArg(options.documentPath, "documentPath");
|
|
563
|
+
const form = new FormData();
|
|
564
|
+
form.append("user", options.user);
|
|
565
|
+
if (options.title) form.append("title", options.title);
|
|
566
|
+
if (options.description) form.append("description", options.description);
|
|
567
|
+
if (options.firstComment) form.append("first_comment", options.firstComment);
|
|
568
|
+
if (options.visibility) form.append("visibility", options.visibility);
|
|
569
|
+
if (options.targetLinkedinPageId) form.append("target_linkedin_page_id", options.targetLinkedinPageId);
|
|
570
|
+
if (options.schedule) form.append("schedule", options.schedule);
|
|
571
|
+
if (options.timezone) form.append("timezone", options.timezone);
|
|
572
|
+
if (options.requestId) form.append("request_id", options.requestId);
|
|
573
|
+
for (const [k, v] of Object.entries(options.platformOptions || {})) appendOption(form, k, v);
|
|
574
|
+
form.append("document", await fileBlob(options.documentPath), basename(options.documentPath));
|
|
575
|
+
return this.request("/api/upload_document", {
|
|
576
|
+
method: "POST",
|
|
577
|
+
form,
|
|
578
|
+
headers: this.idemHeaders(options.idempotencyKey)
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
// ── Uploads / status ──────────────────────────────────────────────────────
|
|
582
|
+
/** Current account: plan, monthly usage, API key id. */
|
|
583
|
+
async getMe() {
|
|
584
|
+
return this.request("/api/me");
|
|
585
|
+
}
|
|
586
|
+
/** Status of one upload (per-platform results, post ids, errors). */
|
|
587
|
+
async getUploadStatus(uploadId) {
|
|
588
|
+
requireArg(uploadId, "uploadId");
|
|
589
|
+
return this.request(`/api/upload/${seg(uploadId)}/status`);
|
|
590
|
+
}
|
|
591
|
+
/** Look an upload up by your own `requestId` (or by upload id). */
|
|
592
|
+
async getRequestStatus(requestId) {
|
|
593
|
+
requireArg(requestId, "requestId");
|
|
594
|
+
return this.request("/api/uploadposts/status", { query: { request_id: requestId } });
|
|
595
|
+
}
|
|
596
|
+
/** Paginated upload history. */
|
|
597
|
+
async listUploads(options = {}) {
|
|
598
|
+
return this.request("/api/uploads", {
|
|
599
|
+
query: { limit: options.limit, page: options.page, status: options.status }
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
/** A single upload record. */
|
|
603
|
+
async getUpload(uploadId) {
|
|
604
|
+
requireArg(uploadId, "uploadId");
|
|
605
|
+
return this.request(`/api/uploads/${seg(uploadId)}`);
|
|
606
|
+
}
|
|
607
|
+
/** Delete an upload record (and its stored media). Not allowed while processing. */
|
|
608
|
+
async deleteUpload(uploadId) {
|
|
609
|
+
requireArg(uploadId, "uploadId");
|
|
610
|
+
return this.request(`/api/uploads/${seg(uploadId)}`, { method: "DELETE" });
|
|
611
|
+
}
|
|
612
|
+
/** Retry a failed upload. */
|
|
613
|
+
async retryUpload(uploadId) {
|
|
614
|
+
requireArg(uploadId, "uploadId");
|
|
615
|
+
return this.request(`/api/uploads/${seg(uploadId)}/retry`, { method: "POST" });
|
|
616
|
+
}
|
|
617
|
+
/** Per-platform daily posting limits and current usage. */
|
|
618
|
+
async getPlatformLimits() {
|
|
619
|
+
return this.request("/api/platform-limits");
|
|
620
|
+
}
|
|
621
|
+
// ── Profiles ──────────────────────────────────────────────────────────────
|
|
622
|
+
/** List all profiles. */
|
|
623
|
+
async getProfiles() {
|
|
624
|
+
return this.request("/api/profiles");
|
|
625
|
+
}
|
|
626
|
+
/** Create a new profile. */
|
|
627
|
+
async createProfile(name) {
|
|
628
|
+
requireArg(name, "name");
|
|
629
|
+
return this.request("/api/profiles", { method: "POST", json: { name } });
|
|
630
|
+
}
|
|
631
|
+
/** Delete a profile. */
|
|
632
|
+
async deleteProfile(name) {
|
|
633
|
+
requireArg(name, "name");
|
|
634
|
+
return this.request(`/api/profiles/${seg(name)}`, { method: "DELETE" });
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Connect a platform that uses credentials instead of OAuth (Discord, Telegram,
|
|
638
|
+
* Slack, Mastodon, WordPress, Dev.to, Hashnode, Lemmy, Nostr, Whop, Listmonk). The server verifies them live before saving;
|
|
639
|
+
* connecting again replaces the stored credentials.
|
|
640
|
+
*
|
|
641
|
+
* Errors: 400 with `code` MISSING_FIELD / FIELD_TOO_LONG / INVALID_CREDENTIALS
|
|
642
|
+
* (`err.body.details.field` names the field), 404 unknown profile, 502 platform unreachable.
|
|
643
|
+
*
|
|
644
|
+
* @example
|
|
645
|
+
* await client.connectWithCredentials('my-brand', 'mastodon', {
|
|
646
|
+
* instance_url: 'https://mastodon.social', access_token: '...',
|
|
647
|
+
* });
|
|
648
|
+
*/
|
|
649
|
+
async connectWithCredentials(profile, platform, credentials) {
|
|
650
|
+
requireArg(profile, "profile");
|
|
651
|
+
requireArg(platform, "platform");
|
|
652
|
+
if (!credentials || typeof credentials !== "object") throw new TypeError("credentials is required");
|
|
653
|
+
return this.request(`/api/profiles/${seg(profile)}/connect/${seg(platform)}/credentials`, {
|
|
654
|
+
method: "POST",
|
|
655
|
+
json: credentials
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
// ── Scheduling ────────────────────────────────────────────────────────────
|
|
659
|
+
/** All scheduled (not yet published) posts. */
|
|
660
|
+
async getScheduledPosts() {
|
|
661
|
+
return this.request("/api/schedule");
|
|
662
|
+
}
|
|
663
|
+
/** Reschedule or edit a scheduled post. */
|
|
664
|
+
async updateScheduledPost(jobId, options) {
|
|
665
|
+
requireArg(jobId, "jobId");
|
|
666
|
+
const body = {};
|
|
667
|
+
if (options.scheduledDate !== void 0) body.scheduled_date = options.scheduledDate;
|
|
668
|
+
if (options.timezone !== void 0) body.timezone = options.timezone;
|
|
669
|
+
if (options.title !== void 0) body.title = options.title;
|
|
670
|
+
if (options.caption !== void 0) body.caption = options.caption;
|
|
671
|
+
return this.request(`/api/schedule/${seg(jobId)}`, { method: "PATCH", json: body });
|
|
672
|
+
}
|
|
673
|
+
/** Cancel a scheduled post. */
|
|
674
|
+
async cancelScheduledPost(jobId) {
|
|
675
|
+
requireArg(jobId, "jobId");
|
|
676
|
+
return this.request(`/api/schedule/${seg(jobId)}`, { method: "DELETE" });
|
|
677
|
+
}
|
|
678
|
+
// ── Queue ─────────────────────────────────────────────────────────────────
|
|
679
|
+
/** Queue settings (time slots, days, timezone) for a profile. */
|
|
680
|
+
async getQueueSettings(profile) {
|
|
681
|
+
requireArg(profile, "profile");
|
|
682
|
+
return this.request("/api/queue/settings", { query: { profile } });
|
|
683
|
+
}
|
|
684
|
+
/** Create or update a profile's queue settings. */
|
|
685
|
+
async updateQueueSettings(options) {
|
|
686
|
+
requireArg(options?.profile, "profile");
|
|
687
|
+
const body = { profile_username: options.profile };
|
|
688
|
+
if (options.slots !== void 0) body.slots = options.slots;
|
|
689
|
+
if (options.daysOfWeek !== void 0) body.days_of_week = options.daysOfWeek;
|
|
690
|
+
if (options.timezone !== void 0) body.timezone = options.timezone;
|
|
691
|
+
if (options.maxPostsPerSlot !== void 0) body.max_posts_per_slot = options.maxPostsPerSlot;
|
|
692
|
+
return this.request("/api/queue/settings", { method: "POST", json: body });
|
|
693
|
+
}
|
|
694
|
+
/** Upcoming queue slots for a profile. */
|
|
695
|
+
async getQueuePreview(profile, count) {
|
|
696
|
+
requireArg(profile, "profile");
|
|
697
|
+
return this.request("/api/queue/preview", { query: { profile, count } });
|
|
698
|
+
}
|
|
699
|
+
/** The next free queue slot for a profile. */
|
|
700
|
+
async getNextQueueSlot(profile) {
|
|
701
|
+
requireArg(profile, "profile");
|
|
702
|
+
return this.request("/api/queue/next-slot", { query: { profile } });
|
|
703
|
+
}
|
|
704
|
+
// ── Platform helpers ──────────────────────────────────────────────────────
|
|
705
|
+
/** Facebook pages available to the profile (use the id as `facebook_page_id`). */
|
|
706
|
+
async getFacebookPages(profile) {
|
|
707
|
+
requireArg(profile, "profile");
|
|
708
|
+
return this.request("/api/platforms/facebook/pages", { query: { profile } });
|
|
709
|
+
}
|
|
710
|
+
/** LinkedIn company pages (use the id as `target_linkedin_page_id`). */
|
|
711
|
+
async getLinkedInPages(profile) {
|
|
712
|
+
requireArg(profile, "profile");
|
|
713
|
+
return this.request("/api/platforms/linkedin/pages", { query: { profile } });
|
|
714
|
+
}
|
|
715
|
+
/** Pinterest boards (use the id as `pinterest_board_id`). */
|
|
716
|
+
async getPinterestBoards(profile) {
|
|
717
|
+
requireArg(profile, "profile");
|
|
718
|
+
return this.request("/api/platforms/pinterest/boards", { query: { profile } });
|
|
719
|
+
}
|
|
720
|
+
/** Google Business Profile locations (use the id as `gbp_location_id`). */
|
|
721
|
+
async getGoogleBusinessLocations(profile) {
|
|
722
|
+
requireArg(profile, "profile");
|
|
723
|
+
return this.request("/api/platforms/google-business/locations", { query: { profile } });
|
|
724
|
+
}
|
|
725
|
+
// ── Analytics ─────────────────────────────────────────────────────────────
|
|
726
|
+
/** Account analytics overview (e.g. range "7d", "30d", "90d"). */
|
|
727
|
+
async getAnalytics(range = "30d") {
|
|
728
|
+
return this.request("/api/analytics/overview", { query: { range } });
|
|
729
|
+
}
|
|
730
|
+
/** Live follower / engagement stats pulled from the platforms for a profile. */
|
|
731
|
+
async getLiveAnalytics(profile, platforms) {
|
|
732
|
+
requireArg(profile, "profile");
|
|
733
|
+
return this.request(`/api/analytics/live/${seg(profile)}`, {
|
|
734
|
+
query: { platforms: platforms && platforms.length ? platforms.join(",") : void 0 }
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
/** Per-post analytics for an upload (optionally a single platform). */
|
|
738
|
+
async getPostAnalytics(uploadId, platform) {
|
|
739
|
+
requireArg(uploadId, "uploadId");
|
|
740
|
+
return this.request(`/api/analytics/post/${seg(uploadId)}`, { query: { platform } });
|
|
741
|
+
}
|
|
742
|
+
/** Total impressions for a profile. */
|
|
743
|
+
async getTotalImpressions(profile, options = {}) {
|
|
744
|
+
requireArg(profile, "profile");
|
|
745
|
+
return this.request(`/api/analytics/total-impressions/${seg(profile)}`, {
|
|
746
|
+
query: {
|
|
747
|
+
platform: options.platform,
|
|
748
|
+
period: options.period,
|
|
749
|
+
start_date: options.startDate,
|
|
750
|
+
end_date: options.endDate
|
|
751
|
+
}
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
// ── FFmpeg ────────────────────────────────────────────────────────────────
|
|
755
|
+
/** FFmpeg processing minutes used / remaining this month. */
|
|
756
|
+
async getFfmpegUsage() {
|
|
757
|
+
return this.request("/api/ffmpeg/usage");
|
|
758
|
+
}
|
|
759
|
+
/** Recent FFmpeg jobs (latest 50). */
|
|
760
|
+
async listFfmpegJobs() {
|
|
761
|
+
return this.request("/api/ffmpeg/jobs");
|
|
762
|
+
}
|
|
763
|
+
/** A single FFmpeg job. */
|
|
764
|
+
async getFfmpegJob(jobId) {
|
|
765
|
+
requireArg(jobId, "jobId");
|
|
766
|
+
return this.request(`/api/ffmpeg/jobs/${seg(jobId)}`);
|
|
767
|
+
}
|
|
768
|
+
// ── Plans ─────────────────────────────────────────────────────────────────
|
|
769
|
+
/** List available plans. */
|
|
770
|
+
async getPlans() {
|
|
771
|
+
return this.request("/api/plans");
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
var IndReelForge = PostUpload;
|
|
775
|
+
var InReelForge = PostUpload;
|
|
776
|
+
|
|
777
|
+
// src/mcp-bridge.ts
|
|
778
|
+
import { createInterface } from "readline";
|
|
779
|
+
var DEFAULT_MCP_URL = "https://api.post-upload.com/mcp";
|
|
780
|
+
var DEFAULT_MCP_TIMEOUT_MS = 3e5;
|
|
781
|
+
var TRANSPORT_ERROR_CODE = -32e3;
|
|
782
|
+
var PARSE_ERROR_CODE = -32700;
|
|
783
|
+
var INTERNAL_ERROR_CODE = -32603;
|
|
784
|
+
function parseSseData(text) {
|
|
785
|
+
const out = [];
|
|
786
|
+
for (const block of text.split(/\r?\n\r?\n/)) {
|
|
787
|
+
let event = "message";
|
|
788
|
+
const data = [];
|
|
789
|
+
for (const line of block.split(/\r?\n/)) {
|
|
790
|
+
if (line.startsWith(":")) continue;
|
|
791
|
+
const idx = line.indexOf(":");
|
|
792
|
+
const field = idx === -1 ? line : line.slice(0, idx);
|
|
793
|
+
let value = idx === -1 ? "" : line.slice(idx + 1);
|
|
794
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
795
|
+
if (field === "event") event = value;
|
|
796
|
+
else if (field === "data") data.push(value);
|
|
797
|
+
}
|
|
798
|
+
if (event === "message" && data.length) {
|
|
799
|
+
const joined = data.join("\n");
|
|
800
|
+
if (joined.trim()) out.push(joined);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return out;
|
|
804
|
+
}
|
|
805
|
+
function isRequest(m) {
|
|
806
|
+
return !!m && typeof m === "object" && !Array.isArray(m) && typeof m.method === "string" && m.id !== void 0 && m.id !== null;
|
|
807
|
+
}
|
|
808
|
+
function isJsonRpcResponse(m) {
|
|
809
|
+
return !!m && typeof m === "object" && m.jsonrpc === "2.0" && ("error" in m || "result" in m);
|
|
810
|
+
}
|
|
811
|
+
function rpcError(id, code, message, data) {
|
|
812
|
+
const error = { code, message };
|
|
813
|
+
if (data !== void 0) error.data = data;
|
|
814
|
+
return { jsonrpc: "2.0", id, error };
|
|
815
|
+
}
|
|
816
|
+
function describeHttpError(status, statusText, body, text) {
|
|
817
|
+
let detail = "";
|
|
818
|
+
if (body && typeof body === "object") {
|
|
819
|
+
const b = body;
|
|
820
|
+
const parts = [b.error, b.error_description, b.message].filter((p) => typeof p === "string" && p);
|
|
821
|
+
detail = [...new Set(parts)].join(": ");
|
|
822
|
+
}
|
|
823
|
+
if (!detail && text.trim()) detail = text.trim().replace(/\s+/g, " ").slice(0, 200);
|
|
824
|
+
if (!detail) detail = statusText || "request failed";
|
|
825
|
+
let msg = `Post-Upload MCP server returned HTTP ${status}: ${detail}`;
|
|
826
|
+
if (status === 401 || status === 403) {
|
|
827
|
+
msg += " (check that POST_UPLOAD_API_KEY is a valid Post-Upload API key)";
|
|
828
|
+
}
|
|
829
|
+
return msg;
|
|
830
|
+
}
|
|
831
|
+
async function forwardLine(line, state, opts) {
|
|
832
|
+
const trimmed = line.trim();
|
|
833
|
+
if (!trimmed) return [];
|
|
834
|
+
let msg;
|
|
835
|
+
try {
|
|
836
|
+
msg = JSON.parse(trimmed);
|
|
837
|
+
} catch (err) {
|
|
838
|
+
opts.log(`[post-upload] ignoring invalid JSON on stdin: ${err.message}`);
|
|
839
|
+
return [rpcError(null, PARSE_ERROR_CODE, "Parse error: invalid JSON received on stdin")];
|
|
840
|
+
}
|
|
841
|
+
const isBatch = Array.isArray(msg);
|
|
842
|
+
const requests = (isBatch ? msg : [msg]).filter(isRequest);
|
|
843
|
+
const ids = requests.map((r) => r.id);
|
|
844
|
+
const isInitialize = requests.some((r) => r.method === "initialize");
|
|
845
|
+
const failAll = (code, message, data) => {
|
|
846
|
+
opts.log(`[post-upload] ${message}`);
|
|
847
|
+
if (!ids.length) return [];
|
|
848
|
+
const errors = ids.map((id) => rpcError(id, code, message, data));
|
|
849
|
+
return isBatch ? [errors] : errors;
|
|
850
|
+
};
|
|
851
|
+
const headers = {
|
|
852
|
+
Authorization: `ApiKey ${opts.apiKey}`,
|
|
853
|
+
"Content-Type": "application/json",
|
|
854
|
+
Accept: "application/json, text/event-stream",
|
|
855
|
+
"User-Agent": `post-upload-node/${VERSION}`
|
|
856
|
+
};
|
|
857
|
+
if (state.sessionId) headers["Mcp-Session-Id"] = state.sessionId;
|
|
858
|
+
if (state.protocolVersion && !isInitialize) headers["MCP-Protocol-Version"] = state.protocolVersion;
|
|
859
|
+
const controller = new AbortController();
|
|
860
|
+
const timer = setTimeout(() => controller.abort(), opts.timeoutMs);
|
|
861
|
+
let res;
|
|
862
|
+
let text;
|
|
863
|
+
try {
|
|
864
|
+
res = await opts.fetch(opts.url, { method: "POST", headers, body: trimmed, signal: controller.signal });
|
|
865
|
+
text = await res.text();
|
|
866
|
+
} catch (err) {
|
|
867
|
+
const e = err;
|
|
868
|
+
if (e?.name === "AbortError") {
|
|
869
|
+
return failAll(TRANSPORT_ERROR_CODE, `Request to Post-Upload MCP server timed out after ${Math.round(opts.timeoutMs / 1e3)}s`);
|
|
870
|
+
}
|
|
871
|
+
const cause = e?.cause;
|
|
872
|
+
const reason = cause?.code || cause?.message || e?.message || String(err);
|
|
873
|
+
return failAll(TRANSPORT_ERROR_CODE, `Could not reach Post-Upload MCP server at ${opts.url}: ${reason}`);
|
|
874
|
+
} finally {
|
|
875
|
+
clearTimeout(timer);
|
|
876
|
+
}
|
|
877
|
+
const sid = res.headers.get("mcp-session-id");
|
|
878
|
+
if (sid) state.sessionId = sid;
|
|
879
|
+
if (res.status === 202 || res.status === 204) return [];
|
|
880
|
+
const contentType = (res.headers.get("content-type") || "").toLowerCase();
|
|
881
|
+
const payloads = [];
|
|
882
|
+
let undecodable = false;
|
|
883
|
+
const chunks = contentType.includes("text/event-stream") ? parseSseData(text) : text.trim() ? [text] : [];
|
|
884
|
+
for (const chunk of chunks) {
|
|
885
|
+
try {
|
|
886
|
+
payloads.push(JSON.parse(chunk));
|
|
887
|
+
} catch {
|
|
888
|
+
undecodable = true;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (!res.ok) {
|
|
892
|
+
if (res.status === 404 && state.sessionId) {
|
|
893
|
+
opts.log("[post-upload] MCP session expired; the client must re-initialize");
|
|
894
|
+
state.sessionId = null;
|
|
895
|
+
}
|
|
896
|
+
const rpc = payloads.filter((p) => isJsonRpcResponse(p) || Array.isArray(p) && p.some(isJsonRpcResponse));
|
|
897
|
+
if (rpc.length) {
|
|
898
|
+
opts.log(`[post-upload] HTTP ${res.status} with JSON-RPC error body (passed through)`);
|
|
899
|
+
return rpc;
|
|
900
|
+
}
|
|
901
|
+
return failAll(
|
|
902
|
+
TRANSPORT_ERROR_CODE,
|
|
903
|
+
describeHttpError(res.status, res.statusText, payloads[0], text),
|
|
904
|
+
{ httpStatus: res.status, body: payloads[0] ?? (text.trim() ? text.slice(0, 500) : null) }
|
|
905
|
+
);
|
|
906
|
+
}
|
|
907
|
+
if (!payloads.length) {
|
|
908
|
+
if (undecodable) return failAll(INTERNAL_ERROR_CODE, "Post-Upload MCP server returned a response that is not valid JSON");
|
|
909
|
+
return ids.length ? failAll(INTERNAL_ERROR_CODE, `Post-Upload MCP server returned an empty response (HTTP ${res.status})`) : [];
|
|
910
|
+
}
|
|
911
|
+
if (isInitialize) {
|
|
912
|
+
for (const p of payloads.flat()) {
|
|
913
|
+
const v = p?.result?.protocolVersion;
|
|
914
|
+
if (typeof v === "string") state.protocolVersion = v;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
return payloads;
|
|
918
|
+
}
|
|
919
|
+
async function runMcpBridge(options) {
|
|
920
|
+
if (!options.apiKey) throw new Error("apiKey is required");
|
|
921
|
+
const input = options.input || process.stdin;
|
|
922
|
+
const output = options.output || process.stdout;
|
|
923
|
+
const log = options.log || ((m) => process.stderr.write(`${m}
|
|
924
|
+
`));
|
|
925
|
+
const fetchImpl = options.fetch || globalThis.fetch;
|
|
926
|
+
if (typeof fetchImpl !== "function") throw new Error("global fetch is unavailable; Node.js >= 18 is required");
|
|
927
|
+
const opts = {
|
|
928
|
+
apiKey: options.apiKey,
|
|
929
|
+
url: options.url || DEFAULT_MCP_URL,
|
|
930
|
+
timeoutMs: options.timeoutMs || DEFAULT_MCP_TIMEOUT_MS,
|
|
931
|
+
fetch: fetchImpl,
|
|
932
|
+
log
|
|
933
|
+
};
|
|
934
|
+
const state = { sessionId: null, protocolVersion: null, initGate: null };
|
|
935
|
+
const inflight = /* @__PURE__ */ new Set();
|
|
936
|
+
const write = (payload) => {
|
|
937
|
+
output.write(`${JSON.stringify(payload)}
|
|
938
|
+
`);
|
|
939
|
+
};
|
|
940
|
+
const handle = async (line) => {
|
|
941
|
+
const gate = state.initGate;
|
|
942
|
+
if (gate) await gate;
|
|
943
|
+
try {
|
|
944
|
+
for (const payload of await forwardLine(line, state, opts)) write(payload);
|
|
945
|
+
} catch (err) {
|
|
946
|
+
log(`[post-upload] unexpected bridge error: ${err?.stack || String(err)}`);
|
|
947
|
+
}
|
|
948
|
+
};
|
|
949
|
+
const rl = createInterface({ input, crlfDelay: Infinity, terminal: false });
|
|
950
|
+
for await (const line of rl) {
|
|
951
|
+
if (!line.trim()) continue;
|
|
952
|
+
let initializing = false;
|
|
953
|
+
try {
|
|
954
|
+
const parsed = JSON.parse(line);
|
|
955
|
+
initializing = (Array.isArray(parsed) ? parsed : [parsed]).some((m) => m && m.method === "initialize");
|
|
956
|
+
} catch {
|
|
957
|
+
}
|
|
958
|
+
const p = handle(line);
|
|
959
|
+
inflight.add(p);
|
|
960
|
+
p.finally(() => inflight.delete(p));
|
|
961
|
+
if (initializing) state.initGate = p.then(() => void 0);
|
|
962
|
+
}
|
|
963
|
+
await Promise.allSettled([...inflight]);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// src/index.ts
|
|
967
|
+
var src_default = PostUpload;
|
|
968
|
+
export {
|
|
969
|
+
CHUNKED_THRESHOLD_BYTES,
|
|
970
|
+
CREDENTIAL_PLATFORMS,
|
|
971
|
+
DEFAULT_BASE_URL,
|
|
972
|
+
DEFAULT_MCP_URL,
|
|
973
|
+
InReelForge,
|
|
974
|
+
InReelForgeError,
|
|
975
|
+
IndReelForge,
|
|
976
|
+
IndReelForgeError,
|
|
977
|
+
MAX_VIDEO_BYTES,
|
|
978
|
+
PLATFORMS,
|
|
979
|
+
PostUpload,
|
|
980
|
+
PostUploadError,
|
|
981
|
+
VERSION,
|
|
982
|
+
src_default as default,
|
|
983
|
+
runMcpBridge
|
|
984
|
+
};
|