2026-10-10 01:53:59 +08:00
import { constants as bufferConstants } from "node:buffer" ;
2026-10-08 00:52:37 +08:00
import { resolve } from "node:path" ;
2026-07-16 10:21:41 +08:00
2026-10-09 13:49:54 -04:00
import {
NonRegularFileReadError ,
readRegularFile ,
} from "./application/RegularFileRead.js" ;
2026-10-10 01:53:59 +08:00
import {
AnalysisInputError ,
AnalysisResourceConstraintError ,
} from "./domain/analysisErrorCore.js" ;
2026-10-06 05:57:38 +08:00
import { projectAnalysisError } from "./domain/analysisErrorProjection.js" ;
2026-07-16 10:21:41 +08:00
import type { JsonValue } from "./domain/jsonValue.js" ;
2026-10-06 05:00:54 +08:00
import { safeParseJson } from "./domain/safeJson.js" ;
2026-07-16 10:21:41 +08:00
2026-09-29 17:00:06 +08:00
/** Parse inline JSON or one local JSON file for a CLI workflow. */
2026-07-16 10:21:41 +08:00
export const parseCliJsonInput = async (
value : string ,
operation : string ,
) : Promise <
| { readonly ok : true ; readonly value : unknown }
| { readonly ok : false ; readonly error : JsonValue }
> => {
const inline = parseJson ( value );
2026-10-10 01:53:59 +08:00
if ( inline . kind === "valid" ) return { ok : true , value : inline.value };
if ( inline . kind === "too-large" )
return jsonTooLargeError ( undefined , operation );
2026-07-16 10:21:41 +08:00
try {
2026-10-06 05:15:17 +08:00
// Read raw bytes so invalid UTF-8 is rejected by parseJson instead of
// being silently replaced by lossy "utf8" decoding.
2026-10-09 13:49:54 -04:00
const parsed = parseJson ( await readRegularFile ( value ));
2026-10-10 01:53:59 +08:00
if ( parsed . kind === "valid" ) return { ok : true , value : parsed.value };
if ( parsed . kind === "too-large" ) return jsonTooLargeError ( value , operation );
return jsonFileError ( value , operation , "invalid-json" );
2026-10-06 05:00:54 +08:00
} catch ( cause : unknown ) {
2026-10-08 00:03:36 +08:00
if (
[ "{" , "[" ]. includes ( value . trimStart ()[ 0 ] ?? "" ) &&
cannotBeAnExistingFile ( cause ) &&
! hasExplicitJsonFileExtension ( value )
)
return { ok : false , error : inputError ( operation ) };
2026-10-06 05:00:54 +08:00
return jsonFileError ( value , operation , "read-failed" , cause );
2026-07-16 10:21:41 +08:00
}
};
2026-10-08 00:52:37 +08:00
/**
* Resolve named string fields of CLI-supplied JSON against the operator
* working directory. Each entry is a key path from the document root; only
2026-10-08 19:57:54 +07:00
* fields holding nonblank strings are resolved, everything else passes through
* untouched so shared schemas can reject blank paths. Shared MCP contracts reject
* relative paths, so CLI workflows resolve operator-relative values before validation.
2026-10-08 00:52:37 +08:00
*/
export const resolveCliJsonPaths = (
value : unknown ,
paths : ReadonlyArray < ReadonlyArray < string >>,
) : unknown => {
let resolved = value ;
for ( const keys of paths ) resolved = resolveJsonPath ( resolved , keys );
return resolved ;
};
const resolveJsonPath = (
value : unknown ,
keys : ReadonlyArray < string >,
) : unknown => {
const [ head , ... tail ] = keys ;
if ( typeof value !== "object" || value === null || Array . isArray ( value ))
return value ;
const entries = Object . entries ( value ). map (
([ key , entry ] : readonly [ string , unknown ]) : readonly [ string , unknown ] => {
if ( key !== head ) return [ key , entry ];
if ( tail . length === 0 )
2026-10-08 19:57:54 +07:00
return [
key ,
typeof entry === "string" && entry . trim (). length > 0
? resolve ( entry )
: entry ,
];
2026-10-08 00:52:37 +08:00
return [ key , resolveJsonPath ( entry , tail )];
},
);
return Object . fromEntries ( entries );
};
2026-10-08 00:03:36 +08:00
const cannotBeAnExistingFile = ( cause : unknown ) : boolean =>
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
2026-10-08 01:06:31 +08:00
( cause . code === "ENOENT" ||
cause . code === "ENAMETOOLONG" ||
cause . code === "ENOTDIR" );
2026-10-08 00:03:36 +08:00
const hasExplicitJsonFileExtension = ( value : string ) : boolean =>
value . toLowerCase (). endsWith ( ".json" );
2026-10-10 01:53:59 +08:00
type JsonParseResult =
| { readonly kind : "valid" ; readonly value : unknown }
| { readonly kind : "invalid" }
| { readonly kind : "too-large" };
const parseJson = ( value : string | Uint8Array ) : JsonParseResult => {
2026-10-06 05:00:54 +08:00
let text : string ;
if ( typeof value === "string" ) {
text = value ;
} else {
try {
text = new TextDecoder ( "utf-8" , {
fatal : true ,
ignoreBOM : true ,
}). decode ( value );
} catch ( cause : unknown ) {
2026-10-10 01:53:59 +08:00
return isStringLengthLimit ( cause )
? { kind : "too-large" }
: { kind : "invalid" };
2026-10-06 05:00:54 +08:00
}
2026-07-16 10:21:41 +08:00
}
2026-10-06 05:00:54 +08:00
const parsed = safeParseJson ( text );
2026-10-10 01:53:59 +08:00
if ( parsed . ok ) return { kind : "valid" , value : parsed.value };
return isStringLengthLimit ( parsed . cause )
? { kind : "too-large" }
: { kind : "invalid" };
2026-07-16 10:21:41 +08:00
};
2026-10-10 01:53:59 +08:00
const isStringLengthLimit = ( cause : unknown ) : boolean =>
cause instanceof Error &&
/cannot create a string longer than|invalid string length/i . test (
cause . message ,
);
2026-07-16 10:21:41 +08:00
const inputError = ( operation : string ) : JsonValue => ({
error : "Application workflow failed" ,
2026-07-16 18:49:35 +08:00
... projectAnalysisError (
new AnalysisInputError ( operation , undefined , [
{ path : [], reason : "invalid_format" , expected : "JSON" },
]),
),
2026-07-16 10:21:41 +08:00
});
const jsonFileError = (
2026-09-08 10:59:13 +08:00
path : string | undefined ,
2026-07-16 10:21:41 +08:00
operation : string ,
2026-09-29 17:00:06 +08:00
reason : "invalid-json" | "read-failed" ,
2026-10-06 05:00:54 +08:00
cause? : unknown ,
2026-07-16 10:21:41 +08:00
) => ({
ok : false as const ,
error : {
error : "Application workflow failed" ,
2026-07-16 18:49:35 +08:00
... projectAnalysisError (
new AnalysisInputError (
operation ,
2026-10-06 05:00:54 +08:00
cause === undefined ? undefined : { cause },
2026-07-16 18:49:35 +08:00
reason === "invalid-json"
? [{ path : [], reason : "invalid_format" , expected : "JSON" }]
2026-10-09 09:30:15 +00:00
: [ readFailureIssue ( path , cause )],
2026-07-16 18:49:35 +08:00
),
),
2026-09-08 10:59:13 +08:00
...( path === undefined ? {} : { input_path : path }),
2026-07-16 10:21:41 +08:00
input_reason : reason ,
},
});
2026-10-09 09:30:15 +00:00
2026-10-09 13:49:54 -04:00
/** Preserve file-selection and system failures alongside the requested path. */
2026-10-09 09:30:15 +00:00
const readFailureIssue = ( path : string | undefined , cause : unknown ) => {
const code =
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
typeof cause . code === "string"
? ` ( ${ cause . code } )`
: "" ;
return {
path : [],
reason : "invalid_value" as const ,
2026-10-09 13:49:54 -04:00
message :
cause instanceof NonRegularFileReadError && cause . code === "ENOTFILE"
? `The JSON input must be a regular file ${ code } : ${ path ?? "" } `
: `The JSON input file could not be read ${ code } : ${ path ?? "" } ` ,
2026-10-09 09:30:15 +00:00
};
};
2026-10-10 01:53:59 +08:00
const jsonTooLargeError = (
path : string | undefined ,
operation : string ,
) : { readonly ok : false ; readonly error : JsonValue } => {
const projection = projectAnalysisError (
new AnalysisResourceConstraintError (
operation ,
"memory" ,
`The JSON input exceeds this Node.js runtime's maximum string length ( ${ bufferConstants . MAX_STRING_LENGTH } UTF-16 code units) and cannot be parsed as one value.` ,
{
boundary : "cli-json-input" ,
max_string_code_units : bufferConstants.MAX_STRING_LENGTH ,
},
{
remediationAction :
"Split the JSON into smaller inputs or rerun its producer on a smaller subset, then retry." ,
},
),
);
return {
ok : false ,
error : {
error : "Application workflow failed" ,
... projection ,
...( path === undefined ? {} : { input_path : path }),
input_reason : "too-large" ,
},
};
};