vibedgames 0.0.3 → 0.0.5
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/README.md +7 -2
- package/dist/.tsbuildinfo +1 -0
- package/dist/commands/completions.d.ts +7 -0
- package/dist/commands/completions.js +138 -0
- package/dist/commands/deploy.d.ts +14 -9
- package/dist/commands/deploy.js +63 -3
- package/dist/commands/fork.d.ts +26 -0
- package/dist/commands/fork.js +118 -0
- package/dist/commands/init.d.ts +15 -15
- package/dist/commands/login.js +2 -2
- package/dist/commands/media.d.ts +1 -0
- package/dist/commands/media.js +401 -0
- package/dist/commands/new.d.ts +26 -0
- package/dist/commands/new.js +229 -0
- package/dist/index.js +8 -0
- package/dist/lib/api.js +14 -7
- package/dist/lib/archive.d.ts +17 -0
- package/dist/lib/archive.js +110 -0
- package/dist/lib/config-file.d.ts +3 -0
- package/dist/lib/config-file.js +24 -3
- package/dist/lib/config.js +5 -4
- package/dist/lib/media-args.d.ts +28 -0
- package/dist/lib/media-args.js +199 -0
- package/dist/lib/media-download.d.ts +31 -0
- package/dist/lib/media-download.js +190 -0
- package/dist/lib/media-poll.d.ts +17 -0
- package/dist/lib/media-poll.js +80 -0
- package/dist/lib/media-upload.d.ts +12 -0
- package/dist/lib/media-upload.js +51 -0
- package/dist/lib/types.d.ts +2 -0
- package/dist/lib/types.js +4 -0
- package/package.json +13 -9
- package/dist/commands/list.d.ts +0 -1
- package/dist/commands/list.js +0 -23
- package/dist/commands/rm.d.ts +0 -12
- package/dist/commands/rm.js +0 -35
- package/dist/commands/skills.d.ts +0 -8
- package/dist/commands/skills.js +0 -53
- package/dist/prompt-E6QYABXJ.js +0 -754
package/dist/lib/api.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createTRPCClient, httpBatchLink } from "@trpc/client";
|
|
1
|
+
import { createTRPCClient, httpBatchLink, httpLink, splitLink } from "@trpc/client";
|
|
2
2
|
import superjson from "superjson";
|
|
3
3
|
import { getBaseUrl, getToken } from "./config.js";
|
|
4
4
|
/** Authenticated client — requires a saved session token. */
|
|
@@ -7,20 +7,27 @@ export function createClient() {
|
|
|
7
7
|
if (!token) {
|
|
8
8
|
throw new Error("Not logged in. Run `vg login` to authenticate.");
|
|
9
9
|
}
|
|
10
|
+
const url = `${getBaseUrl()}/api/trpc`;
|
|
11
|
+
const headers = () => ({ Authorization: `Bearer ${token}` });
|
|
10
12
|
return createTRPCClient({
|
|
11
13
|
links: [
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}),
|
|
14
|
+
// Media input bytes use presigned uploads, but mutations can still
|
|
15
|
+
// carry model params. Keep writes off httpBatchLink so one batch
|
|
16
|
+
// body cannot grow with concurrent calls.
|
|
17
|
+
splitLink({
|
|
18
|
+
condition: (op) => op.type === "mutation",
|
|
19
|
+
true: httpLink({ url, transformer: superjson, headers }),
|
|
20
|
+
false: httpBatchLink({ url, transformer: superjson, headers }),
|
|
18
21
|
}),
|
|
19
22
|
],
|
|
20
23
|
});
|
|
21
24
|
}
|
|
22
25
|
/** Unauthenticated client — for login flow. */
|
|
23
26
|
export function createPublicClient(baseUrl) {
|
|
27
|
+
// The login-flow procedures carry no large payloads, so the plain
|
|
28
|
+
// batch link is fine here — no need for the splitLink dance the
|
|
29
|
+
// authenticated client uses to keep `media.run` mutations off the
|
|
30
|
+
// batched path.
|
|
24
31
|
return createTRPCClient({
|
|
25
32
|
links: [
|
|
26
33
|
httpBatchLink({
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type SourceArchive = {
|
|
2
|
+
/** absolute path to the temp .tgz */
|
|
3
|
+
path: string;
|
|
4
|
+
sha256: string;
|
|
5
|
+
bytes: number;
|
|
6
|
+
/** posix relative paths included, for display */
|
|
7
|
+
files: string[];
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Create a gzipped tar of `root`'s source (respecting .gitignore +
|
|
11
|
+
* HARD_EXCLUDES) at a temp path. Returns the archive path, its sha256, byte
|
|
12
|
+
* size, and the list of included files.
|
|
13
|
+
*/
|
|
14
|
+
export declare function packSource(root: string, tmpDir: string): Promise<SourceArchive>;
|
|
15
|
+
/** Extract a gzipped tar into `destDir` (created if needed). tar strips
|
|
16
|
+
* leading slashes and rejects `..` paths, so extraction stays inside dest. */
|
|
17
|
+
export declare function extractSource(archivePath: string, destDir: string): Promise<void>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { join, relative, sep } from "node:path";
|
|
4
|
+
import ignore from "ignore";
|
|
5
|
+
import { create as tarCreate, extract as tarExtract } from "tar";
|
|
6
|
+
/**
|
|
7
|
+
* Patterns ALWAYS excluded from a source archive, regardless of .gitignore —
|
|
8
|
+
* build output, VCS internals, and (critically) secrets. Source upload is a
|
|
9
|
+
* publish: anything left in the folder becomes forkable by anyone.
|
|
10
|
+
*/
|
|
11
|
+
const HARD_EXCLUDES = [
|
|
12
|
+
"node_modules",
|
|
13
|
+
".git",
|
|
14
|
+
"dist",
|
|
15
|
+
"build",
|
|
16
|
+
".next",
|
|
17
|
+
".turbo",
|
|
18
|
+
".cache",
|
|
19
|
+
".vercel",
|
|
20
|
+
".wrangler",
|
|
21
|
+
"coverage",
|
|
22
|
+
".DS_Store",
|
|
23
|
+
"*.log",
|
|
24
|
+
// secrets — never ship these
|
|
25
|
+
".env",
|
|
26
|
+
".env.*",
|
|
27
|
+
"*.pem",
|
|
28
|
+
"*.key",
|
|
29
|
+
"*.p12",
|
|
30
|
+
"*.pfx",
|
|
31
|
+
"id_rsa",
|
|
32
|
+
"id_dsa",
|
|
33
|
+
"id_ecdsa",
|
|
34
|
+
"id_ed25519",
|
|
35
|
+
".npmrc",
|
|
36
|
+
".git-credentials",
|
|
37
|
+
// archives (avoid bundling our own output)
|
|
38
|
+
"*.tgz",
|
|
39
|
+
"*.tar.gz",
|
|
40
|
+
];
|
|
41
|
+
/**
|
|
42
|
+
* Build the exclusion predicate. HARD_EXCLUDES live in their OWN matcher,
|
|
43
|
+
* checked independently of the user's .gitignore/.vibedgamesignore — so a
|
|
44
|
+
* negation like `!.env` in a user ignore file can NOT un-exclude a secret.
|
|
45
|
+
* A path is excluded if EITHER matcher says so.
|
|
46
|
+
*/
|
|
47
|
+
function buildIgnorer(root) {
|
|
48
|
+
const hard = ignore().add(HARD_EXCLUDES);
|
|
49
|
+
const user = ignore();
|
|
50
|
+
for (const name of [".gitignore", ".vibedgamesignore"]) {
|
|
51
|
+
const p = join(root, name);
|
|
52
|
+
if (existsSync(p))
|
|
53
|
+
user.add(readFileSync(p, "utf8"));
|
|
54
|
+
}
|
|
55
|
+
return (rel) => hard.ignores(rel) || user.ignores(rel);
|
|
56
|
+
}
|
|
57
|
+
/** Walk `root`, returning posix relative paths of files not ignored. Ignored
|
|
58
|
+
* directories are pruned (not descended into) for speed. */
|
|
59
|
+
function collectFiles(root, ignored) {
|
|
60
|
+
const out = [];
|
|
61
|
+
const walk = (dir) => {
|
|
62
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
63
|
+
const abs = join(dir, entry.name);
|
|
64
|
+
const rel = relative(root, abs).split(sep).join("/");
|
|
65
|
+
if (!rel)
|
|
66
|
+
continue;
|
|
67
|
+
// `ignore` matches dirs via a trailing slash; test both forms.
|
|
68
|
+
if (entry.isDirectory()) {
|
|
69
|
+
if (ignored(`${rel}/`) || ignored(rel))
|
|
70
|
+
continue;
|
|
71
|
+
walk(abs);
|
|
72
|
+
}
|
|
73
|
+
else if (entry.isFile()) {
|
|
74
|
+
if (ignored(rel))
|
|
75
|
+
continue;
|
|
76
|
+
out.push(rel);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
walk(root);
|
|
81
|
+
return out.sort();
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Create a gzipped tar of `root`'s source (respecting .gitignore +
|
|
85
|
+
* HARD_EXCLUDES) at a temp path. Returns the archive path, its sha256, byte
|
|
86
|
+
* size, and the list of included files.
|
|
87
|
+
*/
|
|
88
|
+
export async function packSource(root, tmpDir) {
|
|
89
|
+
const ignored = buildIgnorer(root);
|
|
90
|
+
const files = collectFiles(root, ignored);
|
|
91
|
+
if (files.length === 0) {
|
|
92
|
+
throw new Error("No source files to archive (everything was ignored?).");
|
|
93
|
+
}
|
|
94
|
+
mkdirSync(tmpDir, { recursive: true });
|
|
95
|
+
const path = join(tmpDir, `vg-source-${process.pid}-${files.length}.tgz`);
|
|
96
|
+
await tarCreate({ gzip: true, file: path, cwd: root, portable: true }, files);
|
|
97
|
+
const buf = readFileSync(path);
|
|
98
|
+
return {
|
|
99
|
+
path,
|
|
100
|
+
sha256: createHash("sha256").update(buf).digest("hex"),
|
|
101
|
+
bytes: statSync(path).size,
|
|
102
|
+
files,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** Extract a gzipped tar into `destDir` (created if needed). tar strips
|
|
106
|
+
* leading slashes and rejects `..` paths, so extraction stays inside dest. */
|
|
107
|
+
export async function extractSource(archivePath, destDir) {
|
|
108
|
+
mkdirSync(destDir, { recursive: true });
|
|
109
|
+
await tarExtract({ file: archivePath, cwd: destDir });
|
|
110
|
+
}
|
|
@@ -2,6 +2,9 @@ export type ProjectConfig = {
|
|
|
2
2
|
slug: string;
|
|
3
3
|
name?: string;
|
|
4
4
|
};
|
|
5
|
+
/** The directory containing the nearest vibedgames.json at or above `dir`,
|
|
6
|
+
* or null if none — i.e. the project root to archive as forkable source. */
|
|
7
|
+
export declare function findProjectRoot(dir: string): string | null;
|
|
5
8
|
export declare function readProjectConfig(dir: string): ProjectConfig | null;
|
|
6
9
|
export declare function writeProjectConfig(dir: string, config: ProjectConfig): void;
|
|
7
10
|
export declare function projectConfigPath(dir: string): string;
|
package/dist/lib/config-file.js
CHANGED
|
@@ -1,9 +1,30 @@
|
|
|
1
1
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { join } from "node:path";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
3
|
const FILENAME = "vibedgames.json";
|
|
4
|
+
// Walk from `dir` up toward the filesystem root, stopping at the first
|
|
5
|
+
// vibedgames.json. Lets `vg deploy ./dist` pick up the config from the
|
|
6
|
+
// project root even when the build step doesn't copy it into the output.
|
|
7
|
+
function findConfigPath(dir) {
|
|
8
|
+
let current = resolve(dir);
|
|
9
|
+
while (true) {
|
|
10
|
+
const candidate = join(current, FILENAME);
|
|
11
|
+
if (existsSync(candidate))
|
|
12
|
+
return candidate;
|
|
13
|
+
const parent = dirname(current);
|
|
14
|
+
if (parent === current)
|
|
15
|
+
return null;
|
|
16
|
+
current = parent;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** The directory containing the nearest vibedgames.json at or above `dir`,
|
|
20
|
+
* or null if none — i.e. the project root to archive as forkable source. */
|
|
21
|
+
export function findProjectRoot(dir) {
|
|
22
|
+
const path = findConfigPath(dir);
|
|
23
|
+
return path ? dirname(path) : null;
|
|
24
|
+
}
|
|
4
25
|
export function readProjectConfig(dir) {
|
|
5
|
-
const path =
|
|
6
|
-
if (!
|
|
26
|
+
const path = findConfigPath(dir);
|
|
27
|
+
if (!path)
|
|
7
28
|
return null;
|
|
8
29
|
const raw = readFileSync(path, "utf-8");
|
|
9
30
|
const parsed = JSON.parse(raw);
|
package/dist/lib/config.js
CHANGED
|
@@ -36,10 +36,11 @@ export function clearConfig() {
|
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
export function getBaseUrl() {
|
|
39
|
-
return
|
|
40
|
-
getConfig()?.baseUrl ??
|
|
41
|
-
"https://vibedgames.com");
|
|
39
|
+
return process.env.VG_API_URL ?? getConfig()?.baseUrl ?? "https://vibedgames.com";
|
|
42
40
|
}
|
|
43
41
|
export function getToken() {
|
|
44
|
-
|
|
42
|
+
// VG_TOKEN lets local/CI runs authenticate without touching the saved
|
|
43
|
+
// login (e.g. a seeded dev session), so headless testing never clobbers
|
|
44
|
+
// the user's real `vg login` credentials.
|
|
45
|
+
return process.env.VG_TOKEN ?? getConfig()?.token ?? null;
|
|
45
46
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
|
|
3
|
+
* values that look like JSON (true/false/null/numbers/objects/arrays) and
|
|
4
|
+
* leaving everything else as a string. Mirrors genmedia's parse-value
|
|
5
|
+
* behavior so skills targeting that surface produce the same input shapes.
|
|
6
|
+
*
|
|
7
|
+
* Handles both `--key value` and the GNU-style `--key=value`. Without
|
|
8
|
+
* `=` support, `--prompt=hello` would silently send the malformed key
|
|
9
|
+
* `"prompt=hello"` to fal, and `--async=true` would slip past the
|
|
10
|
+
* RUN_RESERVED_FLAGS guard as a bogus model param.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseRunInput(argv: string[]): Record<string, unknown>;
|
|
13
|
+
export type LocalFile = {
|
|
14
|
+
path: string;
|
|
15
|
+
filename: string;
|
|
16
|
+
contentType: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Probe a path the user explicitly asked us to read (e.g.
|
|
20
|
+
* `vg media upload <path>`). Skips the path-shape heuristic so a bare
|
|
21
|
+
* filename with a non-media extension — `model.glb`, `scene.fbx`,
|
|
22
|
+
* `data.ply`, even `LICENSE` — still works.
|
|
23
|
+
*/
|
|
24
|
+
export declare function readExplicitLocalFile(value: string): LocalFile | null;
|
|
25
|
+
export declare function parseDownloadFlag(argv: string[]): {
|
|
26
|
+
mode: "off" | "on";
|
|
27
|
+
template?: string;
|
|
28
|
+
};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, extname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
// `--json`/`--help`/`--quiet` are global; `--async` switches the run path
|
|
5
|
+
// in citty; `--download` takes an optional template. None of them should
|
|
6
|
+
// leak through to fal as model parameters. `--logs` is intentionally NOT
|
|
7
|
+
// here: it's a `vg media status` flag, not a `run` flag, so swallowing it
|
|
8
|
+
// would block users from passing a legitimate `logs` parameter to a
|
|
9
|
+
// model endpoint.
|
|
10
|
+
const RUN_RESERVED_FLAGS = new Set([
|
|
11
|
+
"--json",
|
|
12
|
+
"--help",
|
|
13
|
+
"--quiet",
|
|
14
|
+
"--async",
|
|
15
|
+
"--download",
|
|
16
|
+
]);
|
|
17
|
+
/**
|
|
18
|
+
* Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
|
|
19
|
+
* values that look like JSON (true/false/null/numbers/objects/arrays) and
|
|
20
|
+
* leaving everything else as a string. Mirrors genmedia's parse-value
|
|
21
|
+
* behavior so skills targeting that surface produce the same input shapes.
|
|
22
|
+
*
|
|
23
|
+
* Handles both `--key value` and the GNU-style `--key=value`. Without
|
|
24
|
+
* `=` support, `--prompt=hello` would silently send the malformed key
|
|
25
|
+
* `"prompt=hello"` to fal, and `--async=true` would slip past the
|
|
26
|
+
* RUN_RESERVED_FLAGS guard as a bogus model param.
|
|
27
|
+
*/
|
|
28
|
+
export function parseRunInput(argv) {
|
|
29
|
+
const out = {};
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const arg = argv[i];
|
|
32
|
+
if (!arg || !arg.startsWith("--"))
|
|
33
|
+
continue;
|
|
34
|
+
// POSIX `--` argument terminator: stop interpreting subsequent
|
|
35
|
+
// tokens as flags. Without this guard, `--` itself parses as
|
|
36
|
+
// `{ "": <next token> }` and pollutes the request body.
|
|
37
|
+
if (arg === "--")
|
|
38
|
+
break;
|
|
39
|
+
const eqIdx = arg.indexOf("=");
|
|
40
|
+
const name = eqIdx === -1 ? arg : arg.slice(0, eqIdx);
|
|
41
|
+
const inlineValue = eqIdx === -1 ? undefined : arg.slice(eqIdx + 1);
|
|
42
|
+
if (RUN_RESERVED_FLAGS.has(name)) {
|
|
43
|
+
// --download (without inline value) optionally consumes the next
|
|
44
|
+
// token as its template. With `--download=foo` the value is
|
|
45
|
+
// already attached and we move on without skipping anything.
|
|
46
|
+
if (name === "--download" && inlineValue === undefined) {
|
|
47
|
+
const next = argv[i + 1];
|
|
48
|
+
if (next && !next.startsWith("--"))
|
|
49
|
+
i++;
|
|
50
|
+
}
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const key = name.slice(2);
|
|
54
|
+
if (inlineValue !== undefined) {
|
|
55
|
+
assign(out, key, parseValue(inlineValue));
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const next = argv[i + 1];
|
|
59
|
+
if (next === undefined || next.startsWith("--")) {
|
|
60
|
+
assign(out, key, true);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
assign(out, key, parseValue(next));
|
|
64
|
+
i++;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
function assign(out, key, value) {
|
|
69
|
+
if (key in out) {
|
|
70
|
+
const existing = out[key];
|
|
71
|
+
if (Array.isArray(existing))
|
|
72
|
+
existing.push(value);
|
|
73
|
+
else
|
|
74
|
+
out[key] = [existing, value];
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
out[key] = value;
|
|
78
|
+
}
|
|
79
|
+
function parseValue(raw) {
|
|
80
|
+
if (raw === "true")
|
|
81
|
+
return true;
|
|
82
|
+
if (raw === "false")
|
|
83
|
+
return false;
|
|
84
|
+
if (raw === "null")
|
|
85
|
+
return null;
|
|
86
|
+
if (raw.length > 0 && (raw[0] === "{" || raw[0] === "[")) {
|
|
87
|
+
try {
|
|
88
|
+
return JSON.parse(raw);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return raw;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (/^-?\d+(\.\d+)?$/.test(raw)) {
|
|
95
|
+
const n = Number(raw);
|
|
96
|
+
if (Number.isFinite(n))
|
|
97
|
+
return n;
|
|
98
|
+
}
|
|
99
|
+
return raw;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Probe a path the user explicitly asked us to read (e.g.
|
|
103
|
+
* `vg media upload <path>`). Skips the path-shape heuristic so a bare
|
|
104
|
+
* filename with a non-media extension — `model.glb`, `scene.fbx`,
|
|
105
|
+
* `data.ply`, even `LICENSE` — still works.
|
|
106
|
+
*/
|
|
107
|
+
export function readExplicitLocalFile(value) {
|
|
108
|
+
if (value.startsWith("http://") || value.startsWith("https://"))
|
|
109
|
+
return null;
|
|
110
|
+
if (value.startsWith("data:"))
|
|
111
|
+
return null;
|
|
112
|
+
if (value.length === 0)
|
|
113
|
+
return null;
|
|
114
|
+
const expanded = expandHome(value);
|
|
115
|
+
const abs = isAbsolute(expanded) ? expanded : resolve(expanded);
|
|
116
|
+
let stat;
|
|
117
|
+
try {
|
|
118
|
+
stat = statSync(abs);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (!stat.isFile())
|
|
124
|
+
return null;
|
|
125
|
+
return {
|
|
126
|
+
path: abs,
|
|
127
|
+
filename: basename(abs),
|
|
128
|
+
contentType: contentTypeForPath(abs),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function expandHome(value) {
|
|
132
|
+
// node:path's resolve() doesn't expand `~` — that's a shell feature.
|
|
133
|
+
// We expand it ourselves so quoted paths like `"~/photo.png"` work.
|
|
134
|
+
if (value === "~")
|
|
135
|
+
return homedir();
|
|
136
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
|
137
|
+
return join(homedir(), value.slice(2));
|
|
138
|
+
}
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
function contentTypeForPath(path) {
|
|
142
|
+
// extname splits on basename, so a dotted directory like
|
|
143
|
+
// "/home/user/my.project/texture" correctly yields "" instead of
|
|
144
|
+
// mistaking "project/texture" for the extension.
|
|
145
|
+
const ext = extname(path).slice(1).toLowerCase();
|
|
146
|
+
const map = {
|
|
147
|
+
png: "image/png",
|
|
148
|
+
jpg: "image/jpeg",
|
|
149
|
+
jpeg: "image/jpeg",
|
|
150
|
+
webp: "image/webp",
|
|
151
|
+
gif: "image/gif",
|
|
152
|
+
bmp: "image/bmp",
|
|
153
|
+
tif: "image/tiff",
|
|
154
|
+
tiff: "image/tiff",
|
|
155
|
+
avif: "image/avif",
|
|
156
|
+
mp4: "video/mp4",
|
|
157
|
+
mov: "video/quicktime",
|
|
158
|
+
webm: "video/webm",
|
|
159
|
+
mp3: "audio/mpeg",
|
|
160
|
+
wav: "audio/wav",
|
|
161
|
+
ogg: "audio/ogg",
|
|
162
|
+
flac: "audio/flac",
|
|
163
|
+
m4a: "audio/mp4",
|
|
164
|
+
txt: "text/plain",
|
|
165
|
+
json: "application/json",
|
|
166
|
+
};
|
|
167
|
+
return map[ext] ?? "application/octet-stream";
|
|
168
|
+
}
|
|
169
|
+
export function parseDownloadFlag(argv) {
|
|
170
|
+
let lastIdx = -1;
|
|
171
|
+
let inlineValue;
|
|
172
|
+
for (let i = 0; i < argv.length; i++) {
|
|
173
|
+
const arg = argv[i];
|
|
174
|
+
if (!arg)
|
|
175
|
+
continue;
|
|
176
|
+
if (arg === "--")
|
|
177
|
+
break;
|
|
178
|
+
if (arg === "--download") {
|
|
179
|
+
lastIdx = i;
|
|
180
|
+
inlineValue = undefined;
|
|
181
|
+
}
|
|
182
|
+
else if (arg.startsWith("--download=")) {
|
|
183
|
+
lastIdx = i;
|
|
184
|
+
inlineValue = arg.slice("--download=".length);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (lastIdx === -1)
|
|
188
|
+
return { mode: "off" };
|
|
189
|
+
const candidate = inlineValue ?? argv[lastIdx + 1];
|
|
190
|
+
if (candidate === "false")
|
|
191
|
+
return { mode: "off" };
|
|
192
|
+
if (candidate === undefined ||
|
|
193
|
+
candidate === "" ||
|
|
194
|
+
candidate.startsWith("--") ||
|
|
195
|
+
candidate === "true") {
|
|
196
|
+
return { mode: "on" };
|
|
197
|
+
}
|
|
198
|
+
return { mode: "on", template: candidate };
|
|
199
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
type MediaRef = {
|
|
2
|
+
url: string;
|
|
3
|
+
filename: string;
|
|
4
|
+
contentType: string | null;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Walk a fal result payload and pull out anything that looks like a media
|
|
8
|
+
* output. fal endpoints embed outputs in objects shaped like
|
|
9
|
+
* `{ url, content_type, file_name, ... }`; we accept image/video/audio
|
|
10
|
+
* content types and also fall back to URL extension when content_type is
|
|
11
|
+
* absent (some endpoints omit it).
|
|
12
|
+
*/
|
|
13
|
+
export declare function extractMediaRefs(result: unknown): MediaRef[];
|
|
14
|
+
type DownloadResult = {
|
|
15
|
+
downloaded: string[];
|
|
16
|
+
failed: {
|
|
17
|
+
url: string;
|
|
18
|
+
error: string;
|
|
19
|
+
}[];
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Download all extracted media refs to disk, materializing the path from
|
|
23
|
+
* a template. Supported placeholders: {index}, {name}, {ext}, {request_id}.
|
|
24
|
+
* Falls back to the source filename in the cwd when no template is given.
|
|
25
|
+
*/
|
|
26
|
+
export declare function downloadMedia(opts: {
|
|
27
|
+
refs: MediaRef[];
|
|
28
|
+
template?: string;
|
|
29
|
+
requestId: string;
|
|
30
|
+
}): Promise<DownloadResult>;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, extname, resolve } from "node:path";
|
|
3
|
+
import { isRecord } from "./types.js";
|
|
4
|
+
// Lowercase file extensions we recognize as media when sniffing fal
|
|
5
|
+
// response payloads where `content_type` is missing (some endpoints
|
|
6
|
+
// omit it).
|
|
7
|
+
const MEDIA_EXT = new Set([
|
|
8
|
+
"png", "jpg", "jpeg", "webp", "gif", "bmp", "tif", "tiff", "avif",
|
|
9
|
+
"mp4", "mov", "webm", "mp3", "wav", "ogg", "flac", "m4a",
|
|
10
|
+
]);
|
|
11
|
+
/**
|
|
12
|
+
* Walk a fal result payload and pull out anything that looks like a media
|
|
13
|
+
* output. fal endpoints embed outputs in objects shaped like
|
|
14
|
+
* `{ url, content_type, file_name, ... }`; we accept image/video/audio
|
|
15
|
+
* content types and also fall back to URL extension when content_type is
|
|
16
|
+
* absent (some endpoints omit it).
|
|
17
|
+
*/
|
|
18
|
+
export function extractMediaRefs(result) {
|
|
19
|
+
const seen = new Set();
|
|
20
|
+
const refs = [];
|
|
21
|
+
visit(result, refs, seen);
|
|
22
|
+
return refs;
|
|
23
|
+
}
|
|
24
|
+
// fal stores generated outputs on its own CDN (`X-Fal-Store-IO: 1`) and
|
|
25
|
+
// always serves them over HTTPS. Restrict `--download` candidates to
|
|
26
|
+
// those hosts and that scheme so a fal response can't trick the CLI
|
|
27
|
+
// into fetching arbitrary URLs (e.g. attacker-controlled or
|
|
28
|
+
// internal-network targets) on the user's machine, and can't downgrade
|
|
29
|
+
// to plain HTTP.
|
|
30
|
+
const TRUSTED_HOST_SUFFIXES = [".fal.media", ".fal.run", ".fal.ai"];
|
|
31
|
+
const TRUSTED_HOSTS = new Set(["fal.media", "fal.run", "fal.ai"]);
|
|
32
|
+
function isTrustedFalContentHost(url) {
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = new URL(url);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if (parsed.protocol !== "https:")
|
|
41
|
+
return false;
|
|
42
|
+
const host = parsed.hostname.toLowerCase();
|
|
43
|
+
if (TRUSTED_HOSTS.has(host))
|
|
44
|
+
return true;
|
|
45
|
+
return TRUSTED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));
|
|
46
|
+
}
|
|
47
|
+
function visit(value, refs, seen) {
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
for (const v of value)
|
|
50
|
+
visit(v, refs, seen);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (!isRecord(value))
|
|
54
|
+
return;
|
|
55
|
+
const url = value.url;
|
|
56
|
+
if (typeof url === "string" && isTrustedFalContentHost(url) && !seen.has(url)) {
|
|
57
|
+
const contentType = typeof value.content_type === "string" ? value.content_type.toLowerCase() : null;
|
|
58
|
+
const filenameField = typeof value.file_name === "string" ? sanitizeFilename(value.file_name) : null;
|
|
59
|
+
const ext = filenameField ? extname(filenameField).slice(1).toLowerCase() : extFromUrl(url);
|
|
60
|
+
const looksMedia = contentType !== null ? /^(image|video|audio)\//.test(contentType) : MEDIA_EXT.has(ext);
|
|
61
|
+
if (looksMedia) {
|
|
62
|
+
seen.add(url);
|
|
63
|
+
refs.push({
|
|
64
|
+
url,
|
|
65
|
+
filename: filenameField ?? `output${ext ? "." + ext : ""}`,
|
|
66
|
+
contentType,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const child of Object.values(value))
|
|
71
|
+
visit(child, refs, seen);
|
|
72
|
+
}
|
|
73
|
+
function extFromUrl(url) {
|
|
74
|
+
try {
|
|
75
|
+
const path = new URL(url).pathname;
|
|
76
|
+
const dot = path.lastIndexOf(".");
|
|
77
|
+
return dot === -1 ? "" : path.slice(dot + 1).toLowerCase();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return "";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Download all extracted media refs to disk, materializing the path from
|
|
85
|
+
* a template. Supported placeholders: {index}, {name}, {ext}, {request_id}.
|
|
86
|
+
* Falls back to the source filename in the cwd when no template is given.
|
|
87
|
+
*/
|
|
88
|
+
export async function downloadMedia(opts) {
|
|
89
|
+
const initial = opts.refs.map((ref, i) => renderTemplate(ref, opts.template, i, opts.requestId));
|
|
90
|
+
// Disambiguate any colliding resolved paths so multi-output runs (e.g.
|
|
91
|
+
// `--num_images 3` where fal returns the same default `file_name` for
|
|
92
|
+
// every output) don't silently overwrite each other on disk. The first
|
|
93
|
+
// occurrence keeps the original name; subsequent collisions get a
|
|
94
|
+
// `_1`, `_2`, … suffix inserted before the extension.
|
|
95
|
+
const targets = disambiguateTargets(initial);
|
|
96
|
+
// Create each unique parent directory once instead of redoing it per ref.
|
|
97
|
+
const dirs = new Set(targets.map((t) => dirname(t)));
|
|
98
|
+
for (const d of dirs)
|
|
99
|
+
mkdirSync(d, { recursive: true });
|
|
100
|
+
const outcomes = await Promise.all(opts.refs.map(async (ref, i) => {
|
|
101
|
+
const target = targets[i];
|
|
102
|
+
try {
|
|
103
|
+
const res = await fetch(ref.url);
|
|
104
|
+
if (!res.ok) {
|
|
105
|
+
return { ok: false, url: ref.url, error: `${res.status} ${res.statusText}` };
|
|
106
|
+
}
|
|
107
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
108
|
+
writeFileSync(target, bytes);
|
|
109
|
+
return { ok: true, target };
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
url: ref.url,
|
|
115
|
+
error: err instanceof Error ? err.message : String(err),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}));
|
|
119
|
+
const downloaded = [];
|
|
120
|
+
const failed = [];
|
|
121
|
+
for (const o of outcomes) {
|
|
122
|
+
if (o.ok)
|
|
123
|
+
downloaded.push(o.target);
|
|
124
|
+
else
|
|
125
|
+
failed.push({ url: o.url, error: o.error });
|
|
126
|
+
}
|
|
127
|
+
return { downloaded, failed };
|
|
128
|
+
}
|
|
129
|
+
// Strip any directory components from a fal-provided file_name so a
|
|
130
|
+
// malicious response can't traverse out of the download target dir.
|
|
131
|
+
// Handle both POSIX and Windows separators regardless of host OS so a
|
|
132
|
+
// `..\\..\\evil` payload sent to a Linux client is still flattened.
|
|
133
|
+
function sanitizeFilename(name) {
|
|
134
|
+
const base = name.replace(/[\\/]+/g, "/").split("/").pop() ?? "";
|
|
135
|
+
if (!base || base === "." || base === "..")
|
|
136
|
+
return null;
|
|
137
|
+
return base;
|
|
138
|
+
}
|
|
139
|
+
function disambiguateTargets(paths) {
|
|
140
|
+
const counts = new Map();
|
|
141
|
+
for (const p of paths)
|
|
142
|
+
counts.set(p, (counts.get(p) ?? 0) + 1);
|
|
143
|
+
const seen = new Map();
|
|
144
|
+
return paths.map((p) => {
|
|
145
|
+
if ((counts.get(p) ?? 0) <= 1)
|
|
146
|
+
return p;
|
|
147
|
+
const n = seen.get(p) ?? 0;
|
|
148
|
+
seen.set(p, n + 1);
|
|
149
|
+
if (n === 0)
|
|
150
|
+
return p;
|
|
151
|
+
const ext = extname(p);
|
|
152
|
+
return p.slice(0, p.length - ext.length) + `_${n}` + ext;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function renderTemplate(ref, template, index, requestId) {
|
|
156
|
+
const ext = (() => {
|
|
157
|
+
const fromName = extname(ref.filename).slice(1);
|
|
158
|
+
if (fromName)
|
|
159
|
+
return fromName;
|
|
160
|
+
return extFromUrl(ref.url) || "bin";
|
|
161
|
+
})();
|
|
162
|
+
// String-based stem extraction: a dynamic RegExp built from `ext`
|
|
163
|
+
// would treat any regex metachars in an unusual fal `file_name`
|
|
164
|
+
// (`.`, `+`, `*`) as patterns, potentially stripping the wrong
|
|
165
|
+
// suffix. Plain endsWith is exact and case-insensitive via toLowerCase.
|
|
166
|
+
const lowerName = ref.filename.toLowerCase();
|
|
167
|
+
const dotExt = "." + ext.toLowerCase();
|
|
168
|
+
const stem = lowerName.endsWith(dotExt)
|
|
169
|
+
? ref.filename.slice(0, -dotExt.length) || "output"
|
|
170
|
+
: ref.filename || "output";
|
|
171
|
+
// No template or no placeholder → caller meant either a destination
|
|
172
|
+
// directory (omitted, ".", "./", "../out", "out/") or an explicit
|
|
173
|
+
// output filename (`./out.png`, `frame.mp4`). We disambiguate by
|
|
174
|
+
// looking for an extension on the basename — anything with one is
|
|
175
|
+
// treated as the literal output path; otherwise we resolve into the
|
|
176
|
+
// directory using the ref's filename. The previous all-as-dir
|
|
177
|
+
// behavior wrote `./walk.png/output.png` for `--download ./walk.png`.
|
|
178
|
+
if (!template || !template.includes("{")) {
|
|
179
|
+
if (template && extname(template))
|
|
180
|
+
return resolve(template);
|
|
181
|
+
const dir = template ?? process.cwd();
|
|
182
|
+
return resolve(dir, ref.filename || `output-${index}.${ext}`);
|
|
183
|
+
}
|
|
184
|
+
const rendered = template
|
|
185
|
+
.replaceAll("{index}", String(index))
|
|
186
|
+
.replaceAll("{name}", stem)
|
|
187
|
+
.replaceAll("{ext}", ext)
|
|
188
|
+
.replaceAll("{request_id}", requestId);
|
|
189
|
+
return resolve(rendered);
|
|
190
|
+
}
|