vibedgames 0.4.0 → 0.5.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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/credits.js +7 -18
  3. package/dist/commands/deploy.d.ts +8 -0
  4. package/dist/commands/deploy.js +58 -31
  5. package/dist/commands/fork.js +30 -24
  6. package/dist/commands/generate.js +69 -45
  7. package/dist/commands/init.js +29 -24
  8. package/dist/commands/login.js +2 -2
  9. package/dist/commands/new.d.ts +1 -1
  10. package/dist/commands/new.js +82 -62
  11. package/dist/commands/playtest.d.ts +12 -0
  12. package/dist/commands/playtest.js +36 -2
  13. package/dist/commands/update.js +19 -14
  14. package/dist/commands/whoami.d.ts +10 -1
  15. package/dist/commands/whoami.js +12 -5
  16. package/dist/index.js +2 -0
  17. package/dist/lib/api.d.ts +16 -4
  18. package/dist/lib/api.js +22 -28
  19. package/dist/lib/archive.js +8 -4
  20. package/dist/lib/codex.d.ts +3 -2
  21. package/dist/lib/codex.js +8 -7
  22. package/dist/lib/config-file.js +6 -5
  23. package/dist/lib/config.js +11 -1
  24. package/dist/lib/manifest.js +3 -3
  25. package/dist/lib/media-args.d.ts +4 -2
  26. package/dist/lib/media-args.js +6 -5
  27. package/dist/lib/media-download.d.ts +6 -1
  28. package/dist/lib/media-download.js +54 -10
  29. package/dist/lib/media-poll.d.ts +3 -2
  30. package/dist/lib/media-poll.js +11 -10
  31. package/dist/lib/media-upload.d.ts +1 -1
  32. package/dist/lib/media-upload.js +5 -4
  33. package/dist/lib/output.d.ts +12 -4
  34. package/dist/lib/output.js +11 -3
  35. package/dist/lib/package-manager.js +1 -1
  36. package/dist/lib/run.d.ts +9 -1
  37. package/dist/lib/run.js +8 -3
  38. package/dist/lib/strict-args.d.ts +27 -0
  39. package/dist/lib/strict-args.js +68 -0
  40. package/dist/lib/types.d.ts +16 -2
  41. package/dist/lib/types.js +12 -3
  42. package/dist/lib/update.js +8 -5
  43. package/package.json +16 -17
  44. package/LICENSE +0 -21
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
+ import { isJsonObject, isJsonString } from "./types.js";
4
5
  export function getConfigDir() {
5
6
  const xdg = process.env.XDG_CONFIG_HOME;
6
7
  const base = xdg ?? join(homedir(), ".config");
@@ -13,12 +14,21 @@ export function getConfig() {
13
14
  const path = getConfigPath();
14
15
  if (!existsSync(path))
15
16
  return null;
17
+ let raw;
16
18
  try {
17
- return JSON.parse(readFileSync(path, "utf-8"));
19
+ raw = JSON.parse(readFileSync(path, "utf-8"));
18
20
  }
19
21
  catch {
20
22
  return null;
21
23
  }
24
+ // auth.json is only ever written by saveConfig, so both fields are present
25
+ // in practice; a hand-corrupted file reads as "not logged in".
26
+ if (!isJsonObject(raw))
27
+ return null;
28
+ const { token, baseUrl } = raw;
29
+ if (!isJsonString(token) || !isJsonString(baseUrl))
30
+ return null;
31
+ return { token, baseUrl };
22
32
  }
23
33
  export function saveConfig(config) {
24
34
  const dir = getConfigDir();
@@ -9,7 +9,7 @@ const IGNORED_TOP_LEVEL = new Set([
9
9
  ".DS_Store",
10
10
  "vibedgames.json",
11
11
  ]);
12
- const CONTENT_TYPES = {
12
+ const CONTENT_TYPES = new Map(Object.entries({
13
13
  html: "text/html; charset=utf-8",
14
14
  htm: "text/html; charset=utf-8",
15
15
  js: "application/javascript; charset=utf-8",
@@ -41,10 +41,10 @@ const CONTENT_TYPES = {
41
41
  woff2: "font/woff2",
42
42
  txt: "text/plain; charset=utf-8",
43
43
  xml: "application/xml",
44
- };
44
+ }));
45
45
  function contentTypeForPath(path) {
46
46
  const ext = path.split(".").pop()?.toLowerCase() ?? "";
47
- return CONTENT_TYPES[ext] ?? "application/octet-stream";
47
+ return CONTENT_TYPES.get(ext) ?? "application/octet-stream";
48
48
  }
49
49
  function shouldIgnore(relPath) {
50
50
  const top = relPath.split(sep)[0] ?? "";
@@ -1,3 +1,4 @@
1
+ import type { JsonObject } from "./types.js";
1
2
  /**
2
3
  * Parse `--<key> value` pairs from argv into a JS object, JSON-decoding
3
4
  * values that look like JSON (true/false/null/numbers/objects/arrays) and
@@ -9,7 +10,7 @@
9
10
  * `"prompt=hello"` upstream, and `--async=true` would slip past the
10
11
  * RUN_RESERVED_FLAGS guard as a bogus model param.
11
12
  */
12
- export declare function parseRunInput(argv: string[]): Record<string, unknown>;
13
+ export declare function parseRunInput(argv: string[]): JsonObject;
13
14
  export type LocalFile = {
14
15
  path: string;
15
16
  filename: string;
@@ -22,7 +23,8 @@ export type LocalFile = {
22
23
  * `data.ply`, even `LICENSE` — still works.
23
24
  */
24
25
  export declare function readExplicitLocalFile(value: string): LocalFile | null;
25
- export declare function parseDownloadFlag(argv: string[]): {
26
+ export type DownloadFlag = {
26
27
  mode: "off" | "on";
27
28
  template?: string;
28
29
  };
30
+ export declare function parseDownloadFlag(argv: string[]): DownloadFlag;
@@ -67,8 +67,8 @@ export function parseRunInput(argv) {
67
67
  return out;
68
68
  }
69
69
  function assign(out, key, value) {
70
- if (key in out) {
71
- const existing = out[key];
70
+ const existing = out[key];
71
+ if (existing !== undefined) {
72
72
  if (Array.isArray(existing))
73
73
  existing.push(value);
74
74
  else
@@ -86,6 +86,7 @@ function parseValue(raw) {
86
86
  return null;
87
87
  if (raw.length > 0 && (raw[0] === "{" || raw[0] === "[")) {
88
88
  try {
89
+ // SAFETY: JSON.parse output is structurally JsonValue.
89
90
  return JSON.parse(raw);
90
91
  }
91
92
  catch {
@@ -144,7 +145,7 @@ function contentTypeForPath(path) {
144
145
  // "/home/user/my.project/texture" correctly yields "" instead of
145
146
  // mistaking "project/texture" for the extension.
146
147
  const ext = extname(path).slice(1).toLowerCase();
147
- const map = {
148
+ const map = new Map(Object.entries({
148
149
  png: "image/png",
149
150
  jpg: "image/jpeg",
150
151
  jpeg: "image/jpeg",
@@ -164,8 +165,8 @@ function contentTypeForPath(path) {
164
165
  m4a: "audio/mp4",
165
166
  txt: "text/plain",
166
167
  json: "application/json",
167
- };
168
- return map[ext] ?? "application/octet-stream";
168
+ }));
169
+ return map.get(ext) ?? "application/octet-stream";
169
170
  }
170
171
  export function parseDownloadFlag(argv) {
171
172
  let lastIdx = -1;
@@ -1,3 +1,4 @@
1
+ import { type JsonValue } from "./types.js";
1
2
  type MediaRef = {
2
3
  url: string;
3
4
  filename: string;
@@ -10,13 +11,17 @@ type MediaRef = {
10
11
  * content types and also fall back to URL extension when content_type is
11
12
  * absent (some endpoints omit it).
12
13
  */
13
- export declare function extractMediaRefs(result: unknown): MediaRef[];
14
+ export declare function extractMediaRefs(result: JsonValue): MediaRef[];
14
15
  type DownloadResult = {
15
16
  downloaded: string[];
16
17
  failed: {
17
18
  url: string;
18
19
  error: string;
19
20
  }[];
21
+ mislabeled: {
22
+ path: string;
23
+ actual: string;
24
+ }[];
20
25
  };
21
26
  /**
22
27
  * Download all extracted media refs to disk, materializing the path from
@@ -1,6 +1,6 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import { dirname, extname, resolve } from "node:path";
3
- import { isRecord } from "./types.js";
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
6
6
  // omit it).
@@ -65,12 +65,12 @@ function visit(value, refs, seen) {
65
65
  visit(v, refs, seen);
66
66
  return;
67
67
  }
68
- if (!isRecord(value))
68
+ if (!isJsonObject(value))
69
69
  return;
70
70
  const url = value.url;
71
- if (typeof url === "string" && isTrustedFalContentHost(url) && !seen.has(url)) {
72
- const contentType = typeof value.content_type === "string" ? value.content_type.toLowerCase() : null;
73
- const filenameField = typeof value.file_name === "string" ? sanitizeFilename(value.file_name) : null;
71
+ if (isJsonString(url) && isTrustedFalContentHost(url) && !seen.has(url)) {
72
+ const contentType = isJsonString(value.content_type) ? value.content_type.toLowerCase() : null;
73
+ const filenameField = isJsonString(value.file_name) ? sanitizeFilename(value.file_name) : null;
74
74
  const ext = filenameField ? extname(filenameField).slice(1).toLowerCase() : extFromUrl(url);
75
75
  const looksMedia = contentType !== null ? /^(image|video|audio)\//.test(contentType) : MEDIA_EXT.has(ext);
76
76
  if (looksMedia) {
@@ -95,6 +95,46 @@ function extFromUrl(url) {
95
95
  return "";
96
96
  }
97
97
  }
98
+ // The extension each content type genuinely is. Only formats an agent is
99
+ // likely to hand to a decoder afterwards need an entry; anything absent is
100
+ // left alone rather than guessed at.
101
+ const EXT_FOR_CONTENT_TYPE = new Map(Object.entries({
102
+ "image/png": "png",
103
+ "image/jpeg": "jpg",
104
+ "image/webp": "webp",
105
+ "image/gif": "gif",
106
+ "image/avif": "avif",
107
+ "video/mp4": "mp4",
108
+ "video/webm": "webm",
109
+ "video/quicktime": "mov",
110
+ "audio/mpeg": "mp3",
111
+ "audio/wav": "wav",
112
+ "audio/ogg": "ogg",
113
+ }));
114
+ // Extensions that name the same format, so `.jpg` for `image/jpeg` is not a lie.
115
+ const EXT_ALIASES = new Map(Object.entries({
116
+ jpeg: "jpg",
117
+ tif: "tiff",
118
+ htm: "html",
119
+ }));
120
+ const canonicalExt = (ext) => EXT_ALIASES.get(ext) ?? ext;
121
+ /**
122
+ * The extension the caller asked for versus the bytes actually served.
123
+ *
124
+ * `--download board.png` is honoured literally — renaming the path the caller
125
+ * chose would break whatever they wired it into — so when a model returns JPEG
126
+ * the file is a `.png` holding JPEG bytes. Downstream decoders reject it with
127
+ * "bad signature" and nothing points back here, hence the explicit report.
128
+ */
129
+ function mislabelOf(target, ref) {
130
+ const asked = canonicalExt(extname(target).slice(1).toLowerCase());
131
+ if (!asked)
132
+ return null;
133
+ const actual = ref.contentType ? EXT_FOR_CONTENT_TYPE.get(ref.contentType) : undefined;
134
+ if (!actual || canonicalExt(actual) === asked)
135
+ return null;
136
+ return { path: target, actual };
137
+ }
98
138
  /**
99
139
  * Download all extracted media refs to disk, materializing the path from
100
140
  * a template. Supported placeholders: {index}, {name}, {ext}, {request_id}.
@@ -121,7 +161,7 @@ export async function downloadMedia(opts) {
121
161
  }
122
162
  const bytes = new Uint8Array(await res.arrayBuffer());
123
163
  writeFileSync(target, bytes);
124
- return { ok: true, target };
164
+ return { ok: true, target, mislabel: mislabelOf(target, ref) };
125
165
  }
126
166
  catch (err) {
127
167
  return {
@@ -133,13 +173,17 @@ export async function downloadMedia(opts) {
133
173
  }));
134
174
  const downloaded = [];
135
175
  const failed = [];
176
+ const mislabeled = [];
136
177
  for (const o of outcomes) {
137
- if (o.ok)
138
- downloaded.push(o.target);
139
- else
178
+ if (!o.ok) {
140
179
  failed.push({ url: o.url, error: o.error });
180
+ continue;
181
+ }
182
+ downloaded.push(o.target);
183
+ if (o.mislabel)
184
+ mislabeled.push(o.mislabel);
141
185
  }
142
- return { downloaded, failed };
186
+ return { downloaded, failed, mislabeled };
143
187
  }
144
188
  // Strip any directory components from a fal-provided file_name so a
145
189
  // malicious response can't traverse out of the download target dir.
@@ -1,10 +1,11 @@
1
- import type { createClient } from "./api.js";
1
+ import { type createClient } from "./api.js";
2
+ import { type JsonValue } from "./types.js";
2
3
  type Client = ReturnType<typeof createClient>;
3
4
  export declare function endpointPath(endpointId: string): string;
4
5
  export declare function queueAppId(endpointId: string): string;
5
6
  type CompletedResult = {
6
7
  request_id: string;
7
- result: unknown;
8
+ result: JsonValue;
8
9
  };
9
10
  /**
10
11
  * Poll fal's queue from the client side until the job reaches a
@@ -1,5 +1,6 @@
1
1
  import consola from "consola";
2
- import { isRecord } from "./types.js";
2
+ import { forwardJson } from "./api.js";
3
+ import { isJsonNumber, isJsonObject, isJsonString } from "./types.js";
3
4
  // Strip leading/trailing slashes from a fal endpoint id so it can be
4
5
  // spliced into a URL path without doubling separators.
5
6
  export function endpointPath(endpointId) {
@@ -37,16 +38,16 @@ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
37
38
  `(endpoint=${endpoint_id} request_id=${request_id}). ` +
38
39
  `Use \`vg generate status ${endpoint_id} ${request_id} --result\` to check later.`);
39
40
  }
40
- const raw = await client.generate.forward.mutate({
41
+ const raw = await forwardJson(client, {
41
42
  target: "queue",
42
43
  method: "GET",
43
44
  path: `/${ep}/requests/${request_id}/status`,
44
45
  });
45
- const status = isRecord(raw) && typeof raw.status === "string" ? raw.status : "UNKNOWN";
46
+ const status = isJsonObject(raw) && isJsonString(raw.status) ? raw.status : "UNKNOWN";
46
47
  const upper = status.toUpperCase();
47
48
  if (!opts.quiet && upper !== lastStatus) {
48
49
  lastStatus = upper;
49
- const queuePos = isRecord(raw) && typeof raw.queue_position === "number" ? raw.queue_position : null;
50
+ const queuePos = isJsonObject(raw) && isJsonNumber(raw.queue_position) ? raw.queue_position : null;
50
51
  const tag = queuePos !== null ? `${upper.toLowerCase()} (queue ${queuePos})` : upper.toLowerCase();
51
52
  consola.log(` ${tag}`);
52
53
  }
@@ -58,7 +59,7 @@ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
58
59
  }
59
60
  await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
60
61
  }
61
- const result = await client.generate.forward.mutate({
62
+ const result = await forwardJson(client, {
62
63
  target: "queue",
63
64
  method: "GET",
64
65
  path: `/${ep}/requests/${request_id}`,
@@ -66,15 +67,15 @@ export async function waitForCompletion(client, endpoint_id, request_id, opts) {
66
67
  return { request_id, result };
67
68
  }
68
69
  function pickErrorReason(value) {
69
- if (!isRecord(value))
70
+ if (!isJsonObject(value))
70
71
  return null;
71
- if (typeof value.error === "string" && value.error.length > 0)
72
+ if (isJsonString(value.error) && value.error.length > 0)
72
73
  return value.error;
73
- if (typeof value.detail === "string" && value.detail.length > 0)
74
+ if (isJsonString(value.detail) && value.detail.length > 0)
74
75
  return value.detail;
75
- if (isRecord(value.error) && typeof value.error.message === "string")
76
+ if (isJsonObject(value.error) && isJsonString(value.error.message))
76
77
  return value.error.message;
77
- if (isRecord(value.response))
78
+ if (isJsonObject(value.response))
78
79
  return pickErrorReason(value.response);
79
80
  return null;
80
81
  }
@@ -1,4 +1,4 @@
1
- import type { createClient } from "./api.js";
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
  /**
@@ -1,5 +1,6 @@
1
1
  import { openAsBlob } from "node:fs";
2
- import { isRecord } from "./types.js";
2
+ import { forwardJson } from "./api.js";
3
+ import { isJsonObject, isJsonString } from "./types.js";
3
4
  /**
4
5
  * Upload one local file directly to fal's CDN. The proxy hands us a
5
6
  * presigned upload slot (upload_url + file_url) via the `generate.forward`
@@ -8,7 +9,7 @@ import { isRecord } from "./types.js";
8
9
  * that can be reused across runs without re-uploading.
9
10
  */
10
11
  export async function uploadFile(client, file) {
11
- const slot = await client.generate.forward.mutate({
12
+ const slot = await forwardJson(client, {
12
13
  target: "storage",
13
14
  method: "POST",
14
15
  path: "/storage/upload/initiate",
@@ -29,10 +30,10 @@ export async function uploadFile(client, file) {
29
30
  return fileUrl;
30
31
  }
31
32
  function pickUrl(slot, key) {
32
- if (!isRecord(slot) || typeof slot[key] !== "string" || slot[key].length === 0) {
33
+ const value = isJsonObject(slot) ? slot[key] : undefined;
34
+ if (!isJsonString(value) || value.length === 0) {
33
35
  throw new Error(`fal storage initiate response missing ${key}.`);
34
36
  }
35
- const value = slot[key];
36
37
  // Refuse any non-HTTPS URL even if it comes from a trusted server
37
38
  // response — a misconfigured response (or a downgrade attack on the
38
39
  // proxy hop) must not silently send user bytes over plain HTTP, and
@@ -11,27 +11,35 @@ export type OutputArgs = {
11
11
  json?: boolean;
12
12
  field?: string;
13
13
  };
14
+ /**
15
+ * What the commands hand to stdout: JSON, plus `undefined` so payload types
16
+ * can carry optional members (JSON.stringify drops them, and `--field`
17
+ * reports them as missing).
18
+ */
19
+ export type OutputValue = string | number | boolean | null | undefined | OutputValue[] | {
20
+ [key: string]: OutputValue;
21
+ };
14
22
  export declare function isJsonOutput(args: OutputArgs): boolean;
15
- export declare function writeJson(value: unknown): void;
23
+ export declare function writeJson(value: OutputValue): void;
16
24
  /**
17
25
  * Resolve a dotted path against a decoded JSON value. Supports array indexing
18
26
  * in both `items[0]` and `items.0` spellings, since agents write both.
19
27
  * Returns `undefined` for any path that doesn't resolve.
20
28
  */
21
- export declare function selectField(value: unknown, path: string): unknown;
29
+ export declare function selectField(value: OutputValue, path: string): OutputValue;
22
30
  /**
23
31
  * Render one selected value for shell capture. Scalars print bare so
24
32
  * `$(vg ... --field url)` needs no unquoting; arrays of scalars print one per
25
33
  * line so they can be looped over; anything structural falls back to JSON.
26
34
  */
27
- export declare function formatField(value: unknown): string;
35
+ export declare function formatField(value: OutputValue): string;
28
36
  /**
29
37
  * The standard exit path for a command that produced structured data.
30
38
  * `--field` wins over `--json` when both are passed, since asking for one
31
39
  * value is the more specific request. Returns false when neither flag was
32
40
  * given, so the caller can fall through to its human-readable rendering.
33
41
  */
34
- export declare function writeStructured(value: unknown, args: OutputArgs): boolean;
42
+ export declare function writeStructured(value: OutputValue, args: OutputArgs): boolean;
35
43
  /** The `--json`/`--field` arg pair, for spreading into a citty `args` block. */
36
44
  export declare const outputArgs: {
37
45
  readonly json: {
@@ -7,6 +7,10 @@
7
7
  * skill at all. `--field` removes it: the CLI does the selection itself and
8
8
  * prints a bare scalar that a shell can capture directly.
9
9
  */
10
+ function isOutputObject(value) {
11
+ // Object() is the identity only on objects; arrays are split off explicitly.
12
+ return Object(value) === value && !Array.isArray(value);
13
+ }
10
14
  export function isJsonOutput(args) {
11
15
  return Boolean(args.json) || process.env.VG_JSON_OUTPUT === "1";
12
16
  }
@@ -36,12 +40,16 @@ export function selectField(value, path) {
36
40
  current = current.at(index);
37
41
  continue;
38
42
  }
39
- if (typeof current !== "object")
43
+ if (!isOutputObject(current))
40
44
  return undefined;
41
45
  current = current[segment];
42
46
  }
43
47
  return current;
44
48
  }
49
+ // A value that prints as one bare token: null or a primitive.
50
+ function isScalarEntry(value) {
51
+ return value === null || (value !== undefined && Object(value) !== value);
52
+ }
45
53
  /**
46
54
  * Render one selected value for shell capture. Scalars print bare so
47
55
  * `$(vg ... --field url)` needs no unquoting; arrays of scalars print one per
@@ -51,12 +59,12 @@ export function formatField(value) {
51
59
  if (value === null || value === undefined)
52
60
  return "";
53
61
  if (Array.isArray(value)) {
54
- if (value.every((v) => v === null || ["string", "number", "boolean"].includes(typeof v))) {
62
+ if (value.every(isScalarEntry)) {
55
63
  return value.map((v) => (v === null ? "" : String(v))).join("\n");
56
64
  }
57
65
  return JSON.stringify(value, null, 2);
58
66
  }
59
- if (typeof value === "object")
67
+ if (isOutputObject(value))
60
68
  return JSON.stringify(value, null, 2);
61
69
  return String(value);
62
70
  }
@@ -49,7 +49,7 @@ export function detectPackageManager(installPath, env = process.env) {
49
49
  return manager;
50
50
  }
51
51
  // Bun reports itself in versions; running under it means `bun add` works.
52
- if (typeof globalThis.Bun !== "undefined")
52
+ if ("Bun" in globalThis)
53
53
  return "bun";
54
54
  return fromUserAgent(env.npm_config_user_agent) ?? "npm";
55
55
  }
package/dist/lib/run.d.ts CHANGED
@@ -2,10 +2,18 @@ export type RunResult = {
2
2
  code: number;
3
3
  output: string;
4
4
  };
5
+ export type RunOptions = {
6
+ /**
7
+ * Mirror the child's output to this process as it arrives. Long steps
8
+ * (`npx skills add` clones a repo per skill) otherwise look hung: the
9
+ * buffered output is only readable once the child has already exited.
10
+ */
11
+ stream?: boolean;
12
+ };
5
13
  /**
6
14
  * True when the command never started, as opposed to running and failing.
7
15
  * `run` turns a spawn error into an exit code, so the message is the only
8
16
  * thing that separates "no such binary" from "the binary said no".
9
17
  */
10
18
  export declare const isMissingCommand: (result: RunResult) => boolean;
11
- export declare const run: (cmd: string, args: string[]) => Promise<RunResult>;
19
+ export declare const run: (cmd: string, args: string[], options?: RunOptions) => Promise<RunResult>;
package/dist/lib/run.js CHANGED
@@ -5,11 +5,16 @@ import spawn from "cross-spawn";
5
5
  * thing that separates "no such binary" from "the binary said no".
6
6
  */
7
7
  export const isMissingCommand = (result) => result.code !== 0 && /ENOENT|not found|not recognized/i.test(result.output);
8
- export const run = (cmd, args) => new Promise((resolve) => {
8
+ export const run = (cmd, args, options = {}) => new Promise((resolve) => {
9
9
  const chunks = [];
10
10
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
11
- child.stdout?.on("data", (c) => chunks.push(c));
12
- child.stderr?.on("data", (c) => chunks.push(c));
11
+ const collect = (stream) => (c) => {
12
+ chunks.push(c);
13
+ if (options.stream)
14
+ stream.write(c);
15
+ };
16
+ child.stdout?.on("data", collect(process.stderr));
17
+ child.stderr?.on("data", collect(process.stderr));
13
18
  child.on("error", (err) => resolve({ code: 1, output: `${err.message}\n` }));
14
19
  child.on("close", (code) => resolve({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
15
20
  });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Reject flags a command does not declare.
3
+ *
4
+ * citty hard-codes `strict: false` on node's `parseArgs`, so an unknown flag is
5
+ * parsed and then dropped: `vg deploy ./dist --slugg wrong` deploys to the
6
+ * *default* slug and exits 0. A human notices the wrong URL in the output; an
7
+ * agent reads exit 0 and carries on. The skill scripts already fail this way
8
+ * (`unrecognized arguments: …`, exit 2), so this matches them.
9
+ *
10
+ * Only for commands whose flags are a closed set. `vg generate run` forwards
11
+ * arbitrary `--param value` pairs to a model's schema and must stay permissive,
12
+ * and `vg playtest`/`vg factory` are passthroughs to another binary's grammar.
13
+ */
14
+ /** The subset of citty's `ArgDef` this check reads. */
15
+ type ArgSpec = {
16
+ type?: string;
17
+ alias?: string | string[];
18
+ };
19
+ /**
20
+ * The long flags in `rawArgs` that `argsDef` does not declare, in the order
21
+ * they were typed. Everything after a bare `--` is a passthrough payload and is
22
+ * left alone.
23
+ */
24
+ export declare function unknownFlags(rawArgs: string[], argsDef: Record<string, ArgSpec>): string[];
25
+ /** Exit 2 naming every undeclared flag, or return so the command can run. */
26
+ export declare function assertKnownFlags(rawArgs: string[], argsDef: Record<string, ArgSpec>): void;
27
+ export {};
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Reject flags a command does not declare.
3
+ *
4
+ * citty hard-codes `strict: false` on node's `parseArgs`, so an unknown flag is
5
+ * parsed and then dropped: `vg deploy ./dist --slugg wrong` deploys to the
6
+ * *default* slug and exits 0. A human notices the wrong URL in the output; an
7
+ * agent reads exit 0 and carries on. The skill scripts already fail this way
8
+ * (`unrecognized arguments: …`, exit 2), so this matches them.
9
+ *
10
+ * Only for commands whose flags are a closed set. `vg generate run` forwards
11
+ * arbitrary `--param value` pairs to a model's schema and must stay permissive,
12
+ * and `vg playtest`/`vg factory` are passthroughs to another binary's grammar.
13
+ */
14
+ const UNRECOGNIZED_EXIT = 2;
15
+ function declaredNames(argsDef) {
16
+ const names = new Set();
17
+ for (const [name, spec] of Object.entries(argsDef)) {
18
+ if (spec.type === "positional")
19
+ continue;
20
+ names.add(name);
21
+ // citty accepts a camelCase arg under its kebab spelling too.
22
+ names.add(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
23
+ const alias = spec.alias;
24
+ if (Array.isArray(alias))
25
+ for (const a of alias)
26
+ names.add(a);
27
+ else if (alias !== undefined)
28
+ names.add(alias);
29
+ }
30
+ // citty answers these itself; they never reach a command's `args`.
31
+ names.add("help");
32
+ names.add("version");
33
+ return names;
34
+ }
35
+ /**
36
+ * The long flags in `rawArgs` that `argsDef` does not declare, in the order
37
+ * they were typed. Everything after a bare `--` is a passthrough payload and is
38
+ * left alone.
39
+ */
40
+ export function unknownFlags(rawArgs, argsDef) {
41
+ const known = declaredNames(argsDef);
42
+ const unknown = [];
43
+ for (const raw of rawArgs) {
44
+ if (raw === "--")
45
+ break;
46
+ if (!raw.startsWith("--") || raw.length === 2)
47
+ continue;
48
+ const flag = (raw.slice(2).split("=")[0] ?? "").trim();
49
+ if (flag.length === 0)
50
+ continue;
51
+ // `--no-foo` is citty's negation of the boolean `foo`.
52
+ const negated = flag.startsWith("no-") ? flag.slice(3) : null;
53
+ if (known.has(flag))
54
+ continue;
55
+ if (negated !== null && known.has(negated))
56
+ continue;
57
+ unknown.push(`--${flag}`);
58
+ }
59
+ return unknown;
60
+ }
61
+ /** Exit 2 naming every undeclared flag, or return so the command can run. */
62
+ export function assertKnownFlags(rawArgs, argsDef) {
63
+ const unknown = unknownFlags(rawArgs, argsDef);
64
+ if (unknown.length === 0)
65
+ return;
66
+ process.stderr.write(`unrecognized arguments: ${unknown.join(" ")}\n`);
67
+ process.exit(UNRECOGNIZED_EXIT);
68
+ }
@@ -1,2 +1,16 @@
1
- /** Type-guard helpers shared across CLI modules. */
2
- export declare function isRecord(value: unknown): value is Record<string, unknown>;
1
+ /** JSON domain types and guards shared across CLI modules. */
2
+ /**
3
+ * What the CLI's I/O boundaries actually produce: fal responses proxied
4
+ * through `generate.forward`, config files, and any other `JSON.parse`
5
+ * output. Values are narrowed from this closed union instead of sniffed
6
+ * with `typeof`.
7
+ */
8
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
9
+ [key: string]: JsonValue;
10
+ };
11
+ export type JsonObject = {
12
+ [key: string]: JsonValue;
13
+ };
14
+ export declare function isJsonObject(value: JsonValue | undefined): value is JsonObject;
15
+ export declare function isJsonString(value: JsonValue | undefined): value is string;
16
+ export declare function isJsonNumber(value: JsonValue | undefined): value is number;
package/dist/lib/types.js CHANGED
@@ -1,4 +1,13 @@
1
- /** Type-guard helpers shared across CLI modules. */
2
- export function isRecord(value) {
3
- return typeof value === "object" && value !== null && !Array.isArray(value);
1
+ /** JSON domain types and guards shared across CLI modules. */
2
+ export function isJsonObject(value) {
3
+ // Object() is the identity only on objects; arrays are split off explicitly.
4
+ return Object(value) === value && !Array.isArray(value);
5
+ }
6
+ export function isJsonString(value) {
7
+ // String() is the identity only on strings.
8
+ return String(value) === value;
9
+ }
10
+ export function isJsonNumber(value) {
11
+ // JSON cannot encode NaN/Infinity, so isFinite matches every JSON number.
12
+ return Number.isFinite(value);
4
13
  }