mirror of
https://github.com/OpenRouterTeam/spawn.git
synced 2026-05-20 09:31:15 +00:00
Move the PkgVersionSchema (v.object({ version: v.string() })) from its
duplicate definitions in commands/shared.ts and update-check.ts into the
shared parse module. Both consumers now import from the single source.
Bump CLI version to 0.15.22.
Co-authored-by: spawn-qa-bot <qa@openrouter.ai>
Co-authored-by: L <6723574+louisgv@users.noreply.github.com>
40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
// shared/parse.ts — Schema-validated JSON parsing (replaces unsafe `as` casts)
|
|
|
|
import * as v from "valibot";
|
|
|
|
/**
|
|
* Parse a JSON string and validate it against a valibot schema.
|
|
* Returns the validated value, or null if parsing/validation fails.
|
|
*/
|
|
export function parseJsonWith<T extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>>(
|
|
text: string,
|
|
schema: T,
|
|
): v.InferOutput<T> | null {
|
|
try {
|
|
return v.parse(schema, JSON.parse(text));
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Schema for responses containing a `version` field (npm registry, GitHub releases). */
|
|
export const PkgVersionSchema = v.object({
|
|
version: v.string(),
|
|
});
|
|
|
|
/**
|
|
* Parse a JSON string and return it as a Record<string, unknown> or null.
|
|
* Rejects non-object results (arrays, primitives).
|
|
* Use for API responses that are always a JSON object.
|
|
*/
|
|
export function parseJsonObj(text: string): Record<string, unknown> | null {
|
|
try {
|
|
const val = JSON.parse(text);
|
|
if (val !== null && typeof val === "object" && !Array.isArray(val)) {
|
|
return val;
|
|
}
|
|
return null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|