refactor(runtime): centralize safe JSON parsing and preserve error causes (#629)
* refactor(domain): consolidate canonical ordering and digest helpers (#624) * refactor(domain): consolidate canonical ordering and digest helpers Single owner for code-point ordering (domain/canonicalOrdering.ts) and canonical JSON digests (domain/comparisonSemantics.ts). Delete all local compareCodePoints/compareText/digestCanonical duplicates and migrate every importer. No re-export shims. * fix(ci): allow slower real browser startup * chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks Delete eslint.config.js (oxlint is the linter), drop lint:dead alias, pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run cacheable, align oxlint ignores. * fix(config): hash all test inputs for cached runs * docs: fix architecture diagram and pretty-print tool catalog Drop dangling REPLAY edges, add dotnet/reference/error/evaluation nodes. Emit 2-space JSON from the catalog generator and regenerate. * test: extract shared fixtures, drop knip carve-outs Dedupe android/apple session tests, bundler adapter headers, and reconstruction helpers into tests/support fixtures. Delete unused type aliases and the knip ignoreIssues block. Lower jscpd threshold 2.7 to 2.5. * refactor(app): split Setup and ProcessOwnership modules Extract SetupTypes/SetupHost from Setup.ts and move observation helpers into ProcessOwnershipObservation/ProcessTree. Migrate all importers including CLI commands. No re-export shims. * refactor(runtime): centralize safe JSON parsing and preserve error causes Add domain/safeJson.safeParseJson and migrate all raw JSON.parse call sites. Name catch causes and preserve failure reasons instead of swallowing; annotate genuine best-effort cleanup. * fix(runtime): retain JSON parse error causes
This commit is contained in:
@@ -6,6 +6,7 @@ import {
|
||||
BrowserObservationError,
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
|
||||
export interface CdpEvent {
|
||||
readonly method: string;
|
||||
@@ -140,13 +141,12 @@ export class CdpConnection {
|
||||
}
|
||||
|
||||
#receive(data: RawData): void {
|
||||
let message: unknown;
|
||||
try {
|
||||
message = JSON.parse(rawText(data));
|
||||
} catch {
|
||||
const parsed = safeParseJson(rawText(data));
|
||||
if (!parsed.ok) {
|
||||
this.#failPending("protocol_error");
|
||||
return;
|
||||
}
|
||||
const message: unknown = parsed.value;
|
||||
if (!isRecord(message)) {
|
||||
this.#failPending("protocol_error");
|
||||
return;
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type BrowserObservationOperation,
|
||||
} from "../domain/errors.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
|
||||
const endpointVersionSchema = z.object({
|
||||
Browser: z.string().min(1),
|
||||
@@ -304,17 +305,18 @@ export const readCdpJson = async (
|
||||
const chunks: Buffer[] = [];
|
||||
response.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
response.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
const parsed = safeParseJson(Buffer.concat(chunks).toString("utf8"));
|
||||
if (!parsed.ok) {
|
||||
reject(
|
||||
new BrowserObservationError(
|
||||
operation,
|
||||
"invalid_endpoint_response",
|
||||
{ cause },
|
||||
{ cause: parsed.cause },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
resolve(parsed.value);
|
||||
});
|
||||
response.on("error", (cause: unknown) =>
|
||||
reject(endpointFailure(cause, operation, signal)),
|
||||
|
||||
@@ -60,8 +60,9 @@ export const closeCdpTargetSession = async (
|
||||
}
|
||||
try {
|
||||
await connection.send(`${domain}.disable`, {}, sessionId, signal);
|
||||
} catch {
|
||||
// Cleanup continues to the detach or direct-socket close boundary.
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: domain disable continues to detach/close boundary.
|
||||
void cause;
|
||||
}
|
||||
}
|
||||
if (signal?.aborted === true) {
|
||||
@@ -76,8 +77,9 @@ export const closeCdpTargetSession = async (
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
} catch {
|
||||
// Closing REA's socket is the final non-destructive cleanup boundary.
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: closing REA's socket is the final cleanup boundary.
|
||||
void cause;
|
||||
}
|
||||
await connection.close();
|
||||
};
|
||||
|
||||
@@ -178,6 +178,8 @@ export const closePlaywrightScenarioBrowser = async (
|
||||
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
|
||||
}
|
||||
})();
|
||||
// best-effort cleanup: the bounded execution boundary below observes the
|
||||
// same cleanup promise; this early attachment only prevents unhandled rejection.
|
||||
void cleanup.catch(() => undefined);
|
||||
// The shared execution boundary rejects cancellation/timeouts instead of
|
||||
// returning a successful capture whose browser or profile may still exist.
|
||||
|
||||
@@ -201,6 +201,8 @@ export const closeInspectorConnection = async (
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
const closing = connection.close();
|
||||
// best-effort cleanup: the race below observes the close; this only prevents
|
||||
// unhandled rejection when the caller abandons the close via cancellation.
|
||||
void closing.catch(() => undefined);
|
||||
// CdpConnection.close has its own one second transport bound. Do not make a
|
||||
// cancelled caller wait for that fallback.
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
} from "../domain/webBundleAnalysis.js";
|
||||
import { webSourceMapsSchema } from "../domain/webBundleAnalysis.js";
|
||||
import { createWebTextArtifact } from "../domain/webContentArtifact.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
|
||||
export interface WebSourceMapRequest {
|
||||
readonly scriptKey: string;
|
||||
@@ -272,12 +273,9 @@ const originalModuleEdges = (
|
||||
};
|
||||
|
||||
const validSourceMapEnvelope = (text: string): boolean => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const parsedResult = safeParseJson(text);
|
||||
if (!parsedResult.ok) return false;
|
||||
const parsed: unknown = parsedResult.value;
|
||||
if (!isRecord(parsed) || parsed.version !== 3) return false;
|
||||
if (typeof parsed.mappings === "string") return validSourceMapLeaf(parsed);
|
||||
if (!Array.isArray(parsed.sections)) return false;
|
||||
|
||||
Reference in New Issue
Block a user