vibedgames 0.4.1 → 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.
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFile
3
3
  import { dirname, join, relative, sep } from "node:path";
4
4
  import ignore from "ignore";
5
5
  import { create as tarCreate, extract as tarExtract } from "tar";
6
+ import { isJsonObject, isJsonString } from "./types.js";
6
7
  /**
7
8
  * Patterns ALWAYS excluded from a source archive, regardless of .gitignore —
8
9
  * build output, VCS internals, and (critically) secrets. Source upload is a
@@ -140,13 +141,15 @@ function rewriteWorkspaceProtocols(root) {
140
141
  catch {
141
142
  return null;
142
143
  }
144
+ if (!isJsonObject(pkg))
145
+ return null;
143
146
  let changed = false;
144
147
  for (const field of DEP_FIELDS) {
145
148
  const deps = pkg[field];
146
- if (!deps || typeof deps !== "object")
149
+ if (!isJsonObject(deps))
147
150
  continue;
148
151
  for (const [name, spec] of Object.entries(deps)) {
149
- if (typeof spec !== "string")
152
+ if (!isJsonString(spec))
150
153
  continue;
151
154
  if (!spec.startsWith("workspace:") && !spec.startsWith("catalog:"))
152
155
  continue;
@@ -185,8 +188,9 @@ function installedVersion(root, name) {
185
188
  const p = join(dir, "node_modules", name, "package.json");
186
189
  if (existsSync(p)) {
187
190
  try {
188
- const v = JSON.parse(readFileSync(p, "utf8")).version;
189
- if (typeof v === "string")
191
+ const pkg = JSON.parse(readFileSync(p, "utf8"));
192
+ const v = isJsonObject(pkg) ? pkg.version : undefined;
193
+ if (isJsonString(v))
190
194
  return v;
191
195
  }
192
196
  catch {
@@ -1,3 +1,4 @@
1
+ import { type JsonObject } from "./types.js";
1
2
  export type Provider = "vibedgames" | "codex";
2
3
  /**
3
4
  * Expected, user-facing failure of the codex provider. Carries a clean
@@ -32,7 +33,7 @@ export type CodexInput = {
32
33
  * no filesystem access, so the reference values are returned verbatim and
33
34
  * resolved to local files later.
34
35
  */
35
- export declare function parseCodexInput(input: Record<string, unknown>): CodexInput;
36
+ export declare function parseCodexInput(input: JsonObject): CodexInput;
36
37
  /**
37
38
  * Build the natural-language instruction handed to `codex exec`. We pin
38
39
  * exact output filenames and the working directory so the generated
@@ -67,7 +68,7 @@ type CodexRun = {
67
68
  * is missing, fails, or produces nothing.
68
69
  */
69
70
  export declare function generateImagesWithCodex(opts: {
70
- input: Record<string, unknown>;
71
+ input: JsonObject;
71
72
  }): Promise<CodexRun>;
72
73
  /**
73
74
  * Copy Codex's raw outputs to their final destinations per the
package/dist/lib/codex.js CHANGED
@@ -5,6 +5,7 @@ import { basename, dirname, extname, join, resolve } from "node:path";
5
5
  import spawn from "cross-spawn";
6
6
  import { readExplicitLocalFile } from "./media-args.js";
7
7
  import { disambiguateTargets } from "./media-download.js";
8
+ import { isJsonNumber, isJsonString } from "./types.js";
8
9
  /**
9
10
  * Expected, user-facing failure of the codex provider. Carries a clean
10
11
  * message plus any output Codex itself emitted, so the caller can present
@@ -63,7 +64,7 @@ export function parseCodexInput(input) {
63
64
  let prompt = "";
64
65
  for (const key of PROMPT_KEYS) {
65
66
  const v = input[key];
66
- if (typeof v === "string" && v.trim().length > 0) {
67
+ if (isJsonString(v) && v.trim().length > 0) {
67
68
  prompt = v.trim();
68
69
  break;
69
70
  }
@@ -71,7 +72,7 @@ export function parseCodexInput(input) {
71
72
  let count = 1;
72
73
  for (const key of COUNT_KEYS) {
73
74
  const v = input[key];
74
- if (typeof v === "number" && Number.isFinite(v)) {
75
+ if (isJsonNumber(v)) {
75
76
  count = Math.max(1, Math.min(MAX_IMAGES, Math.floor(v)));
76
77
  break;
77
78
  }
@@ -79,11 +80,11 @@ export function parseCodexInput(input) {
79
80
  const referenceCandidates = [];
80
81
  for (const key of REF_KEYS) {
81
82
  const v = input[key];
82
- if (typeof v === "string")
83
+ if (isJsonString(v))
83
84
  referenceCandidates.push(v);
84
85
  else if (Array.isArray(v)) {
85
86
  for (const item of v)
86
- if (typeof item === "string")
87
+ if (isJsonString(item))
87
88
  referenceCandidates.push(item);
88
89
  }
89
90
  }
@@ -92,15 +93,15 @@ export function parseCodexInput(input) {
92
93
  function buildSizeHint(input) {
93
94
  const parts = [];
94
95
  const size = input.image_size ?? input.size;
95
- if (typeof size === "string" && size.trim().length > 0)
96
+ if (isJsonString(size) && size.trim().length > 0)
96
97
  parts.push(size.trim());
97
98
  const aspect = input.aspect_ratio;
98
- if (typeof aspect === "string" && aspect.trim().length > 0) {
99
+ if (isJsonString(aspect) && aspect.trim().length > 0) {
99
100
  parts.push(`aspect ratio ${aspect.trim()}`);
100
101
  }
101
102
  const w = input.width;
102
103
  const h = input.height;
103
- if (typeof w === "number" && typeof h === "number")
104
+ if (isJsonNumber(w) && isJsonNumber(h))
104
105
  parts.push(`${w}x${h}px`);
105
106
  return parts.length > 0 ? parts.join(", ") : undefined;
106
107
  }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
+ import { isJsonObject, isJsonString } from "./types.js";
3
4
  const FILENAME = "vibedgames.json";
4
5
  /**
5
6
  * The slug grammar every surface must agree on — it is the deploy target, the
@@ -34,13 +35,13 @@ export function readProjectConfig(dir) {
34
35
  return null;
35
36
  const raw = readFileSync(path, "utf-8");
36
37
  const parsed = JSON.parse(raw);
37
- if (!parsed ||
38
- typeof parsed !== "object" ||
39
- !("slug" in parsed) ||
40
- typeof parsed.slug !== "string") {
38
+ if (!isJsonObject(parsed) || !isJsonString(parsed.slug)) {
41
39
  throw new Error(`${FILENAME} is malformed — missing "slug".`);
42
40
  }
43
- return parsed;
41
+ const config = { slug: parsed.slug };
42
+ if (isJsonString(parsed.name))
43
+ config.name = parsed.name;
44
+ return config;
44
45
  }
45
46
  export function writeProjectConfig(dir, config) {
46
47
  const path = join(dir, FILENAME);
@@ -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,7 +11,7 @@ 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: {
@@ -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) {
@@ -98,7 +98,7 @@ function extFromUrl(url) {
98
98
  // The extension each content type genuinely is. Only formats an agent is
99
99
  // likely to hand to a decoder afterwards need an entry; anything absent is
100
100
  // left alone rather than guessed at.
101
- const EXT_FOR_CONTENT_TYPE = {
101
+ const EXT_FOR_CONTENT_TYPE = new Map(Object.entries({
102
102
  "image/png": "png",
103
103
  "image/jpeg": "jpg",
104
104
  "image/webp": "webp",
@@ -110,14 +110,14 @@ const EXT_FOR_CONTENT_TYPE = {
110
110
  "audio/mpeg": "mp3",
111
111
  "audio/wav": "wav",
112
112
  "audio/ogg": "ogg",
113
- };
113
+ }));
114
114
  // Extensions that name the same format, so `.jpg` for `image/jpeg` is not a lie.
115
- const EXT_ALIASES = {
115
+ const EXT_ALIASES = new Map(Object.entries({
116
116
  jpeg: "jpg",
117
117
  tif: "tiff",
118
118
  htm: "html",
119
- };
120
- const canonicalExt = (ext) => EXT_ALIASES[ext] ?? ext;
119
+ }));
120
+ const canonicalExt = (ext) => EXT_ALIASES.get(ext) ?? ext;
121
121
  /**
122
122
  * The extension the caller asked for versus the bytes actually served.
123
123
  *
@@ -130,7 +130,7 @@ function mislabelOf(target, ref) {
130
130
  const asked = canonicalExt(extname(target).slice(1).toLowerCase());
131
131
  if (!asked)
132
132
  return null;
133
- const actual = ref.contentType ? EXT_FOR_CONTENT_TYPE[ref.contentType] : undefined;
133
+ const actual = ref.contentType ? EXT_FOR_CONTENT_TYPE.get(ref.contentType) : undefined;
134
134
  if (!actual || canonicalExt(actual) === asked)
135
135
  return null;
136
136
  return { path: target, actual };
@@ -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
  }
@@ -21,11 +21,11 @@ function declaredNames(argsDef) {
21
21
  // citty accepts a camelCase arg under its kebab spelling too.
22
22
  names.add(name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`));
23
23
  const alias = spec.alias;
24
- if (typeof alias === "string")
25
- names.add(alias);
26
- else if (Array.isArray(alias))
24
+ if (Array.isArray(alias))
27
25
  for (const a of alias)
28
26
  names.add(a);
27
+ else if (alias !== undefined)
28
+ names.add(alias);
29
29
  }
30
30
  // citty answers these itself; they never reach a command's `args`.
31
31
  names.add("help");
@@ -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
  }
@@ -1,6 +1,7 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { getConfigDir } from "./config.js";
4
+ import { isJsonNumber, isJsonObject, isJsonString } from "./types.js";
4
5
  import { join } from "node:path";
5
6
  const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
6
7
  const VERSION_RE = /^\d+\.\d+\.\d+$/;
@@ -13,9 +14,9 @@ function getLastCheckedAt() {
13
14
  return 0;
14
15
  try {
15
16
  const data = JSON.parse(readFileSync(path, "utf-8"));
16
- if (typeof data === "object" && data !== null && "lastCheckedAt" in data) {
17
+ if (isJsonObject(data)) {
17
18
  const ts = data.lastCheckedAt;
18
- if (typeof ts === "number")
19
+ if (isJsonNumber(ts))
19
20
  return ts;
20
21
  }
21
22
  }
@@ -58,10 +59,12 @@ export async function fetchLatestVersion() {
58
59
  });
59
60
  if (!res.ok)
60
61
  return null;
61
- const data = await res.json();
62
- if (typeof data === "object" && data !== null && "version" in data) {
62
+ // SAFETY: res.json() is JSON.parse of the response body, which is
63
+ // structurally JsonValue.
64
+ const data = (await res.json());
65
+ if (isJsonObject(data)) {
63
66
  const version = data.version;
64
- if (typeof version === "string")
67
+ if (isJsonString(version))
65
68
  return version;
66
69
  }
67
70
  }