@sap/cds-compiler
Version:
CDS (Core Data Services) compiler and backends
92 lines (81 loc) • 2.69 kB
JavaScript
;
const shouldTraceApi = process?.env?.CDSC_TRACE_API;
/**
* Placeholder for disabled tracing (no-op).
*/
function noOp() {
// no-op
}
/**
* Print trace info to stderr when calling an API function
*/
function call( apiName, options, csn, files ) {
const { version } = require('../../package.json');
const now = (new Date( Date.now() )).toISOString();
const args = (files || csn)
? `${ optionsString( options ) } on ${ filesInfo( files ) || csnInfo( csn ) }`
: optionsString( options );
// eslint-disable-next-line no-console
console.error( 'CDSC_TRACE_API: at %s, call %s() of v%s with options %s',
now, apiName, version, args );
}
/**
* Print trace info to stderr when exiting an API function
*/
function exit( apiName, result ) {
const now = (new Date( Date.now() )).toISOString();
const info = (result?.definitions || result?.extensions)
? csnInfo( result )
: `a result of type ${ typeof result }`;
// eslint-disable-next-line no-console
console.error( 'CDSC_TRACE_API: at %s, exit %s() and return %s',
now, apiName, info );
}
/**
* Print trace info to stderr for miscellaneous use cases
*/
function log( info ) {
const now = (new Date( Date.now() )).toISOString();
// eslint-disable-next-line no-console
console.error( 'CDSC_TRACE_API: at %s, %s', now, info );
}
function optionsString( obj ) {
if (!obj || typeof obj !== 'object')
return obj.toString();
try {
if (Array.isArray( obj.messages ) && obj.messages.length) {
const messages = {};
for (const msg of obj.messages)
messages[msg.severity] = (messages[msg.severity] || 0) + 1;
obj = { ...obj, messages };
}
return JSON.stringify( obj, null, 2 );
}
catch (err) {
return err.toString();
}
}
function filesInfo( files ) {
if (!files)
return files;
if (!Array.isArray( files ))
files = Object.keys( files );
return files.length ? [ 'files', ...files ].join( '\n ') : 'no files';
}
function csnInfo( csn ) {
if (!csn || typeof csn !== 'object' || Array.isArray( csn ))
return `some value of type ${ typeof csn }`;
try {
JSON.stringify( csn );
const defs = csn.definitions ? Object.keys( csn.definitions ).length : 'no';
const exts = csn.extensions ? csn.extensions.length : 'no';
const flavor = csn.meta?.flavor || csn.meta?.compilerCsnFlavor || 'unknown';
return `a CSN of flavor '${ flavor }' with ${ defs } definitions and ${ exts } extensions`;
}
catch (err) {
return `a CORRUPTED CSN (${ err.toString() })`;
}
}
module.exports = (shouldTraceApi)
? { call, exit, log }
: { call: noOp, exit: noOp, log: noOp };