vibedgames 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
@@ -0,0 +1,17 @@
1
+ import type { createClient } from "./api.js";
2
+ type Client = ReturnType<typeof createClient>;
3
+ export declare function endpointPath(endpointId: string): string;
4
+ export declare function queueAppId(endpointId: string): string;
5
+ type CompletedResult = {
6
+ request_id: string;
7
+ result: unknown;
8
+ };
9
+ /**
10
+ * Poll fal's queue from the client side until the job reaches a
11
+ * terminal status, then fetch the result. The Worker isn't in the
12
+ * loop — it's only along for each individual `media.forward` hop.
13
+ */
14
+ export declare function waitForCompletion(client: Client, endpoint_id: string, request_id: string, opts: {
15
+ quiet: boolean;
16
+ }): Promise<CompletedResult>;
17
+ export {};
@@ -0,0 +1,80 @@
1
+ import consola from "consola";
2
+ import { isRecord } from "./types.js";
3
+ // Strip leading/trailing slashes from a fal endpoint id so it can be
4
+ // spliced into a URL path without doubling separators.
5
+ export function endpointPath(endpointId) {
6
+ return endpointId.replace(/^\/+|\/+$/g, "");
7
+ }
8
+ // fal's queue accepts the full endpoint id (including any model subpath,
9
+ // e.g. `fal-ai/flux/schnell`) on submit, but the status/result/cancel
10
+ // routes are keyed by the owning *application* id only (`fal-ai/flux`).
11
+ // Passing the subpath to those routes returns 405. `workflows`/`comfy`
12
+ // ids carry the namespace as a leading segment, so their app id is three
13
+ // segments deep.
14
+ const QUEUE_APP_NAMESPACES = new Set(["workflows", "comfy"]);
15
+ export function queueAppId(endpointId) {
16
+ const parts = endpointPath(endpointId).split("/").filter(Boolean);
17
+ const take = QUEUE_APP_NAMESPACES.has(parts[0] ?? "") ? 3 : 2;
18
+ return parts.slice(0, take).join("/");
19
+ }
20
+ const POLL_INTERVAL_MS = 2_000;
21
+ // 30-minute ceiling on a sync run. Generous (this is the user's local
22
+ // CLI process, not a billed Worker) but bounded so a stuck IN_QUEUE
23
+ // job can't hang the CLI indefinitely. Long jobs should use --async.
24
+ const POLL_TIMEOUT_MS = 30 * 60 * 1000;
25
+ /**
26
+ * Poll fal's queue from the client side until the job reaches a
27
+ * terminal status, then fetch the result. The Worker isn't in the
28
+ * loop — it's only along for each individual `media.forward` hop.
29
+ */
30
+ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
31
+ const ep = queueAppId(endpoint_id);
32
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
33
+ let lastStatus;
34
+ while (true) {
35
+ if (Date.now() > deadline) {
36
+ throw new Error(`fal job did not complete within ${POLL_TIMEOUT_MS}ms ` +
37
+ `(endpoint=${endpoint_id} request_id=${request_id}). ` +
38
+ `Use \`vg media status ${endpoint_id} ${request_id} --result\` to check later.`);
39
+ }
40
+ const raw = await client.media.forward.mutate({
41
+ target: "queue",
42
+ method: "GET",
43
+ path: `/${ep}/requests/${request_id}/status`,
44
+ });
45
+ const status = isRecord(raw) && typeof raw.status === "string" ? raw.status : "UNKNOWN";
46
+ const upper = status.toUpperCase();
47
+ if (!opts.quiet && upper !== lastStatus) {
48
+ lastStatus = upper;
49
+ const queuePos = isRecord(raw) && typeof raw.queue_position === "number" ? raw.queue_position : null;
50
+ const tag = queuePos !== null ? `${upper.toLowerCase()} (queue ${queuePos})` : upper.toLowerCase();
51
+ consola.log(` ${tag}`);
52
+ }
53
+ if (upper === "COMPLETED")
54
+ break;
55
+ if (upper === "FAILED" || upper === "CANCELLED") {
56
+ const reason = pickErrorReason(raw);
57
+ throw new Error(reason ? `fal job ${upper.toLowerCase()}: ${reason}` : `fal job ${upper.toLowerCase()}`);
58
+ }
59
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
60
+ }
61
+ const result = await client.media.forward.mutate({
62
+ target: "queue",
63
+ method: "GET",
64
+ path: `/${ep}/requests/${request_id}`,
65
+ });
66
+ return { request_id, result };
67
+ }
68
+ function pickErrorReason(value) {
69
+ if (!isRecord(value))
70
+ return null;
71
+ if (typeof value.error === "string" && value.error.length > 0)
72
+ return value.error;
73
+ if (typeof value.detail === "string" && value.detail.length > 0)
74
+ return value.detail;
75
+ if (isRecord(value.error) && typeof value.error.message === "string")
76
+ return value.error.message;
77
+ if (isRecord(value.response))
78
+ return pickErrorReason(value.response);
79
+ return null;
80
+ }
@@ -0,0 +1,12 @@
1
+ import type { createClient } from "./api.js";
2
+ import type { LocalFile } from "./media-args.js";
3
+ type Client = ReturnType<typeof createClient>;
4
+ /**
5
+ * Upload one local file directly to fal's CDN. The proxy hands us a
6
+ * presigned upload slot (upload_url + file_url) via the `media.forward`
7
+ * storage target; bytes go straight from the client to fal, never
8
+ * through the worker. The returned file_url is a stable fal CDN URL
9
+ * that can be reused across runs without re-uploading.
10
+ */
11
+ export declare function uploadFile(client: Client, file: LocalFile): Promise<string>;
12
+ export {};
@@ -0,0 +1,51 @@
1
+ import { openAsBlob } from "node:fs";
2
+ import { isRecord } from "./types.js";
3
+ /**
4
+ * Upload one local file directly to fal's CDN. The proxy hands us a
5
+ * presigned upload slot (upload_url + file_url) via the `media.forward`
6
+ * storage target; bytes go straight from the client to fal, never
7
+ * through the worker. The returned file_url is a stable fal CDN URL
8
+ * that can be reused across runs without re-uploading.
9
+ */
10
+ export async function uploadFile(client, file) {
11
+ const slot = await client.media.forward.mutate({
12
+ target: "storage",
13
+ method: "POST",
14
+ path: "/storage/upload/initiate",
15
+ body: { content_type: file.contentType, file_name: file.filename },
16
+ });
17
+ const uploadUrl = pickUrl(slot, "upload_url");
18
+ const fileUrl = pickUrl(slot, "file_url");
19
+ const body = await openAsBlob(file.path, { type: file.contentType });
20
+ const res = await fetch(uploadUrl, {
21
+ method: "PUT",
22
+ headers: { "Content-Type": file.contentType },
23
+ body,
24
+ });
25
+ if (!res.ok) {
26
+ const text = await res.text().catch(() => "");
27
+ throw new Error(`Upload failed for ${file.filename}: ${res.status} ${res.statusText} ${text}`);
28
+ }
29
+ return fileUrl;
30
+ }
31
+ function pickUrl(slot, key) {
32
+ if (!isRecord(slot) || typeof slot[key] !== "string" || slot[key].length === 0) {
33
+ throw new Error(`fal storage initiate response missing ${key}.`);
34
+ }
35
+ const value = slot[key];
36
+ // Refuse any non-HTTPS URL even if it comes from a trusted server
37
+ // response — a misconfigured response (or a downgrade attack on the
38
+ // proxy hop) must not silently send user bytes over plain HTTP, and
39
+ // file_url gets passed into later runs where it should stay HTTPS.
40
+ let parsed;
41
+ try {
42
+ parsed = new URL(value);
43
+ }
44
+ catch {
45
+ throw new Error(`fal storage initiate response ${key} is not a valid URL.`);
46
+ }
47
+ if (parsed.protocol !== "https:") {
48
+ throw new Error(`fal storage initiate response ${key} must be HTTPS, got ${parsed.protocol}.`);
49
+ }
50
+ return value;
51
+ }
@@ -0,0 +1,2 @@
1
+ /** Type-guard helpers shared across CLI modules. */
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,4 @@
1
+ /** Type-guard helpers shared across CLI modules. */
2
+ export function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
package/package.json CHANGED
@@ -1,34 +1,36 @@
1
1
  {
2
2
  "name": "vibedgames",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "private": false,
5
- "type": "module",
6
5
  "bin": {
7
6
  "vg": "./dist/index.js"
8
7
  },
9
8
  "files": [
10
9
  "dist"
11
10
  ],
11
+ "type": "module",
12
12
  "dependencies": {
13
- "@trpc/client": "^11.16.0",
14
- "citty": "^0.1.6",
13
+ "@trpc/client": "^11.17.0",
14
+ "citty": "^0.2.2",
15
15
  "consola": "^3.4.2",
16
16
  "cross-spawn": "^7.0.6",
17
- "superjson": "^2.2.6"
17
+ "superjson": "^2.2.6",
18
+ "tiged": "^2.12.8"
18
19
  },
19
20
  "devDependencies": {
20
- "@cloudflare/workers-types": "^4.20260408.1",
21
+ "@cloudflare/workers-types": "^4.20260522.1",
21
22
  "@kyh/tsconfig": "^1.1.14",
22
- "@trpc/server": "^11.16.0",
23
+ "@trpc/server": "^11.17.0",
23
24
  "@types/cross-spawn": "^6.0.6",
24
- "@types/node": "^25.5.2",
25
- "typescript": "^6.0.2",
25
+ "@types/node": "^25.9.1",
26
+ "typescript": "^6.0.3",
26
27
  "@repo/api": "^0.1.0"
27
28
  },
28
29
  "scripts": {
29
30
  "build": "tsc",
30
31
  "dev": "tsc --watch",
31
32
  "clean": "rm -rf .turbo dist node_modules",
33
+ "test:media": "node --import tsx --test test/media-args.test.ts test/media-download.test.ts test/media-poll.test.ts",
32
34
  "typecheck": "tsc --noEmit"
33
35
  }
34
36
  }
@@ -1 +0,0 @@
1
- export declare const listCommand: import("citty").CommandDef<import("citty").ArgsDef>;
@@ -1,23 +0,0 @@
1
- import { defineCommand } from "citty";
2
- import consola from "consola";
3
- import { createClient } from "../lib/api.js";
4
- export const listCommand = defineCommand({
5
- meta: {
6
- name: "list",
7
- description: "List your games",
8
- },
9
- run: async () => {
10
- const client = createClient();
11
- const { builds } = await client.localGame.listBuilds.query({ limit: 50 });
12
- if (builds.length === 0) {
13
- consola.info("No games found");
14
- return;
15
- }
16
- for (const build of builds) {
17
- const fileCount = build.gameBuildFiles.length;
18
- const updated = new Date(build.updatedAt).toLocaleDateString();
19
- const title = build.title ?? "(untitled)";
20
- consola.log(` ${build.id.slice(0, 8)} ${title} ${fileCount} files ${updated}`);
21
- }
22
- },
23
- });
@@ -1,12 +0,0 @@
1
- export declare const rmCommand: import("citty").CommandDef<{
2
- id: {
3
- type: "positional";
4
- description: string;
5
- required: true;
6
- };
7
- force: {
8
- type: "boolean";
9
- description: string;
10
- default: false;
11
- };
12
- }>;
@@ -1,35 +0,0 @@
1
- import { defineCommand } from "citty";
2
- import consola from "consola";
3
- import { createClient } from "../lib/api.js";
4
- export const rmCommand = defineCommand({
5
- meta: {
6
- name: "rm",
7
- description: "Remove a game",
8
- },
9
- args: {
10
- id: {
11
- type: "positional",
12
- description: "Game build ID to remove",
13
- required: true,
14
- },
15
- force: {
16
- type: "boolean",
17
- description: "Skip confirmation",
18
- default: false,
19
- },
20
- },
21
- run: async ({ args }) => {
22
- if (!args.force) {
23
- const confirmed = await consola.prompt(`Remove game ${args.id}?`, {
24
- type: "confirm",
25
- });
26
- if (!confirmed) {
27
- consola.info("Cancelled");
28
- return;
29
- }
30
- }
31
- const client = createClient();
32
- await client.localGame.deleteBuild.mutate({ buildId: args.id });
33
- consola.success(`Removed ${args.id}`);
34
- },
35
- });
@@ -1,8 +0,0 @@
1
- export declare const skillsCommand: import("citty").CommandDef<{
2
- dir: {
3
- type: "positional";
4
- description: string;
5
- required: false;
6
- default: string;
7
- };
8
- }>;
@@ -1,53 +0,0 @@
1
- import { execSync } from "node:child_process";
2
- import { existsSync, mkdirSync, rmSync } from "node:fs";
3
- import { join } from "node:path";
4
- import { defineCommand } from "citty";
5
- import consola from "consola";
6
- const REPO = "kyh/vibedgames";
7
- const SKILLS_PATH = ".claude/skills";
8
- const BRANCH = "main";
9
- export const skillsCommand = defineCommand({
10
- meta: {
11
- name: "skills",
12
- description: "Install vibedgames Claude Code skills into your project",
13
- },
14
- args: {
15
- dir: {
16
- type: "positional",
17
- description: "Project directory",
18
- required: false,
19
- default: ".",
20
- },
21
- },
22
- run: async ({ args }) => {
23
- const projectDir = args.dir;
24
- const targetDir = join(projectDir, SKILLS_PATH);
25
- const tarballUrl = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.tar.gz`;
26
- const tmpDir = join(projectDir, ".vg-skills-tmp");
27
- consola.start("Fetching skills from vibedgames...");
28
- try {
29
- // Download and extract just the skills directory
30
- mkdirSync(tmpDir, { recursive: true });
31
- execSync(`curl -sL "${tarballUrl}" | tar xz --strip-components=3 -C "${tmpDir}" "vibedgames-${BRANCH}/${SKILLS_PATH}"`, { stdio: "pipe" });
32
- // Copy to target
33
- mkdirSync(targetDir, { recursive: true });
34
- execSync(`cp -r "${tmpDir}"/* "${targetDir}"/`, { stdio: "pipe" });
35
- // Count skills
36
- const skills = execSync(`ls "${targetDir}"`, { encoding: "utf-8" })
37
- .trim()
38
- .split("\n")
39
- .filter(Boolean);
40
- consola.success(`Installed ${skills.length} skills to ${targetDir}`);
41
- consola.log(` ${skills.join(", ")}`);
42
- }
43
- catch (err) {
44
- consola.error(err instanceof Error ? err.message : String(err));
45
- process.exit(1);
46
- }
47
- finally {
48
- if (existsSync(tmpDir)) {
49
- rmSync(tmpDir, { recursive: true });
50
- }
51
- }
52
- },
53
- });