vibedgames 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/completions.d.ts +1 -1
  3. package/dist/commands/completions.js +21 -20
  4. package/dist/commands/credits.d.ts +5 -5
  5. package/dist/commands/credits.js +45 -47
  6. package/dist/commands/deploy.d.ts +10 -10
  7. package/dist/commands/deploy.js +157 -137
  8. package/dist/commands/factory.d.ts +1 -1
  9. package/dist/commands/factory.js +18 -15
  10. package/dist/commands/fork.d.ts +14 -14
  11. package/dist/commands/fork.js +53 -45
  12. package/dist/commands/generate.js +343 -286
  13. package/dist/commands/init.d.ts +8 -8
  14. package/dist/commands/init.js +31 -24
  15. package/dist/commands/login.js +14 -14
  16. package/dist/commands/logout.js +2 -2
  17. package/dist/commands/new.d.ts +16 -16
  18. package/dist/commands/new.js +191 -165
  19. package/dist/commands/playtest.d.ts +5 -5
  20. package/dist/commands/playtest.js +103 -97
  21. package/dist/commands/update.d.ts +7 -7
  22. package/dist/commands/update.js +22 -17
  23. package/dist/commands/whoami.d.ts +5 -5
  24. package/dist/commands/whoami.js +11 -10
  25. package/dist/index.js +12 -10
  26. package/dist/lib/api.d.ts +16 -4
  27. package/dist/lib/api.js +20 -32
  28. package/dist/lib/archive.d.ts +4 -4
  29. package/dist/lib/archive.js +123 -102
  30. package/dist/lib/codex.d.ts +46 -15
  31. package/dist/lib/codex.js +178 -108
  32. package/dist/lib/config-file.d.ts +6 -6
  33. package/dist/lib/config-file.js +33 -30
  34. package/dist/lib/config.d.ts +8 -8
  35. package/dist/lib/config.js +38 -30
  36. package/dist/lib/manifest.d.ts +3 -3
  37. package/dist/lib/manifest.js +44 -40
  38. package/dist/lib/media-args.d.ts +8 -6
  39. package/dist/lib/media-args.js +113 -94
  40. package/dist/lib/media-download.d.ts +9 -8
  41. package/dist/lib/media-download.js +158 -144
  42. package/dist/lib/media-poll.d.ts +8 -7
  43. package/dist/lib/media-poll.js +38 -32
  44. package/dist/lib/media-upload.d.ts +1 -1
  45. package/dist/lib/media-upload.js +30 -29
  46. package/dist/lib/output.d.ts +34 -11
  47. package/dist/lib/output.js +28 -20
  48. package/dist/lib/package-manager.d.ts +3 -3
  49. package/dist/lib/package-manager.js +27 -22
  50. package/dist/lib/run.d.ts +4 -4
  51. package/dist/lib/run.js +7 -4
  52. package/dist/lib/strict-args.d.ts +4 -4
  53. package/dist/lib/strict-args.js +29 -19
  54. package/dist/lib/types.d.ts +16 -2
  55. package/dist/lib/types.js +10 -4
  56. package/dist/lib/update.d.ts +4 -4
  57. package/dist/lib/update.js +47 -35
  58. package/dist/lib/upload.d.ts +4 -4
  59. package/dist/lib/upload.js +14 -9
  60. package/package.json +7 -8
@@ -7,39 +7,62 @@
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
- export type OutputArgs = {
10
+ export interface OutputArgs {
11
11
  json?: boolean;
12
12
  field?: string;
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
+ };
22
+ /**
23
+ * What a command may hand to `writeStructured`: a JSON value, or a payload
24
+ * type declared member by member.
25
+ *
26
+ * The second arm exists because TypeScript grants an implicit index signature
27
+ * only to a type alias, never to an interface — declaration merging could add
28
+ * members later, so an interface's keys are never assumed and it is not
29
+ * assignable to `OutputValue`'s object arm. Mapping the payload's own keys
30
+ * checks each one against `OutputValue` instead, which still rejects a `Date`
31
+ * or a method where `[key: string]: unknown` on every payload would not.
32
+ */
33
+ type OutputPayload<T> = OutputValue | {
34
+ [K in keyof T]: OutputValue;
13
35
  };
14
- export declare function isJsonOutput(args: OutputArgs): boolean;
15
- export declare function writeJson(value: unknown): void;
36
+ export declare const isJsonOutput: (args: OutputArgs) => boolean;
37
+ export declare const writeJson: (value: OutputValue) => void;
16
38
  /**
17
39
  * Resolve a dotted path against a decoded JSON value. Supports array indexing
18
40
  * in both `items[0]` and `items.0` spellings, since agents write both.
19
41
  * Returns `undefined` for any path that doesn't resolve.
20
42
  */
21
- export declare function selectField(value: unknown, path: string): unknown;
43
+ export declare const selectField: (value: OutputValue, path: string) => OutputValue;
22
44
  /**
23
45
  * Render one selected value for shell capture. Scalars print bare so
24
46
  * `$(vg ... --field url)` needs no unquoting; arrays of scalars print one per
25
47
  * line so they can be looped over; anything structural falls back to JSON.
26
48
  */
27
- export declare function formatField(value: unknown): string;
49
+ export declare const formatField: (value: OutputValue) => string;
28
50
  /**
29
51
  * The standard exit path for a command that produced structured data.
30
52
  * `--field` wins over `--json` when both are passed, since asking for one
31
53
  * value is the more specific request. Returns false when neither flag was
32
54
  * given, so the caller can fall through to its human-readable rendering.
33
55
  */
34
- export declare function writeStructured(value: unknown, args: OutputArgs): boolean;
56
+ export declare const writeStructured: <T extends OutputPayload<T>>(value: T, args: OutputArgs) => boolean;
35
57
  /** The `--json`/`--field` arg pair, for spreading into a citty `args` block. */
36
58
  export declare const outputArgs: {
37
- readonly json: {
38
- readonly type: "boolean";
39
- readonly description: "Print structured JSON to stdout.";
40
- };
41
59
  readonly field: {
42
- readonly type: "string";
43
60
  readonly description: "Print a single value from the JSON result, e.g. --field request_id or --field images[0].url. Prints scalars bare for shell capture.";
61
+ readonly type: "string";
62
+ };
63
+ readonly json: {
64
+ readonly description: "Print structured JSON to stdout.";
65
+ readonly type: "boolean";
44
66
  };
45
67
  };
68
+ export {};
@@ -7,66 +7,74 @@
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
- export function isJsonOutput(args) {
11
- return Boolean(args.json) || process.env.VG_JSON_OUTPUT === "1";
12
- }
13
- export function writeJson(value) {
10
+ const isOutputObject = (value) =>
11
+ // Object() is the identity only on objects; arrays are split off explicitly.
12
+ Object(value) === value && !Array.isArray(value);
13
+ export const isJsonOutput = (args) => Boolean(args.json) || process.env.VG_JSON_OUTPUT === "1";
14
+ export const writeJson = (value) => {
14
15
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
15
- }
16
+ };
16
17
  /**
17
18
  * Resolve a dotted path against a decoded JSON value. Supports array indexing
18
19
  * in both `items[0]` and `items.0` spellings, since agents write both.
19
20
  * Returns `undefined` for any path that doesn't resolve.
20
21
  */
21
- export function selectField(value, path) {
22
+ export const selectField = (value, path) => {
22
23
  const segments = path
23
- .replace(/\[(-?\d+)\]/g, ".$1")
24
+ .replaceAll(/\[(?<index>-?\d+)\]/gu, ".$<index>")
24
25
  .split(".")
25
26
  .filter(Boolean);
26
27
  let current = value;
27
28
  for (const segment of segments) {
28
- if (current === null || current === undefined)
29
+ if (current === null || current === undefined) {
29
30
  return undefined;
31
+ }
30
32
  if (Array.isArray(current)) {
31
33
  const index = Number(segment);
32
- if (!Number.isInteger(index))
34
+ if (!Number.isInteger(index)) {
33
35
  return undefined;
36
+ }
34
37
  // Negative indices count from the end, which is handy for "the last
35
38
  // frame" style selections.
36
39
  current = current.at(index);
37
40
  continue;
38
41
  }
39
- if (typeof current !== "object")
42
+ if (!isOutputObject(current)) {
40
43
  return undefined;
44
+ }
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
+ const isScalarEntry = (value) => value === null || (value !== undefined && Object(value) !== value);
45
51
  /**
46
52
  * Render one selected value for shell capture. Scalars print bare so
47
53
  * `$(vg ... --field url)` needs no unquoting; arrays of scalars print one per
48
54
  * line so they can be looped over; anything structural falls back to JSON.
49
55
  */
50
- export function formatField(value) {
51
- if (value === null || value === undefined)
56
+ export const formatField = (value) => {
57
+ if (value === null || value === undefined) {
52
58
  return "";
59
+ }
53
60
  if (Array.isArray(value)) {
54
- if (value.every((v) => v === null || ["string", "number", "boolean"].includes(typeof v))) {
61
+ if (value.every(isScalarEntry)) {
55
62
  return value.map((v) => (v === null ? "" : String(v))).join("\n");
56
63
  }
57
64
  return JSON.stringify(value, null, 2);
58
65
  }
59
- if (typeof value === "object")
66
+ if (isOutputObject(value)) {
60
67
  return JSON.stringify(value, null, 2);
68
+ }
61
69
  return String(value);
62
- }
70
+ };
63
71
  /**
64
72
  * The standard exit path for a command that produced structured data.
65
73
  * `--field` wins over `--json` when both are passed, since asking for one
66
74
  * value is the more specific request. Returns false when neither flag was
67
75
  * given, so the caller can fall through to its human-readable rendering.
68
76
  */
69
- export function writeStructured(value, args) {
77
+ export const writeStructured = (value, args) => {
70
78
  if (args.field) {
71
79
  const selected = selectField(value, args.field);
72
80
  if (selected === undefined) {
@@ -83,12 +91,12 @@ export function writeStructured(value, args) {
83
91
  return true;
84
92
  }
85
93
  return false;
86
- }
94
+ };
87
95
  /** The `--json`/`--field` arg pair, for spreading into a citty `args` block. */
88
96
  export const outputArgs = {
89
- json: { type: "boolean", description: "Print structured JSON to stdout." },
90
97
  field: {
91
- type: "string",
92
98
  description: "Print a single value from the JSON result, e.g. --field request_id or --field images[0].url. Prints scalars bare for shell capture.",
99
+ type: "string",
93
100
  },
101
+ json: { description: "Print structured JSON to stdout.", type: "boolean" },
94
102
  };
@@ -18,8 +18,8 @@ export declare const PKG_NAME = "vibedgames";
18
18
  * `installPath` is where the CLI is installed — normally the directory this
19
19
  * module resolves from. Bun's own runtime is a signal in its own right.
20
20
  */
21
- export declare function detectPackageManager(installPath: string, env?: NodeJS.ProcessEnv): PackageManager;
21
+ export declare const detectPackageManager: (installPath: string, env?: NodeJS.ProcessEnv) => PackageManager;
22
22
  /** The argv that installs or upgrades a package globally, per manager. */
23
- export declare function globalInstallArgs(manager: PackageManager, pkg?: string): string[];
23
+ export declare const globalInstallArgs: (manager: PackageManager, pkg?: string) => string[];
24
24
  /** The command a user can copy-paste when the automatic update can't run. */
25
- export declare function globalInstallCommand(manager: PackageManager, pkg?: string): string;
25
+ export declare const globalInstallCommand: (manager: PackageManager, pkg?: string) => string;
@@ -22,51 +22,56 @@ export const PKG_NAME = "vibedgames";
22
22
  * directory named after them.
23
23
  */
24
24
  const SIGNATURES = [
25
- ["bun", /[/\\]\.bun[/\\]/],
25
+ ["bun", /[/\\]\.bun[/\\]/u],
26
26
  // pnpm's global store, not a project-local `node_modules/.pnpm`.
27
- ["pnpm", /[/\\](?:pnpm[/\\]global|\.pnpm-global|Library[/\\]pnpm)[/\\]/],
28
- ["yarn", /[/\\](?:\.yarn|yarn[/\\]global|\.config[/\\]yarn)[/\\]/],
29
- ["npm", /[/\\]lib[/\\]node_modules[/\\]/],
30
- ["npm", /[/\\]npm[/\\]node_modules[/\\]/],
27
+ ["pnpm", /[/\\](?:pnpm[/\\]global|\.pnpm-global|Library[/\\]pnpm)[/\\]/u],
28
+ ["yarn", /[/\\](?:\.yarn|yarn[/\\]global|\.config[/\\]yarn)[/\\]/u],
29
+ ["npm", /[/\\]lib[/\\]node_modules[/\\]/u],
30
+ ["npm", /[/\\]npm[/\\]node_modules[/\\]/u],
31
31
  ];
32
32
  /**
33
33
  * `npm_config_user_agent` is set by whichever manager is running us — reliable
34
34
  * when `vg` was invoked through a script (`pnpm vg …`), absent otherwise.
35
35
  */
36
- function fromUserAgent(userAgent) {
37
- if (!userAgent)
36
+ const fromUserAgent = (userAgent) => {
37
+ if (!userAgent) {
38
38
  return null;
39
- const name = userAgent.split("/")[0];
39
+ }
40
+ const [name] = userAgent.split("/");
40
41
  return name === "npm" || name === "pnpm" || name === "yarn" || name === "bun" ? name : null;
41
- }
42
+ };
42
43
  /**
43
44
  * `installPath` is where the CLI is installed — normally the directory this
44
45
  * module resolves from. Bun's own runtime is a signal in its own right.
45
46
  */
46
- export function detectPackageManager(installPath, env = process.env) {
47
+ export const detectPackageManager = (installPath, env = process.env) => {
47
48
  for (const [manager, signature] of SIGNATURES) {
48
- if (signature.test(installPath))
49
+ if (signature.test(installPath)) {
49
50
  return manager;
51
+ }
50
52
  }
51
53
  // Bun reports itself in versions; running under it means `bun add` works.
52
- if (typeof globalThis.Bun !== "undefined")
54
+ if ("Bun" in globalThis) {
53
55
  return "bun";
56
+ }
54
57
  return fromUserAgent(env.npm_config_user_agent) ?? "npm";
55
- }
58
+ };
56
59
  /** The argv that installs or upgrades a package globally, per manager. */
57
- export function globalInstallArgs(manager, pkg = PKG_NAME) {
60
+ export const globalInstallArgs = (manager, pkg = PKG_NAME) => {
58
61
  switch (manager) {
59
- case "pnpm":
62
+ case "pnpm": {
60
63
  return ["add", "-g", pkg];
61
- case "yarn":
64
+ }
65
+ case "yarn": {
62
66
  return ["global", "add", pkg];
63
- case "bun":
67
+ }
68
+ case "bun": {
64
69
  return ["add", "-g", pkg];
65
- case "npm":
70
+ }
71
+ default: {
66
72
  return ["install", "-g", pkg];
73
+ }
67
74
  }
68
- }
75
+ };
69
76
  /** The command a user can copy-paste when the automatic update can't run. */
70
- export function globalInstallCommand(manager, pkg = PKG_NAME) {
71
- return `${manager} ${globalInstallArgs(manager, pkg).join(" ")}`;
72
- }
77
+ export const globalInstallCommand = (manager, pkg = PKG_NAME) => `${manager} ${globalInstallArgs(manager, pkg).join(" ")}`;
package/dist/lib/run.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- export type RunResult = {
1
+ export interface RunResult {
2
2
  code: number;
3
3
  output: string;
4
- };
5
- export type RunOptions = {
4
+ }
5
+ export interface RunOptions {
6
6
  /**
7
7
  * Mirror the child's output to this process as it arrives. Long steps
8
8
  * (`npx skills add` clones a repo per skill) otherwise look hung: the
9
9
  * buffered output is only readable once the child has already exited.
10
10
  */
11
11
  stream?: boolean;
12
- };
12
+ }
13
13
  /**
14
14
  * True when the command never started, as opposed to running and failing.
15
15
  * `run` turns a spawn error into an exit code, so the message is the only
package/dist/lib/run.js CHANGED
@@ -4,17 +4,20 @@ import spawn from "cross-spawn";
4
4
  * `run` turns a spawn error into an exit code, so the message is the only
5
5
  * thing that separates "no such binary" from "the binary said no".
6
6
  */
7
- export const isMissingCommand = (result) => result.code !== 0 && /ENOENT|not found|not recognized/i.test(result.output);
8
- export const run = (cmd, args, options = {}) => new Promise((resolve) => {
7
+ export const isMissingCommand = (result) => result.code !== 0 && /ENOENT|not found|not recognized/iu.test(result.output);
8
+ export const run = (cmd, args, options = {}) =>
9
+ // oxlint-disable-next-line promise/avoid-new -- child_process.spawn is event-based
10
+ new Promise((resolve) => {
9
11
  const chunks = [];
10
12
  const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
11
13
  const collect = (stream) => (c) => {
12
14
  chunks.push(c);
13
- if (options.stream)
15
+ if (options.stream) {
14
16
  stream.write(c);
17
+ }
15
18
  };
16
19
  child.stdout?.on("data", collect(process.stderr));
17
20
  child.stderr?.on("data", collect(process.stderr));
18
21
  child.on("error", (err) => resolve({ code: 1, output: `${err.message}\n` }));
19
- child.on("close", (code) => resolve({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
22
+ child.on("close", (code) => resolve({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf-8") }));
20
23
  });
@@ -12,16 +12,16 @@
12
12
  * and `vg playtest`/`vg factory` are passthroughs to another binary's grammar.
13
13
  */
14
14
  /** The subset of citty's `ArgDef` this check reads. */
15
- type ArgSpec = {
15
+ interface ArgSpec {
16
16
  type?: string;
17
17
  alias?: string | string[];
18
- };
18
+ }
19
19
  /**
20
20
  * The long flags in `rawArgs` that `argsDef` does not declare, in the order
21
21
  * they were typed. Everything after a bare `--` is a passthrough payload and is
22
22
  * left alone.
23
23
  */
24
- export declare function unknownFlags(rawArgs: string[], argsDef: Record<string, ArgSpec>): string[];
24
+ export declare const unknownFlags: (rawArgs: string[], argsDef: Record<string, ArgSpec>) => string[];
25
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;
26
+ export declare const assertKnownFlags: (rawArgs: string[], argsDef: Record<string, ArgSpec>) => void;
27
27
  export {};
@@ -12,57 +12,67 @@
12
12
  * and `vg playtest`/`vg factory` are passthroughs to another binary's grammar.
13
13
  */
14
14
  const UNRECOGNIZED_EXIT = 2;
15
- function declaredNames(argsDef) {
15
+ const declaredNames = (argsDef) => {
16
16
  const names = new Set();
17
17
  for (const [name, spec] of Object.entries(argsDef)) {
18
- if (spec.type === "positional")
18
+ if (spec.type === "positional") {
19
19
  continue;
20
+ }
20
21
  names.add(name);
21
22
  // 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 (typeof alias === "string")
25
- names.add(alias);
26
- else if (Array.isArray(alias))
27
- for (const a of alias)
23
+ names.add(name.replaceAll(/[A-Z]/gu, (c) => `-${c.toLowerCase()}`));
24
+ const { alias } = spec;
25
+ if (Array.isArray(alias)) {
26
+ for (const a of alias) {
28
27
  names.add(a);
28
+ }
29
+ }
30
+ else if (alias !== undefined) {
31
+ names.add(alias);
32
+ }
29
33
  }
30
34
  // citty answers these itself; they never reach a command's `args`.
31
35
  names.add("help");
32
36
  names.add("version");
33
37
  return names;
34
- }
38
+ };
35
39
  /**
36
40
  * The long flags in `rawArgs` that `argsDef` does not declare, in the order
37
41
  * they were typed. Everything after a bare `--` is a passthrough payload and is
38
42
  * left alone.
39
43
  */
40
- export function unknownFlags(rawArgs, argsDef) {
44
+ export const unknownFlags = (rawArgs, argsDef) => {
41
45
  const known = declaredNames(argsDef);
42
46
  const unknown = [];
43
47
  for (const raw of rawArgs) {
44
- if (raw === "--")
48
+ if (raw === "--") {
45
49
  break;
46
- if (!raw.startsWith("--") || raw.length === 2)
50
+ }
51
+ if (!raw.startsWith("--") || raw.length === 2) {
47
52
  continue;
53
+ }
48
54
  const flag = (raw.slice(2).split("=")[0] ?? "").trim();
49
- if (flag.length === 0)
55
+ if (flag.length === 0) {
50
56
  continue;
57
+ }
51
58
  // `--no-foo` is citty's negation of the boolean `foo`.
52
59
  const negated = flag.startsWith("no-") ? flag.slice(3) : null;
53
- if (known.has(flag))
60
+ if (known.has(flag)) {
54
61
  continue;
55
- if (negated !== null && known.has(negated))
62
+ }
63
+ if (negated !== null && known.has(negated)) {
56
64
  continue;
65
+ }
57
66
  unknown.push(`--${flag}`);
58
67
  }
59
68
  return unknown;
60
- }
69
+ };
61
70
  /** Exit 2 naming every undeclared flag, or return so the command can run. */
62
- export function assertKnownFlags(rawArgs, argsDef) {
71
+ export const assertKnownFlags = (rawArgs, argsDef) => {
63
72
  const unknown = unknownFlags(rawArgs, argsDef);
64
- if (unknown.length === 0)
73
+ if (unknown.length === 0) {
65
74
  return;
75
+ }
66
76
  process.stderr.write(`unrecognized arguments: ${unknown.join(" ")}\n`);
67
77
  process.exit(UNRECOGNIZED_EXIT);
68
- }
78
+ };
@@ -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 interface JsonObject {
12
+ [key: string]: JsonValue;
13
+ }
14
+ export declare const isJsonObject: (value: JsonValue | undefined) => value is JsonObject;
15
+ export declare const isJsonString: (value: JsonValue | undefined) => value is string;
16
+ export declare const isJsonNumber: (value: JsonValue | undefined) => value is number;
package/dist/lib/types.js CHANGED
@@ -1,4 +1,10 @@
1
- /** Type-guard helpers shared across CLI modules. */
2
- export function isRecord(value) {
3
- return typeof value === "object" && value !== null && !Array.isArray(value);
4
- }
1
+ /** JSON domain types and guards shared across CLI modules. */
2
+ export const isJsonObject = (value) =>
3
+ // Object() is the identity only on objects; arrays are split off explicitly.
4
+ Object(value) === value && !Array.isArray(value);
5
+ export const isJsonString = (value) =>
6
+ // String() is the identity only on strings.
7
+ String(value) === value;
8
+ export const isJsonNumber = (value) =>
9
+ // JSON cannot encode NaN/Infinity, so isFinite matches every JSON number.
10
+ Number.isFinite(value);
@@ -1,10 +1,10 @@
1
- export declare function markUpdateChecked(): void;
2
- export declare function isNewerVersion(latest: string, current: string): boolean;
3
- export declare function fetchLatestVersion(): Promise<string | null>;
1
+ export declare const markUpdateChecked: () => void;
2
+ export declare const isNewerVersion: (latest: string, current: string) => boolean;
3
+ export declare const fetchLatestVersion: () => Promise<string | null>;
4
4
  /**
5
5
  * Fire-and-forget background update: at most once per day (and never in CI
6
6
  * or with VG_NO_AUTO_UPDATE set), re-invoke this CLI as a detached
7
7
  * `vg update --auto`, which only applies anything when npm has a newer
8
8
  * version. The foreground command pays no latency and prints nothing.
9
9
  */
10
- export declare function maybeScheduleAutoUpdate(): void;
10
+ export declare const maybeScheduleAutoUpdate: () => void;
@@ -1,89 +1,101 @@
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 { join } from "node:path";
4
+ import { isJsonNumber, isJsonObject, isJsonString } from "./types.js";
5
+ import path from "node:path";
5
6
  const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
6
- const VERSION_RE = /^\d+\.\d+\.\d+$/;
7
- function getCachePath() {
8
- return join(getConfigDir(), "update-check.json");
9
- }
10
- function getLastCheckedAt() {
11
- const path = getCachePath();
12
- if (!existsSync(path))
7
+ const VERSION_RE = /^\d+\.\d+\.\d+$/u;
8
+ const getCachePath = () => path.join(getConfigDir(), "update-check.json");
9
+ const getLastCheckedAt = () => {
10
+ const cache = getCachePath();
11
+ if (!existsSync(cache)) {
13
12
  return 0;
13
+ }
14
14
  try {
15
- const data = JSON.parse(readFileSync(path, "utf-8"));
16
- if (typeof data === "object" && data !== null && "lastCheckedAt" in data) {
15
+ const data = JSON.parse(readFileSync(cache, "utf-8"));
16
+ if (isJsonObject(data)) {
17
17
  const ts = data.lastCheckedAt;
18
- if (typeof ts === "number")
18
+ if (isJsonNumber(ts)) {
19
19
  return ts;
20
+ }
20
21
  }
21
22
  }
22
23
  catch {
23
24
  // corrupt cache — treat as never checked
24
25
  }
25
26
  return 0;
26
- }
27
- export function markUpdateChecked() {
27
+ };
28
+ export const markUpdateChecked = () => {
28
29
  const dir = getConfigDir();
29
30
  try {
30
- if (!existsSync(dir))
31
- mkdirSync(dir, { recursive: true, mode: 0o700 });
31
+ if (!existsSync(dir)) {
32
+ mkdirSync(dir, { mode: 0o700, recursive: true });
33
+ }
32
34
  writeFileSync(getCachePath(), JSON.stringify({ lastCheckedAt: Date.now() }, null, 2));
33
35
  }
34
36
  catch {
35
37
  // best-effort; worst case we check again next run
36
38
  }
37
- }
38
- export function isNewerVersion(latest, current) {
39
- if (!VERSION_RE.test(latest) || !VERSION_RE.test(current))
39
+ };
40
+ export const isNewerVersion = (latest, current) => {
41
+ if (!VERSION_RE.test(latest) || !VERSION_RE.test(current)) {
40
42
  return false;
43
+ }
41
44
  const a = latest.split(".").map(Number);
42
45
  const b = current.split(".").map(Number);
43
- for (let i = 0; i < 3; i++) {
46
+ for (let i = 0; i < 3; i += 1) {
44
47
  const left = a[i] ?? 0;
45
48
  const right = b[i] ?? 0;
46
- if (left > right)
49
+ if (left > right) {
47
50
  return true;
48
- if (left < right)
51
+ }
52
+ if (left < right) {
49
53
  return false;
54
+ }
50
55
  }
51
56
  return false;
52
- }
53
- export async function fetchLatestVersion() {
57
+ };
58
+ export const fetchLatestVersion = async () => {
54
59
  const registry = process.env.VG_REGISTRY_URL ?? "https://registry.npmjs.org";
55
60
  try {
56
61
  const res = await fetch(`${registry}/vibedgames/latest`, {
57
62
  signal: AbortSignal.timeout(5000),
58
63
  });
59
- if (!res.ok)
64
+ if (!res.ok) {
60
65
  return null;
61
- const data = await res.json();
62
- if (typeof data === "object" && data !== null && "version" in data) {
63
- const version = data.version;
64
- if (typeof version === "string")
66
+ }
67
+ // SAFETY: res.json() is JSON.parse of the response body, which is
68
+ // structurally JsonValue.
69
+ const data = (await res.json());
70
+ if (isJsonObject(data)) {
71
+ const { version } = data;
72
+ if (isJsonString(version)) {
65
73
  return version;
74
+ }
66
75
  }
67
76
  }
68
77
  catch {
69
78
  // offline or registry down — skip this round
70
79
  }
71
80
  return null;
72
- }
81
+ };
73
82
  /**
74
83
  * Fire-and-forget background update: at most once per day (and never in CI
75
84
  * or with VG_NO_AUTO_UPDATE set), re-invoke this CLI as a detached
76
85
  * `vg update --auto`, which only applies anything when npm has a newer
77
86
  * version. The foreground command pays no latency and prints nothing.
78
87
  */
79
- export function maybeScheduleAutoUpdate() {
80
- if (process.env.VG_NO_AUTO_UPDATE || process.env.CI)
88
+ export const maybeScheduleAutoUpdate = () => {
89
+ if (process.env.VG_NO_AUTO_UPDATE || process.env.CI) {
81
90
  return;
82
- const script = process.argv[1];
83
- if (!script)
91
+ }
92
+ const [, script] = process.argv;
93
+ if (!script) {
84
94
  return;
85
- if (Date.now() - getLastCheckedAt() < CHECK_INTERVAL_MS)
95
+ }
96
+ if (Date.now() - getLastCheckedAt() < CHECK_INTERVAL_MS) {
86
97
  return;
98
+ }
87
99
  markUpdateChecked();
88
100
  try {
89
101
  const child = spawn(process.execPath, [script, "update", "--auto"], {
@@ -95,4 +107,4 @@ export function maybeScheduleAutoUpdate() {
95
107
  catch {
96
108
  // best-effort; worst case we try again next run
97
109
  }
98
- }
110
+ };
@@ -1,16 +1,16 @@
1
1
  import type { ManifestFile } from "./manifest.js";
2
- export type UploadTarget = {
2
+ export interface UploadTarget {
3
3
  path: string;
4
4
  url: string;
5
5
  headers: Record<string, string>;
6
- };
6
+ }
7
7
  /**
8
8
  * Upload all files to their presigned PUT URLs with bounded concurrency.
9
9
  * Throws on the first non-2xx response.
10
10
  */
11
- export declare function uploadAll({ files, uploads, concurrency, onProgress, }: {
11
+ export declare const uploadAll: ({ files, uploads, concurrency, onProgress, }: {
12
12
  files: ManifestFile[];
13
13
  uploads: UploadTarget[];
14
14
  concurrency?: number;
15
15
  onProgress?: (done: number, total: number) => void;
16
- }): Promise<void>;
16
+ }) => Promise<void>;