vibedgames 0.5.0 → 0.5.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/LICENSE +21 -0
- package/dist/commands/completions.d.ts +1 -1
- package/dist/commands/completions.js +21 -20
- package/dist/commands/credits.d.ts +5 -5
- package/dist/commands/credits.js +43 -33
- package/dist/commands/deploy.d.ts +10 -10
- package/dist/commands/deploy.js +155 -139
- package/dist/commands/factory.d.ts +1 -1
- package/dist/commands/factory.js +18 -15
- package/dist/commands/fork.d.ts +14 -14
- package/dist/commands/fork.js +51 -46
- package/dist/commands/generate.js +318 -264
- package/dist/commands/init.d.ts +8 -8
- package/dist/commands/init.js +31 -24
- package/dist/commands/login.js +12 -12
- package/dist/commands/logout.js +2 -2
- package/dist/commands/new.d.ts +16 -16
- package/dist/commands/new.js +153 -142
- package/dist/commands/playtest.d.ts +5 -5
- package/dist/commands/playtest.js +103 -97
- package/dist/commands/update.d.ts +7 -7
- package/dist/commands/update.js +20 -17
- package/dist/commands/whoami.d.ts +5 -5
- package/dist/commands/whoami.js +8 -7
- package/dist/index.js +10 -10
- package/dist/lib/api.d.ts +4 -4
- package/dist/lib/api.js +6 -12
- package/dist/lib/archive.d.ts +4 -4
- package/dist/lib/archive.js +121 -104
- package/dist/lib/codex.d.ts +45 -15
- package/dist/lib/codex.js +175 -106
- package/dist/lib/config-file.d.ts +6 -6
- package/dist/lib/config-file.js +28 -26
- package/dist/lib/config.d.ts +8 -8
- package/dist/lib/config.js +31 -33
- package/dist/lib/manifest.d.ts +3 -3
- package/dist/lib/manifest.js +42 -38
- package/dist/lib/media-args.d.ts +7 -7
- package/dist/lib/media-args.js +113 -95
- package/dist/lib/media-download.d.ts +9 -9
- package/dist/lib/media-download.js +148 -134
- package/dist/lib/media-poll.d.ts +8 -8
- package/dist/lib/media-poll.js +32 -27
- package/dist/lib/media-upload.d.ts +2 -2
- package/dist/lib/media-upload.js +27 -27
- package/dist/lib/output.d.ts +27 -12
- package/dist/lib/output.js +26 -26
- package/dist/lib/package-manager.d.ts +3 -3
- package/dist/lib/package-manager.js +27 -22
- package/dist/lib/run.d.ts +4 -4
- package/dist/lib/run.js +7 -4
- package/dist/lib/strict-args.d.ts +4 -4
- package/dist/lib/strict-args.js +28 -18
- package/dist/lib/types.d.ts +5 -5
- package/dist/lib/types.js +9 -12
- package/dist/lib/update.d.ts +4 -4
- package/dist/lib/update.js +41 -32
- package/dist/lib/upload.d.ts +4 -4
- package/dist/lib/upload.js +14 -9
- package/package.json +16 -16
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
-
import
|
|
2
|
+
import path from "node:path";
|
|
3
3
|
import { isJsonObject, isJsonString } from "./types.js";
|
|
4
4
|
// Lowercase file extensions we recognize as media when sniffing fal
|
|
5
5
|
// response payloads where `content_type` is missing (some endpoints
|
|
@@ -23,28 +23,9 @@ const MEDIA_EXT = new Set([
|
|
|
23
23
|
"flac",
|
|
24
24
|
"m4a",
|
|
25
25
|
]);
|
|
26
|
-
/**
|
|
27
|
-
* Walk a fal result payload and pull out anything that looks like a media
|
|
28
|
-
* output. fal endpoints embed outputs in objects shaped like
|
|
29
|
-
* `{ url, content_type, file_name, ... }`; we accept image/video/audio
|
|
30
|
-
* content types and also fall back to URL extension when content_type is
|
|
31
|
-
* absent (some endpoints omit it).
|
|
32
|
-
*/
|
|
33
|
-
export function extractMediaRefs(result) {
|
|
34
|
-
const seen = new Set();
|
|
35
|
-
const refs = [];
|
|
36
|
-
visit(result, refs, seen);
|
|
37
|
-
return refs;
|
|
38
|
-
}
|
|
39
|
-
// fal stores generated outputs on its own CDN (`X-Fal-Store-IO: 1`) and
|
|
40
|
-
// always serves them over HTTPS. Restrict `--download` candidates to
|
|
41
|
-
// those hosts and that scheme so a fal response can't trick the CLI
|
|
42
|
-
// into fetching arbitrary URLs (e.g. attacker-controlled or
|
|
43
|
-
// internal-network targets) on the user's machine, and can't downgrade
|
|
44
|
-
// to plain HTTP.
|
|
45
26
|
const TRUSTED_HOST_SUFFIXES = [".fal.media", ".fal.run", ".fal.ai"];
|
|
46
27
|
const TRUSTED_HOSTS = new Set(["fal.media", "fal.run", "fal.ai"]);
|
|
47
|
-
|
|
28
|
+
const isTrustedFalContentHost = (url) => {
|
|
48
29
|
let parsed;
|
|
49
30
|
try {
|
|
50
31
|
parsed = new URL(url);
|
|
@@ -52,70 +33,104 @@ function isTrustedFalContentHost(url) {
|
|
|
52
33
|
catch {
|
|
53
34
|
return false;
|
|
54
35
|
}
|
|
55
|
-
if (parsed.protocol !== "https:")
|
|
36
|
+
if (parsed.protocol !== "https:") {
|
|
56
37
|
return false;
|
|
38
|
+
}
|
|
57
39
|
const host = parsed.hostname.toLowerCase();
|
|
58
|
-
if (TRUSTED_HOSTS.has(host))
|
|
40
|
+
if (TRUSTED_HOSTS.has(host)) {
|
|
59
41
|
return true;
|
|
42
|
+
}
|
|
60
43
|
return TRUSTED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));
|
|
61
|
-
}
|
|
62
|
-
|
|
44
|
+
};
|
|
45
|
+
const extFromUrl = (url) => {
|
|
46
|
+
try {
|
|
47
|
+
const { pathname } = new URL(url);
|
|
48
|
+
const dot = pathname.lastIndexOf(".");
|
|
49
|
+
return dot === -1 ? "" : pathname.slice(dot + 1).toLowerCase();
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
// Strip any directory components from a fal-provided file_name so a
|
|
56
|
+
// malicious response can't traverse out of the download target dir.
|
|
57
|
+
// Handle both POSIX and Windows separators regardless of host OS so a
|
|
58
|
+
// `..\\..\\evil` payload sent to a Linux client is still flattened.
|
|
59
|
+
const sanitizeFilename = (name) => {
|
|
60
|
+
const base = name
|
|
61
|
+
.replaceAll(/[\\/]+/gu, "/")
|
|
62
|
+
.split("/")
|
|
63
|
+
.pop() ?? "";
|
|
64
|
+
if (!base || base === "." || base === "..") {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
return base;
|
|
68
|
+
};
|
|
69
|
+
const visit = (value, refs, seen) => {
|
|
63
70
|
if (Array.isArray(value)) {
|
|
64
|
-
for (const v of value)
|
|
71
|
+
for (const v of value) {
|
|
65
72
|
visit(v, refs, seen);
|
|
73
|
+
}
|
|
66
74
|
return;
|
|
67
75
|
}
|
|
68
|
-
if (!isJsonObject(value))
|
|
76
|
+
if (!isJsonObject(value)) {
|
|
69
77
|
return;
|
|
70
|
-
|
|
78
|
+
}
|
|
79
|
+
const { url } = value;
|
|
71
80
|
if (isJsonString(url) && isTrustedFalContentHost(url) && !seen.has(url)) {
|
|
72
81
|
const contentType = isJsonString(value.content_type) ? value.content_type.toLowerCase() : null;
|
|
73
82
|
const filenameField = isJsonString(value.file_name) ? sanitizeFilename(value.file_name) : null;
|
|
74
|
-
const ext = filenameField
|
|
75
|
-
|
|
83
|
+
const ext = filenameField
|
|
84
|
+
? path.extname(filenameField).slice(1).toLowerCase()
|
|
85
|
+
: extFromUrl(url);
|
|
86
|
+
const looksMedia = contentType === null ? MEDIA_EXT.has(ext) : /^(?:image|video|audio)\//u.test(contentType);
|
|
76
87
|
if (looksMedia) {
|
|
77
88
|
seen.add(url);
|
|
78
89
|
refs.push({
|
|
79
|
-
url,
|
|
80
|
-
filename: filenameField ?? `output${ext ? "." + ext : ""}`,
|
|
81
90
|
contentType,
|
|
91
|
+
filename: filenameField ?? `output${ext ? `.${ext}` : ""}`,
|
|
92
|
+
url,
|
|
82
93
|
});
|
|
83
94
|
}
|
|
84
95
|
}
|
|
85
|
-
for (const child of Object.values(value))
|
|
96
|
+
for (const child of Object.values(value)) {
|
|
86
97
|
visit(child, refs, seen);
|
|
87
|
-
}
|
|
88
|
-
function extFromUrl(url) {
|
|
89
|
-
try {
|
|
90
|
-
const path = new URL(url).pathname;
|
|
91
|
-
const dot = path.lastIndexOf(".");
|
|
92
|
-
return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
|
|
93
|
-
}
|
|
94
|
-
catch {
|
|
95
|
-
return "";
|
|
96
98
|
}
|
|
97
|
-
}
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Walk a fal result payload and pull out anything that looks like a media
|
|
102
|
+
* output. fal endpoints embed outputs in objects shaped like
|
|
103
|
+
* `{ url, content_type, file_name, ... }`; we accept image/video/audio
|
|
104
|
+
* content types and also fall back to URL extension when content_type is
|
|
105
|
+
* absent (some endpoints omit it).
|
|
106
|
+
*/
|
|
107
|
+
export const extractMediaRefs = (result) => {
|
|
108
|
+
const seen = new Set();
|
|
109
|
+
const refs = [];
|
|
110
|
+
visit(result, refs, seen);
|
|
111
|
+
return refs;
|
|
112
|
+
};
|
|
98
113
|
// The extension each content type genuinely is. Only formats an agent is
|
|
99
114
|
// likely to hand to a decoder afterwards need an entry; anything absent is
|
|
100
115
|
// left alone rather than guessed at.
|
|
101
116
|
const EXT_FOR_CONTENT_TYPE = new Map(Object.entries({
|
|
102
|
-
"
|
|
117
|
+
"audio/mpeg": "mp3",
|
|
118
|
+
"audio/ogg": "ogg",
|
|
119
|
+
"audio/wav": "wav",
|
|
120
|
+
"image/avif": "avif",
|
|
121
|
+
"image/gif": "gif",
|
|
103
122
|
"image/jpeg": "jpg",
|
|
123
|
+
"image/png": "png",
|
|
104
124
|
"image/webp": "webp",
|
|
105
|
-
"image/gif": "gif",
|
|
106
|
-
"image/avif": "avif",
|
|
107
125
|
"video/mp4": "mp4",
|
|
108
|
-
"video/webm": "webm",
|
|
109
126
|
"video/quicktime": "mov",
|
|
110
|
-
"
|
|
111
|
-
"audio/wav": "wav",
|
|
112
|
-
"audio/ogg": "ogg",
|
|
127
|
+
"video/webm": "webm",
|
|
113
128
|
}));
|
|
114
129
|
// Extensions that name the same format, so `.jpg` for `image/jpeg` is not a lie.
|
|
115
130
|
const EXT_ALIASES = new Map(Object.entries({
|
|
131
|
+
htm: "html",
|
|
116
132
|
jpeg: "jpg",
|
|
117
133
|
tif: "tiff",
|
|
118
|
-
htm: "html",
|
|
119
134
|
}));
|
|
120
135
|
const canonicalExt = (ext) => EXT_ALIASES.get(ext) ?? ext;
|
|
121
136
|
/**
|
|
@@ -126,21 +141,82 @@ const canonicalExt = (ext) => EXT_ALIASES.get(ext) ?? ext;
|
|
|
126
141
|
* the file is a `.png` holding JPEG bytes. Downstream decoders reject it with
|
|
127
142
|
* "bad signature" and nothing points back here, hence the explicit report.
|
|
128
143
|
*/
|
|
129
|
-
|
|
130
|
-
const asked = canonicalExt(extname(target).slice(1).toLowerCase());
|
|
131
|
-
if (!asked)
|
|
144
|
+
const mislabelOf = (target, ref) => {
|
|
145
|
+
const asked = canonicalExt(path.extname(target).slice(1).toLowerCase());
|
|
146
|
+
if (!asked) {
|
|
132
147
|
return null;
|
|
148
|
+
}
|
|
133
149
|
const actual = ref.contentType ? EXT_FOR_CONTENT_TYPE.get(ref.contentType) : undefined;
|
|
134
|
-
if (!actual || canonicalExt(actual) === asked)
|
|
150
|
+
if (!actual || canonicalExt(actual) === asked) {
|
|
135
151
|
return null;
|
|
136
|
-
|
|
137
|
-
}
|
|
152
|
+
}
|
|
153
|
+
return { actual, path: target };
|
|
154
|
+
};
|
|
155
|
+
// Exported so the codex provider (lib/codex.ts) reuses identical
|
|
156
|
+
// `_1`/`_2` collision-suffix behavior when placing its local outputs.
|
|
157
|
+
export const disambiguateTargets = (paths) => {
|
|
158
|
+
const counts = new Map();
|
|
159
|
+
for (const p of paths) {
|
|
160
|
+
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
161
|
+
}
|
|
162
|
+
const seen = new Map();
|
|
163
|
+
return paths.map((p) => {
|
|
164
|
+
if ((counts.get(p) ?? 0) <= 1) {
|
|
165
|
+
return p;
|
|
166
|
+
}
|
|
167
|
+
const n = seen.get(p) ?? 0;
|
|
168
|
+
seen.set(p, n + 1);
|
|
169
|
+
if (n === 0) {
|
|
170
|
+
return p;
|
|
171
|
+
}
|
|
172
|
+
const ext = path.extname(p);
|
|
173
|
+
return `${p.slice(0, p.length - ext.length)}_${n}${ext}`;
|
|
174
|
+
});
|
|
175
|
+
};
|
|
176
|
+
const renderTemplate = (ref, template, index, requestId) => {
|
|
177
|
+
const ext = (() => {
|
|
178
|
+
const fromName = path.extname(ref.filename).slice(1);
|
|
179
|
+
if (fromName) {
|
|
180
|
+
return fromName;
|
|
181
|
+
}
|
|
182
|
+
return extFromUrl(ref.url) || "bin";
|
|
183
|
+
})();
|
|
184
|
+
// String-based stem extraction: a dynamic RegExp built from `ext`
|
|
185
|
+
// would treat any regex metachars in an unusual fal `file_name`
|
|
186
|
+
// (`.`, `+`, `*`) as patterns, potentially stripping the wrong
|
|
187
|
+
// suffix. Plain endsWith is exact and case-insensitive via toLowerCase.
|
|
188
|
+
const lowerName = ref.filename.toLowerCase();
|
|
189
|
+
const dotExt = `.${ext.toLowerCase()}`;
|
|
190
|
+
const stem = lowerName.endsWith(dotExt)
|
|
191
|
+
? ref.filename.slice(0, -dotExt.length) || "output"
|
|
192
|
+
: ref.filename || "output";
|
|
193
|
+
// No template or no placeholder → caller meant either a destination
|
|
194
|
+
// directory (omitted, ".", "./", "../out", "out/") or an explicit
|
|
195
|
+
// output filename (`./out.png`, `frame.mp4`). We disambiguate by
|
|
196
|
+
// looking for an extension on the basename — anything with one is
|
|
197
|
+
// treated as the literal output path; otherwise we resolve into the
|
|
198
|
+
// directory using the ref's filename. The previous all-as-dir
|
|
199
|
+
// behavior wrote `./walk.png/output.png` for `--download ./walk.png`.
|
|
200
|
+
if (!template || !template.includes("{")) {
|
|
201
|
+
if (template && path.extname(template)) {
|
|
202
|
+
return path.resolve(template);
|
|
203
|
+
}
|
|
204
|
+
const dir = template ?? process.cwd();
|
|
205
|
+
return path.resolve(dir, ref.filename || `output-${index}.${ext}`);
|
|
206
|
+
}
|
|
207
|
+
const rendered = template
|
|
208
|
+
.replaceAll("{index}", String(index))
|
|
209
|
+
.replaceAll("{name}", stem)
|
|
210
|
+
.replaceAll("{ext}", ext)
|
|
211
|
+
.replaceAll("{request_id}", requestId);
|
|
212
|
+
return path.resolve(rendered);
|
|
213
|
+
};
|
|
138
214
|
/**
|
|
139
215
|
* Download all extracted media refs to disk, materializing the path from
|
|
140
216
|
* a template. Supported placeholders: {index}, {name}, {ext}, {request_id}.
|
|
141
217
|
* Falls back to the source filename in the cwd when no template is given.
|
|
142
218
|
*/
|
|
143
|
-
export async
|
|
219
|
+
export const downloadMedia = async (opts) => {
|
|
144
220
|
const initial = opts.refs.map((ref, i) => renderTemplate(ref, opts.template, i, opts.requestId));
|
|
145
221
|
// Disambiguate any colliding resolved paths so multi-output runs (e.g.
|
|
146
222
|
// `--num_images 3` where fal returns the same default `file_name` for
|
|
@@ -149,25 +225,29 @@ export async function downloadMedia(opts) {
|
|
|
149
225
|
// `_1`, `_2`, … suffix inserted before the extension.
|
|
150
226
|
const targets = disambiguateTargets(initial);
|
|
151
227
|
// Create each unique parent directory once instead of redoing it per ref.
|
|
152
|
-
const dirs = new Set(targets.map((t) => dirname(t)));
|
|
153
|
-
for (const d of dirs)
|
|
228
|
+
const dirs = new Set(targets.map((t) => path.dirname(t)));
|
|
229
|
+
for (const d of dirs) {
|
|
154
230
|
mkdirSync(d, { recursive: true });
|
|
231
|
+
}
|
|
155
232
|
const outcomes = await Promise.all(opts.refs.map(async (ref, i) => {
|
|
156
233
|
const target = targets[i];
|
|
234
|
+
if (target === undefined) {
|
|
235
|
+
return { error: "no download target", ok: false, url: ref.url };
|
|
236
|
+
}
|
|
157
237
|
try {
|
|
158
238
|
const res = await fetch(ref.url);
|
|
159
239
|
if (!res.ok) {
|
|
160
|
-
return {
|
|
240
|
+
return { error: `${res.status} ${res.statusText}`, ok: false, url: ref.url };
|
|
161
241
|
}
|
|
162
242
|
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
163
243
|
writeFileSync(target, bytes);
|
|
164
|
-
return {
|
|
244
|
+
return { mislabel: mislabelOf(target, ref), ok: true, target };
|
|
165
245
|
}
|
|
166
|
-
catch (
|
|
246
|
+
catch (error) {
|
|
167
247
|
return {
|
|
248
|
+
error: error instanceof Error ? error.message : String(error),
|
|
168
249
|
ok: false,
|
|
169
250
|
url: ref.url,
|
|
170
|
-
error: err instanceof Error ? err.message : String(err),
|
|
171
251
|
};
|
|
172
252
|
}
|
|
173
253
|
}));
|
|
@@ -176,79 +256,13 @@ export async function downloadMedia(opts) {
|
|
|
176
256
|
const mislabeled = [];
|
|
177
257
|
for (const o of outcomes) {
|
|
178
258
|
if (!o.ok) {
|
|
179
|
-
failed.push({
|
|
259
|
+
failed.push({ error: o.error, url: o.url });
|
|
180
260
|
continue;
|
|
181
261
|
}
|
|
182
262
|
downloaded.push(o.target);
|
|
183
|
-
if (o.mislabel)
|
|
263
|
+
if (o.mislabel) {
|
|
184
264
|
mislabeled.push(o.mislabel);
|
|
265
|
+
}
|
|
185
266
|
}
|
|
186
267
|
return { downloaded, failed, mislabeled };
|
|
187
|
-
}
|
|
188
|
-
// Strip any directory components from a fal-provided file_name so a
|
|
189
|
-
// malicious response can't traverse out of the download target dir.
|
|
190
|
-
// Handle both POSIX and Windows separators regardless of host OS so a
|
|
191
|
-
// `..\\..\\evil` payload sent to a Linux client is still flattened.
|
|
192
|
-
function sanitizeFilename(name) {
|
|
193
|
-
const base = name
|
|
194
|
-
.replace(/[\\/]+/g, "/")
|
|
195
|
-
.split("/")
|
|
196
|
-
.pop() ?? "";
|
|
197
|
-
if (!base || base === "." || base === "..")
|
|
198
|
-
return null;
|
|
199
|
-
return base;
|
|
200
|
-
}
|
|
201
|
-
// Exported so the codex provider (lib/codex.ts) reuses identical
|
|
202
|
-
// `_1`/`_2` collision-suffix behavior when placing its local outputs.
|
|
203
|
-
export function disambiguateTargets(paths) {
|
|
204
|
-
const counts = new Map();
|
|
205
|
-
for (const p of paths)
|
|
206
|
-
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
207
|
-
const seen = new Map();
|
|
208
|
-
return paths.map((p) => {
|
|
209
|
-
if ((counts.get(p) ?? 0) <= 1)
|
|
210
|
-
return p;
|
|
211
|
-
const n = seen.get(p) ?? 0;
|
|
212
|
-
seen.set(p, n + 1);
|
|
213
|
-
if (n === 0)
|
|
214
|
-
return p;
|
|
215
|
-
const ext = extname(p);
|
|
216
|
-
return p.slice(0, p.length - ext.length) + `_${n}` + ext;
|
|
217
|
-
});
|
|
218
|
-
}
|
|
219
|
-
function renderTemplate(ref, template, index, requestId) {
|
|
220
|
-
const ext = (() => {
|
|
221
|
-
const fromName = extname(ref.filename).slice(1);
|
|
222
|
-
if (fromName)
|
|
223
|
-
return fromName;
|
|
224
|
-
return extFromUrl(ref.url) || "bin";
|
|
225
|
-
})();
|
|
226
|
-
// String-based stem extraction: a dynamic RegExp built from `ext`
|
|
227
|
-
// would treat any regex metachars in an unusual fal `file_name`
|
|
228
|
-
// (`.`, `+`, `*`) as patterns, potentially stripping the wrong
|
|
229
|
-
// suffix. Plain endsWith is exact and case-insensitive via toLowerCase.
|
|
230
|
-
const lowerName = ref.filename.toLowerCase();
|
|
231
|
-
const dotExt = "." + ext.toLowerCase();
|
|
232
|
-
const stem = lowerName.endsWith(dotExt)
|
|
233
|
-
? ref.filename.slice(0, -dotExt.length) || "output"
|
|
234
|
-
: ref.filename || "output";
|
|
235
|
-
// No template or no placeholder → caller meant either a destination
|
|
236
|
-
// directory (omitted, ".", "./", "../out", "out/") or an explicit
|
|
237
|
-
// output filename (`./out.png`, `frame.mp4`). We disambiguate by
|
|
238
|
-
// looking for an extension on the basename — anything with one is
|
|
239
|
-
// treated as the literal output path; otherwise we resolve into the
|
|
240
|
-
// directory using the ref's filename. The previous all-as-dir
|
|
241
|
-
// behavior wrote `./walk.png/output.png` for `--download ./walk.png`.
|
|
242
|
-
if (!template || !template.includes("{")) {
|
|
243
|
-
if (template && extname(template))
|
|
244
|
-
return resolve(template);
|
|
245
|
-
const dir = template ?? process.cwd();
|
|
246
|
-
return resolve(dir, ref.filename || `output-${index}.${ext}`);
|
|
247
|
-
}
|
|
248
|
-
const rendered = template
|
|
249
|
-
.replaceAll("{index}", String(index))
|
|
250
|
-
.replaceAll("{name}", stem)
|
|
251
|
-
.replaceAll("{ext}", ext)
|
|
252
|
-
.replaceAll("{request_id}", requestId);
|
|
253
|
-
return resolve(rendered);
|
|
254
|
-
}
|
|
268
|
+
};
|
package/dist/lib/media-poll.d.ts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import type { createClient } from "./api.js";
|
|
2
|
+
import type { JsonValue } from "./types.js";
|
|
3
3
|
type Client = ReturnType<typeof createClient>;
|
|
4
|
-
export declare
|
|
5
|
-
export declare
|
|
6
|
-
|
|
4
|
+
export declare const endpointPath: (endpointId: string) => string;
|
|
5
|
+
export declare const queueAppId: (endpointId: string) => string;
|
|
6
|
+
interface CompletedResult {
|
|
7
7
|
request_id: string;
|
|
8
8
|
result: JsonValue;
|
|
9
|
-
}
|
|
9
|
+
}
|
|
10
10
|
/**
|
|
11
11
|
* Poll fal's queue from the client side until the job reaches a
|
|
12
12
|
* terminal status, then fetch the result. The Worker isn't in the
|
|
13
13
|
* loop — it's only along for each individual `generate.forward` hop.
|
|
14
14
|
*/
|
|
15
|
-
export declare
|
|
15
|
+
export declare const waitForCompletion: (client: Client, endpoint_id: string, request_id: string, opts: {
|
|
16
16
|
quiet: boolean;
|
|
17
|
-
})
|
|
17
|
+
}) => Promise<CompletedResult>;
|
|
18
18
|
export {};
|
package/dist/lib/media-poll.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
|
+
import { consola } from "consola";
|
|
2
3
|
import { forwardJson } from "./api.js";
|
|
3
4
|
import { isJsonNumber, isJsonObject, isJsonString } from "./types.js";
|
|
4
5
|
// Strip leading/trailing slashes from a fal endpoint id so it can be
|
|
5
6
|
// spliced into a URL path without doubling separators.
|
|
6
|
-
export
|
|
7
|
-
return endpointId.replace(/^\/+|\/+$/g, "");
|
|
8
|
-
}
|
|
7
|
+
export const endpointPath = (endpointId) => endpointId.replaceAll(/^\/+|\/+$/gu, "");
|
|
9
8
|
// fal's queue accepts the full endpoint id (including any model subpath,
|
|
10
9
|
// e.g. `fal-ai/flux/schnell`) on submit, but the status/result/cancel
|
|
11
10
|
// routes are keyed by the owning *application* id only (`fal-ai/flux`).
|
|
@@ -13,22 +12,40 @@ export function endpointPath(endpointId) {
|
|
|
13
12
|
// ids carry the namespace as a leading segment, so their app id is three
|
|
14
13
|
// segments deep.
|
|
15
14
|
const QUEUE_APP_NAMESPACES = new Set(["workflows", "comfy"]);
|
|
16
|
-
export
|
|
15
|
+
export const queueAppId = (endpointId) => {
|
|
17
16
|
const parts = endpointPath(endpointId).split("/").filter(Boolean);
|
|
18
17
|
const take = QUEUE_APP_NAMESPACES.has(parts[0] ?? "") ? 3 : 2;
|
|
19
18
|
return parts.slice(0, take).join("/");
|
|
20
|
-
}
|
|
21
|
-
const POLL_INTERVAL_MS =
|
|
19
|
+
};
|
|
20
|
+
const POLL_INTERVAL_MS = 2000;
|
|
22
21
|
// 30-minute ceiling on a sync run. Generous (this is the user's local
|
|
23
22
|
// CLI process, not a billed Worker) but bounded so a stuck IN_QUEUE
|
|
24
23
|
// job can't hang the CLI indefinitely. Long jobs should use --async.
|
|
25
24
|
const POLL_TIMEOUT_MS = 30 * 60 * 1000;
|
|
25
|
+
const pickErrorReason = (value) => {
|
|
26
|
+
if (!isJsonObject(value)) {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
if (isJsonString(value.error) && value.error.length > 0) {
|
|
30
|
+
return value.error;
|
|
31
|
+
}
|
|
32
|
+
if (isJsonString(value.detail) && value.detail.length > 0) {
|
|
33
|
+
return value.detail;
|
|
34
|
+
}
|
|
35
|
+
if (isJsonObject(value.error) && isJsonString(value.error.message)) {
|
|
36
|
+
return value.error.message;
|
|
37
|
+
}
|
|
38
|
+
if (isJsonObject(value.response)) {
|
|
39
|
+
return pickErrorReason(value.response);
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
};
|
|
26
43
|
/**
|
|
27
44
|
* Poll fal's queue from the client side until the job reaches a
|
|
28
45
|
* terminal status, then fetch the result. The Worker isn't in the
|
|
29
46
|
* loop — it's only along for each individual `generate.forward` hop.
|
|
30
47
|
*/
|
|
31
|
-
export async
|
|
48
|
+
export const waitForCompletion = async (client, endpoint_id, request_id, opts) => {
|
|
32
49
|
const ep = queueAppId(endpoint_id);
|
|
33
50
|
const deadline = Date.now() + POLL_TIMEOUT_MS;
|
|
34
51
|
let lastStatus;
|
|
@@ -39,43 +56,31 @@ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
|
|
|
39
56
|
`Use \`vg generate status ${endpoint_id} ${request_id} --result\` to check later.`);
|
|
40
57
|
}
|
|
41
58
|
const raw = await forwardJson(client, {
|
|
42
|
-
target: "queue",
|
|
43
59
|
method: "GET",
|
|
44
60
|
path: `/${ep}/requests/${request_id}/status`,
|
|
61
|
+
target: "queue",
|
|
45
62
|
});
|
|
46
63
|
const status = isJsonObject(raw) && isJsonString(raw.status) ? raw.status : "UNKNOWN";
|
|
47
64
|
const upper = status.toUpperCase();
|
|
48
65
|
if (!opts.quiet && upper !== lastStatus) {
|
|
49
66
|
lastStatus = upper;
|
|
50
67
|
const queuePos = isJsonObject(raw) && isJsonNumber(raw.queue_position) ? raw.queue_position : null;
|
|
51
|
-
const tag = queuePos
|
|
68
|
+
const tag = queuePos === null ? upper.toLowerCase() : `${upper.toLowerCase()} (queue ${queuePos})`;
|
|
52
69
|
consola.log(` ${tag}`);
|
|
53
70
|
}
|
|
54
|
-
if (upper === "COMPLETED")
|
|
71
|
+
if (upper === "COMPLETED") {
|
|
55
72
|
break;
|
|
73
|
+
}
|
|
56
74
|
if (upper === "FAILED" || upper === "CANCELLED") {
|
|
57
75
|
const reason = pickErrorReason(raw);
|
|
58
76
|
throw new Error(reason ? `Job ${upper.toLowerCase()}: ${reason}` : `Job ${upper.toLowerCase()}`);
|
|
59
77
|
}
|
|
60
|
-
await
|
|
78
|
+
await sleep(POLL_INTERVAL_MS);
|
|
61
79
|
}
|
|
62
80
|
const result = await forwardJson(client, {
|
|
63
|
-
target: "queue",
|
|
64
81
|
method: "GET",
|
|
65
82
|
path: `/${ep}/requests/${request_id}`,
|
|
83
|
+
target: "queue",
|
|
66
84
|
});
|
|
67
85
|
return { request_id, result };
|
|
68
|
-
}
|
|
69
|
-
function pickErrorReason(value) {
|
|
70
|
-
if (!isJsonObject(value))
|
|
71
|
-
return null;
|
|
72
|
-
if (isJsonString(value.error) && value.error.length > 0)
|
|
73
|
-
return value.error;
|
|
74
|
-
if (isJsonString(value.detail) && value.detail.length > 0)
|
|
75
|
-
return value.detail;
|
|
76
|
-
if (isJsonObject(value.error) && isJsonString(value.error.message))
|
|
77
|
-
return value.error.message;
|
|
78
|
-
if (isJsonObject(value.response))
|
|
79
|
-
return pickErrorReason(value.response);
|
|
80
|
-
return null;
|
|
81
|
-
}
|
|
86
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { createClient } from "./api.js";
|
|
2
2
|
import type { LocalFile } from "./media-args.js";
|
|
3
3
|
type Client = ReturnType<typeof createClient>;
|
|
4
4
|
/**
|
|
@@ -8,5 +8,5 @@ type Client = ReturnType<typeof createClient>;
|
|
|
8
8
|
* through the worker. The returned file_url is a stable fal CDN URL
|
|
9
9
|
* that can be reused across runs without re-uploading.
|
|
10
10
|
*/
|
|
11
|
-
export declare
|
|
11
|
+
export declare const uploadFile: (client: Client, file: LocalFile) => Promise<string>;
|
|
12
12
|
export {};
|
package/dist/lib/media-upload.js
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
import { openAsBlob } from "node:fs";
|
|
2
2
|
import { forwardJson } from "./api.js";
|
|
3
3
|
import { isJsonObject, isJsonString } from "./types.js";
|
|
4
|
+
const pickUrl = (slot, key) => {
|
|
5
|
+
const value = isJsonObject(slot) ? slot[key] : undefined;
|
|
6
|
+
if (!isJsonString(value) || value.length === 0) {
|
|
7
|
+
throw new Error(`fal storage initiate response missing ${key}.`);
|
|
8
|
+
}
|
|
9
|
+
// Refuse any non-HTTPS URL even if it comes from a trusted server
|
|
10
|
+
// response — a misconfigured response (or a downgrade attack on the
|
|
11
|
+
// proxy hop) must not silently send user bytes over plain HTTP, and
|
|
12
|
+
// file_url gets passed into later runs where it should stay HTTPS.
|
|
13
|
+
let parsed;
|
|
14
|
+
try {
|
|
15
|
+
parsed = new URL(value);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new Error(`fal storage initiate response ${key} is not a valid URL.`);
|
|
19
|
+
}
|
|
20
|
+
if (parsed.protocol !== "https:") {
|
|
21
|
+
throw new Error(`fal storage initiate response ${key} must be HTTPS, got ${parsed.protocol}.`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
};
|
|
4
25
|
/**
|
|
5
26
|
* Upload one local file directly to fal's CDN. The proxy hands us a
|
|
6
27
|
* presigned upload slot (upload_url + file_url) via the `generate.forward`
|
|
@@ -8,45 +29,24 @@ import { isJsonObject, isJsonString } from "./types.js";
|
|
|
8
29
|
* through the worker. The returned file_url is a stable fal CDN URL
|
|
9
30
|
* that can be reused across runs without re-uploading.
|
|
10
31
|
*/
|
|
11
|
-
export async
|
|
32
|
+
export const uploadFile = async (client, file) => {
|
|
12
33
|
const slot = await forwardJson(client, {
|
|
13
|
-
|
|
34
|
+
body: { content_type: file.contentType, file_name: file.filename },
|
|
14
35
|
method: "POST",
|
|
15
36
|
path: "/storage/upload/initiate",
|
|
16
|
-
|
|
37
|
+
target: "storage",
|
|
17
38
|
});
|
|
18
39
|
const uploadUrl = pickUrl(slot, "upload_url");
|
|
19
40
|
const fileUrl = pickUrl(slot, "file_url");
|
|
20
41
|
const body = await openAsBlob(file.path, { type: file.contentType });
|
|
21
42
|
const res = await fetch(uploadUrl, {
|
|
22
|
-
method: "PUT",
|
|
23
|
-
headers: { "Content-Type": file.contentType },
|
|
24
43
|
body,
|
|
44
|
+
headers: { "Content-Type": file.contentType },
|
|
45
|
+
method: "PUT",
|
|
25
46
|
});
|
|
26
47
|
if (!res.ok) {
|
|
27
48
|
const text = await res.text().catch(() => "");
|
|
28
49
|
throw new Error(`Upload failed for ${file.filename}: ${res.status} ${res.statusText} ${text}`);
|
|
29
50
|
}
|
|
30
51
|
return fileUrl;
|
|
31
|
-
}
|
|
32
|
-
function pickUrl(slot, key) {
|
|
33
|
-
const value = isJsonObject(slot) ? slot[key] : undefined;
|
|
34
|
-
if (!isJsonString(value) || value.length === 0) {
|
|
35
|
-
throw new Error(`fal storage initiate response missing ${key}.`);
|
|
36
|
-
}
|
|
37
|
-
// Refuse any non-HTTPS URL even if it comes from a trusted server
|
|
38
|
-
// response — a misconfigured response (or a downgrade attack on the
|
|
39
|
-
// proxy hop) must not silently send user bytes over plain HTTP, and
|
|
40
|
-
// file_url gets passed into later runs where it should stay HTTPS.
|
|
41
|
-
let parsed;
|
|
42
|
-
try {
|
|
43
|
-
parsed = new URL(value);
|
|
44
|
-
}
|
|
45
|
-
catch {
|
|
46
|
-
throw new Error(`fal storage initiate response ${key} is not a valid URL.`);
|
|
47
|
-
}
|
|
48
|
-
if (parsed.protocol !== "https:") {
|
|
49
|
-
throw new Error(`fal storage initiate response ${key} must be HTTPS, got ${parsed.protocol}.`);
|
|
50
|
-
}
|
|
51
|
-
return value;
|
|
52
|
-
}
|
|
52
|
+
};
|