or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdjava-integration.mdjavascript-objects.mdscript-execution.mdsecurity-debugging.md

script-execution.mddocs/

0

# Script Execution

1

2

Core JavaScript execution engine providing context management, script compilation, evaluation, and execution control. Supports both interpreted and compiled modes with comprehensive configuration options.

3

4

## Capabilities

5

6

### Context Management

7

8

The Context class represents the runtime environment for JavaScript execution and must be associated with each thread that runs JavaScript code.

9

10

```java { .api }

11

/**

12

* Associates a Context instance with the current thread

13

* @return Context instance for this thread

14

*/

15

public static Context enter();

16

17

/**

18

* Removes the Context association from the current thread

19

* Must be called in finally block to prevent memory leaks

20

*/

21

public static void exit();

22

23

/**

24

* Gets the Context associated with the current thread

25

* @return Current Context or null if no Context is active

26

*/

27

public static Context getCurrentContext();

28

29

/**

30

* Implements Closeable for try-with-resources pattern

31

* Automatically calls exit() when closed

32

*/

33

public void close();

34

```

35

36

**Usage Examples:**

37

38

```java

39

// Manual Context management

40

Context cx = Context.enter();

41

try {

42

// JavaScript execution code here

43

} finally {

44

Context.exit();

45

}

46

47

// Try-with-resources (Rhino 1.7.8+)

48

try (Context cx = Context.enter()) {

49

// JavaScript execution code here

50

// exit() is called automatically

51

}

52

```

53

54

### Context Factory

55

56

ContextFactory provides thread-safe Context creation and configuration, recommended over direct Context instantiation.

57

58

```java { .api }

59

/**

60

* Context factory for creating and configuring Context instances

61

*/

62

public class ContextFactory {

63

/**

64

* Gets the global ContextFactory instance

65

* @return Global ContextFactory

66

*/

67

public static ContextFactory getGlobal();

68

69

/**

70

* Creates and enters a new Context for current thread

71

* @return New Context instance

72

*/

73

public Context enterContext();

74

75

/**

76

* Enters an existing Context for current thread

77

* @param cx Context to enter, or null to create new

78

* @return The entered Context

79

*/

80

public Context enterContext(Context cx);

81

82

/**

83

* Creates a new Context without entering it

84

* @return New Context instance

85

*/

86

public Context makeContext();

87

88

/**

89

* Executes ContextAction with proper Context lifecycle

90

* @param action Action to execute with Context

91

* @return Result from action

92

*/

93

public <T> T call(ContextAction<T> action);

94

}

95

96

/**

97

* Interface for code that requires Context access

98

*/

99

public interface ContextAction<T> {

100

/**

101

* Executes with the provided Context

102

* @param cx Context for JavaScript execution

103

* @return Action result

104

*/

105

T run(Context cx);

106

}

107

```

108

109

**Usage Examples:**

110

111

```java

112

// Using ContextFactory.call() (recommended)

113

Object result = ContextFactory.getGlobal().call(cx -> {

114

Scriptable scope = cx.initStandardObjects();

115

return cx.evaluateString(scope, "Math.PI * 2", "calc", 1, null);

116

});

117

118

// Manual ContextFactory usage

119

ContextFactory factory = ContextFactory.getGlobal();

120

Context cx = factory.enterContext();

121

try {

122

// JavaScript execution

123

} finally {

124

Context.exit();

125

}

126

```

127

128

### Scope Initialization

129

130

Scopes define the global object and available JavaScript built-in objects for script execution.

131

132

```java { .api }

133

/**

134

* Initializes standard JavaScript objects (Object, Array, Function, etc.)

135

* @return Scriptable scope with all standard objects

136

*/

137

public ScriptableObject initStandardObjects();

138

139

/**

140

* Initializes standard objects with specified scope object

141

* @param scope Scope object to initialize

142

* @return The initialized scope

143

*/

144

public Scriptable initStandardObjects(ScriptableObject scope);

145

146

/**

147

* Initializes safe standard objects without Java class access

148

* Prevents access to Java packages and classes from JavaScript

149

* @return Safe Scriptable scope

150

*/

151

public ScriptableObject initSafeStandardObjects();

152

153

/**

154

* Initializes safe standard objects with specified scope

155

* @param scope Scope object to initialize safely

156

* @return The initialized safe scope

157

*/

158

public Scriptable initSafeStandardObjects(ScriptableObject scope);

159

```

160

161

**Usage Examples:**

162

163

```java

164

// Standard scope with Java access

165

Scriptable scope = cx.initStandardObjects();

166

167

// Safe scope without Java access (recommended for sandboxing)

168

Scriptable safeScope = cx.initSafeStandardObjects();

169

170

// Custom scope object

171

ScriptableObject myScope = new MyCustomScope();

172

cx.initStandardObjects(myScope);

173

```

174

175

### Script Evaluation

176

177

Direct evaluation of JavaScript source code without pre-compilation.

178

179

```java { .api }

180

/**

181

* Evaluates JavaScript source string

182

* @param scope Scope for variable resolution

183

* @param source JavaScript source code

184

* @param sourceName Name for debugging and error reporting

185

* @param lineno Starting line number

186

* @param securityDomain Security domain for access control

187

* @return Evaluation result

188

*/

189

public Object evaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain);

190

191

/**

192

* Evaluates JavaScript from Reader (file, stream, etc.)

193

* @param scope Scope for variable resolution

194

* @param in Reader containing JavaScript source

195

* @param sourceName Name for debugging and error reporting

196

* @param lineno Starting line number

197

* @param securityDomain Security domain for access control

198

* @return Evaluation result

199

*/

200

public Object evaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain);

201

```

202

203

**Usage Examples:**

204

205

```java

206

// Simple expression evaluation

207

Object result = cx.evaluateString(scope, "2 + 3", "expression", 1, null);

208

System.out.println(Context.toString(result)); // "5"

209

210

// Multi-line script evaluation

211

String script = """

212

var x = 10;

213

var y = 20;

214

x + y;

215

""";

216

Object sum = cx.evaluateString(scope, script, "calculation.js", 1, null);

217

218

// File evaluation

219

try (FileReader reader = new FileReader("script.js")) {

220

Object result = cx.evaluateReader(scope, reader, "script.js", 1, null);

221

}

222

```

223

224

### Script Compilation

225

226

Pre-compilation of JavaScript for better performance when executing repeatedly.

227

228

```java { .api }

229

/**

230

* Compiles JavaScript source string into executable Script

231

* @param source JavaScript source code

232

* @param sourceName Name for debugging and error reporting

233

* @param lineno Starting line number

234

* @param securityDomain Security domain for access control

235

* @return Compiled Script object

236

*/

237

public Script compileString(String source, String sourceName, int lineno, Object securityDomain);

238

239

/**

240

* Compiles JavaScript from Reader into executable Script

241

* @param in Reader containing JavaScript source

242

* @param sourceName Name for debugging and error reporting

243

* @param lineno Starting line number

244

* @param securityDomain Security domain for access control

245

* @return Compiled Script object

246

*/

247

public Script compileReader(Reader in, String sourceName, int lineno, Object securityDomain);

248

249

/**

250

* Compiles JavaScript function

251

* @param scope Scope for compilation

252

* @param source Function source code

253

* @param sourceName Name for debugging

254

* @param lineno Starting line number

255

* @param securityDomain Security domain

256

* @return Compiled Function object

257

*/

258

public Function compileFunction(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain);

259

```

260

261

**Usage Examples:**

262

263

```java

264

// Compile once, execute multiple times

265

Script compiled = cx.compileString("Math.random() * 100", "random.js", 1, null);

266

267

// Execute compiled script multiple times

268

for (int i = 0; i < 10; i++) {

269

Object result = compiled.exec(cx, scope);

270

System.out.println("Random: " + Context.toString(result));

271

}

272

273

// Compile and cache functions

274

Function factorial = cx.compileFunction(scope,

275

"function factorial(n) { return n <= 1 ? 1 : n * factorial(n-1); }",

276

"factorial.js", 1, null);

277

278

// Call compiled function

279

Object[] args = {5};

280

Object result = factorial.call(cx, scope, scope, args);

281

```

282

283

### Script Interface

284

285

The Script interface represents compiled JavaScript code ready for execution.

286

287

```java { .api }

288

/**

289

* Interface for compiled JavaScript code

290

*/

291

public interface Script {

292

/**

293

* Executes the compiled script

294

* @param cx Context for execution

295

* @param scope Scope for variable resolution

296

* @return Execution result

297

*/

298

Object exec(Context cx, Scriptable scope);

299

}

300

```

301

302

### Context Configuration

303

304

Configuration options for controlling JavaScript execution behavior.

305

306

```java { .api }

307

/**

308

* Gets the JavaScript language version for this Context

309

* @return Language version constant

310

*/

311

public int getLanguageVersion();

312

313

/**

314

* Sets the JavaScript language version

315

* @param version Version constant (VERSION_DEFAULT, VERSION_ES6, etc.)

316

*/

317

public void setLanguageVersion(int version);

318

319

/**

320

* Gets the error reporter for compilation and runtime errors

321

* @return Current ErrorReporter

322

*/

323

public ErrorReporter getErrorReporter();

324

325

/**

326

* Sets the error reporter for compilation and runtime errors

327

* @param reporter ErrorReporter implementation

328

* @return Previous ErrorReporter

329

*/

330

public ErrorReporter setErrorReporter(ErrorReporter reporter);

331

332

/**

333

* Checks if debug information generation is enabled

334

* @return true if debug info is generated

335

*/

336

public boolean isGeneratingDebug();

337

338

/**

339

* Controls debug information generation

340

* @param generatingDebug true to generate debug info

341

*/

342

public void setGeneratingDebug(boolean generatingDebug);

343

344

/**

345

* Checks if source information is preserved in compiled code

346

* @return true if source is preserved

347

*/

348

public boolean isGeneratingSource();

349

350

/**

351

* Controls source information preservation

352

* @param generatingSource true to preserve source

353

*/

354

public void setGeneratingSource(boolean generatingSource);

355

356

/**

357

* Checks if interpreter mode is enabled (vs compiled mode)

358

* @return true if using interpreter

359

*/

360

public boolean isInterpretedMode();

361

362

/**

363

* Controls execution mode

364

* @param interpretedMode true for interpreter, false for compiler

365

*/

366

public void setInterpretedMode(boolean interpretedMode);

367

```

368

369

### Language Version Constants

370

371

```java { .api }

372

// Language version constants for setLanguageVersion()

373

public static final int VERSION_DEFAULT = 0; // Use implementation default

374

public static final int VERSION_1_0 = 100; // JavaScript 1.0

375

public static final int VERSION_1_1 = 110; // JavaScript 1.1

376

public static final int VERSION_1_2 = 120; // JavaScript 1.2

377

public static final int VERSION_1_3 = 130; // JavaScript 1.3

378

public static final int VERSION_1_4 = 140; // JavaScript 1.4

379

public static final int VERSION_1_5 = 150; // JavaScript 1.5

380

public static final int VERSION_1_6 = 160; // JavaScript 1.6

381

public static final int VERSION_1_7 = 170; // JavaScript 1.7

382

public static final int VERSION_1_8 = 180; // JavaScript 1.8

383

public static final int VERSION_ES6 = 200; // ES6/ES2015 (default)

384

public static final int VERSION_ECMASCRIPT = 250; // Latest ECMAScript

385

```

386

387

**Usage Examples:**

388

389

```java

390

// Configure Context for ES6 features

391

cx.setLanguageVersion(Context.VERSION_ES6);

392

393

// Enable debug information for debugging

394

cx.setGeneratingDebug(true);

395

cx.setGeneratingSource(true);

396

397

// Use interpreter mode for better debugging

398

cx.setInterpretedMode(true);

399

400

// Set custom error reporter

401

cx.setErrorReporter(new MyErrorReporter());

402

```

403

404

### Object Creation

405

406

Creating JavaScript objects and arrays from Java code.

407

408

```java { .api }

409

/**

410

* Creates a new JavaScript Object

411

* @param scope Scope for prototype chain

412

* @return New empty Object

413

*/

414

public Scriptable newObject(Scriptable scope);

415

416

/**

417

* Creates a new JavaScript Object using specified constructor

418

* @param scope Scope for resolution

419

* @param constructorName Constructor function name

420

* @return New object instance

421

*/

422

public Scriptable newObject(Scriptable scope, String constructorName);

423

424

/**

425

* Creates a new JavaScript Array with specified length

426

* @param scope Scope for prototype chain

427

* @param length Initial array length

428

* @return New Array object

429

*/

430

public Scriptable newArray(Scriptable scope, int length);

431

432

/**

433

* Creates a new JavaScript Array from Java array

434

* @param scope Scope for prototype chain

435

* @param elements Initial array elements

436

* @return New Array object with elements

437

*/

438

public Scriptable newArray(Scriptable scope, Object[] elements);

439

```

440

441

**Usage Examples:**

442

443

```java

444

// Create empty JavaScript objects

445

Scriptable obj = cx.newObject(scope);

446

Scriptable arr = cx.newArray(scope, 0);

447

448

// Create Date object

449

Scriptable date = cx.newObject(scope, "Date");

450

451

// Create Array with initial elements

452

Object[] elements = {"hello", "world", 42};

453

Scriptable array = cx.newArray(scope, elements);

454

455

// Set properties on created objects

456

obj.put("name", obj, "example");

457

obj.put("value", obj, 123);

458

```

459

460

## Advanced Execution Features

461

462

### Compiler Environment

463

464

Configuration for JavaScript compilation process.

465

466

```java { .api }

467

/**

468

* Configuration for JavaScript compilation

469

*/

470

public class CompilerEnvirons {

471

/**

472

* Initialize from Context settings

473

* @param cx Context to copy settings from

474

*/

475

public void initFromContext(Context cx);

476

477

/**

478

* Check if source preservation is enabled

479

* @return true if generating source

480

*/

481

public boolean isGeneratingSource();

482

483

/**

484

* Control source preservation in compiled code

485

* @param generatingSource true to preserve source

486

*/

487

public void setGeneratingSource(boolean generatingSource);

488

489

/**

490

* Get language version for compilation

491

* @return Language version constant

492

*/

493

public int getLanguageVersion();

494

495

/**

496

* Set language version for compilation

497

* @param languageVersion Version constant

498

*/

499

public void setLanguageVersion(int languageVersion);

500

}

501

```

502

503

### Parser

504

505

Direct access to JavaScript parsing for AST manipulation.

506

507

```java { .api }

508

/**

509

* JavaScript parser for creating Abstract Syntax Trees

510

*/

511

public class Parser {

512

/**

513

* Parse JavaScript source into AST

514

* @param sourceString JavaScript source code

515

* @param sourceName Source name for error reporting

516

* @param lineno Starting line number

517

* @return AST root node

518

*/

519

public AstRoot parse(String sourceString, String sourceName, int lineno);

520

521

/**

522

* Parse JavaScript from Reader into AST

523

* @param sourceReader Reader with JavaScript source

524

* @param sourceName Source name for error reporting

525

* @param lineno Starting line number

526

* @return AST root node

527

*/

528

public AstRoot parse(Reader sourceReader, String sourceName, int lineno);

529

}

530

```

531

532

**Usage Examples:**

533

534

```java

535

// Parse JavaScript into AST for analysis

536

Parser parser = new Parser();

537

CompilerEnvirons env = new CompilerEnvirons();

538

env.initFromContext(cx);

539

540

AstRoot ast = parser.parse("function test() { return 42; }", "test.js", 1);

541

// Analyze or modify AST...

542

```