or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-api.mdindex.mdmodels.mdprogrammatic-api.mdreporters.mdutilities.md

utilities.mddocs/

0

# Utility Functions

1

2

Helper functions for file operations, JSON processing, and output formatting. These utilities support the core analysis functionality and provide common operations used throughout Plato.

3

4

## Capabilities

5

6

### File Path Operations

7

8

Find common base paths from arrays of file paths for consistent report generation.

9

10

```javascript { .api }

11

/**

12

* Find common base path from array of file paths

13

* @param {Array} files - Array of file paths

14

* @returns {String} Common base path

15

*/

16

function findCommonBase(files);

17

```

18

19

**Parameters:**

20

21

- `files` (Array): Array of file paths to analyze

22

23

**Returns:** String - The common base path shared by all input files

24

25

**Usage Examples:**

26

27

```javascript

28

const { findCommonBase } = require('plato/lib/util');

29

30

// Find common base for report generation

31

const files = [

32

'/project/src/app.js',

33

'/project/src/utils/helper.js',

34

'/project/src/components/modal.js'

35

];

36

37

const basePath = findCommonBase(files);

38

console.log(basePath); // '/project/src'

39

40

// Use with relative paths

41

const relativeFiles = [

42

'src/app.js',

43

'src/utils/helper.js',

44

'test/app.test.js'

45

];

46

47

const relativeBase = findCommonBase(relativeFiles);

48

console.log(relativeBase); // '.'

49

```

50

51

### JSON Processing

52

53

Format and read JSON data with specialized handling for reports and configuration files.

54

55

```javascript { .api }

56

/**

57

* Format JSON with identifier stripping for clean output

58

* @param {Object} report - Report object to format

59

* @returns {String} Formatted JSON string

60

*/

61

function formatJSON(report);

62

63

/**

64

* Read and parse JSON file with error handling

65

* @param {String} file - File path to JSON file

66

* @param {Object} options - Options object

67

* @returns {Object} Parsed JSON or empty object on error

68

*/

69

function readJSON(file, options);

70

```

71

72

**formatJSON Parameters:**

73

74

- `report` (Object): Report object to format and stringify

75

76

**Returns:** String - Formatted JSON string with identifiers stripped

77

78

**readJSON Parameters:**

79

80

- `file` (String): File path to the JSON file to read

81

- `options` (Object): Configuration options for reading

82

83

**Returns:** Object - Parsed JSON object, or empty object `{}` if file read/parse fails

84

85

**Usage Examples:**

86

87

```javascript

88

const { formatJSON, readJSON } = require('plato/lib/util');

89

90

// Format report for output

91

const report = {

92

complexity: { cyclomatic: 5 },

93

info: { file: 'app.js' }

94

};

95

96

const formatted = formatJSON(report);

97

console.log(formatted); // Clean JSON string

98

99

// Read configuration files

100

const jshintConfig = readJSON('.jshintrc', {});

101

const packageInfo = readJSON('package.json', {});

102

103

// Safe reading - returns {} if file doesn't exist

104

const config = readJSON('nonexistent.json', {});

105

console.log(config); // {}

106

```

107

108

### Source Code Processing

109

110

Process JavaScript source code for analysis and reporting.

111

112

```javascript { .api }

113

/**

114

* Remove JavaScript comments from source code string

115

* @param {String} str - Source code string

116

* @returns {String} Code without comments

117

*/

118

function stripComments(str);

119

```

120

121

**Parameters:**

122

123

- `str` (String): JavaScript source code string

124

125

**Returns:** String - Source code with all comments removed

126

127

**Usage Examples:**

128

129

```javascript

130

const { stripComments } = require('plato/lib/util');

131

132

const sourceCode = `

133

// This is a comment

134

function hello() {

135

/* Multi-line comment

136

spanning multiple lines */

137

console.log('Hello World');

138

}

139

`;

140

141

const cleanCode = stripComments(sourceCode);

142

console.log(cleanCode);

143

// Output:

144

// function hello() {

145

// console.log('Hello World');

146

// }

147

```

148

149

### HTML Processing

150

151

Escape HTML entities for safe output in generated reports.

152

153

```javascript { .api }

154

/**

155

* Escape HTML entities in string for safe output

156

* @param {String} html - HTML string to escape

157

* @returns {String} Escaped HTML string

158

*/

159

function escapeHTML(html);

160

```

161

162

**Parameters:**

163

164

- `html` (String): HTML string containing potential entities to escape

165

166

**Returns:** String - HTML string with entities properly escaped

167

168

**Usage Examples:**

169

170

```javascript

171

const { escapeHTML } = require('plato/lib/util');

172

173

// Escape potentially dangerous HTML

174

const userInput = '<script>alert("XSS")</script>';

175

const safeHTML = escapeHTML(userInput);

176

console.log(safeHTML); // '&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;'

177

178

// Use in report generation

179

const fileName = 'app<test>.js';

180

const safeFileName = escapeHTML(fileName);

181

console.log(safeFileName); // 'app&lt;test&gt;.js'

182

```

183

184

## Integration with Core Functionality

185

186

These utilities are used throughout Plato's core functionality:

187

188

### Report Generation

189

190

```javascript

191

// Example of utility integration in report generation

192

const { findCommonBase, formatJSON, escapeHTML } = require('plato/lib/util');

193

194

function generateReport(files, reports) {

195

// Find common base for consistent paths

196

const basePath = findCommonBase(files);

197

198

// Process each report

199

reports.forEach(report => {

200

// Safe HTML for file names

201

report.info.fileSafe = escapeHTML(report.info.file);

202

203

// Format report data

204

const jsonData = formatJSON(report);

205

206

// Write to file...

207

});

208

}

209

```

210

211

### Configuration Loading

212

213

```javascript

214

// Example of configuration loading

215

const { readJSON } = require('plato/lib/util');

216

217

function loadConfiguration() {

218

// Load various config files safely

219

const packageConfig = readJSON('package.json', {});

220

const jshintConfig = readJSON('.jshintrc', {});

221

const platoConfig = readJSON('.plato.json', {});

222

223

return {

224

package: packageConfig,

225

jshint: jshintConfig,

226

plato: platoConfig

227

};

228

}

229

```

230

231

### Source Code Analysis

232

233

```javascript

234

// Example of source processing

235

const { stripComments } = require('plato/lib/util');

236

const fs = require('fs');

237

238

function analyzeFile(filePath) {

239

const source = fs.readFileSync(filePath, 'utf8');

240

241

// Remove comments for certain analysis types

242

const cleanSource = stripComments(source);

243

244

// Perform analysis on clean source

245

return performComplexityAnalysis(cleanSource);

246

}

247

```

248

249

## Error Handling

250

251

The utility functions are designed to be robust and handle common error scenarios:

252

253

### File Operations

254

255

- `readJSON()` returns empty object `{}` instead of throwing on file read errors

256

- `findCommonBase()` handles empty arrays and invalid paths gracefully

257

258

### String Processing

259

260

- `stripComments()` handles malformed or incomplete comments

261

- `escapeHTML()` processes null/undefined input safely

262

- `formatJSON()` handles circular references and non-serializable objects

263

264

**Safe Usage Patterns:**

265

266

```javascript

267

const { readJSON, findCommonBase } = require('plato/lib/util');

268

269

// Always safe - won't throw

270

const config = readJSON('might-not-exist.json', {});

271

const basePath = findCommonBase([]) || '.';

272

273

// Check results as needed

274

if (Object.keys(config).length > 0) {

275

console.log('Configuration loaded');

276

}

277

```