Skip to content

Commit 4b261d4

Browse files
committed
refactor(utils): add safe JSON parsing util
- Added `safeParseJSON` utility function. - Improves error handling for JSON parsing. - Prevents crashes from invalid JSON input. - Handles undefined or null input gracefully. - Added JSON parsing error logging.
1 parent 954f874 commit 4b261d4

3 files changed

Lines changed: 20 additions & 2 deletions

File tree

src/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { UpdaterService, GitService, ChangelogService } from './services';
2-
import { FileHandler } from './utils';
2+
import { FileHandler, safeParseJSON } from './utils';
33
import { UpdaterRegistry } from './registry';
44
import {
55
PlatformDetectionError,
@@ -8,6 +8,7 @@ import {
88
InvalidManifestError,
99
} from './errors';
1010
import { RELEASE_TYPE, TARGET_PLATFORM, GIT_TAG, TARGET_PATH, BUMP_TARGETS } from './config';
11+
1112
import * as core from '@actions/core';
1213

1314
async function initializeServices() {
@@ -37,7 +38,7 @@ async function run() {
3738
const platform = updaterService.getPlatform(targetPlatform);
3839
core.info(`Detected platform: ${platform}`);
3940

40-
const bumpTargets = JSON.parse(BUMP_TARGETS);
41+
const bumpTargets = safeParseJSON<{ path: string; variable: string }[]>(BUMP_TARGETS);
4142
const version = updaterService.updateVersion(platform, releaseType, bumpTargets);
4243
core.setOutput('new_version', version);
4344

src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './versionUtil';
22
export * from './fileHandler';
33
export * from './manifestParser';
4+
export * from './jsonUtils';

src/utils/jsonUtils.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Safely parses a JSON string.
3+
* Returns null (or a fallback) if parsing fails or input is invalid.
4+
*/
5+
/* eslint-disable @typescript-eslint/no-explicit-any */
6+
export function safeParseJSON<T>(str: string | undefined | null): T | undefined {
7+
try {
8+
if (!str || typeof str !== 'string' || str.trim() === '') {
9+
return undefined;
10+
}
11+
return JSON.parse(str) as T;
12+
} catch (e) {
13+
console.error('Invalid JSON:', e);
14+
return undefined;
15+
}
16+
}

0 commit comments

Comments
 (0)