> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentfront.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# ast-guard

> API reference for the ast-guard package

API reference for the `@enclave-vm/ast` package.

## Installation

```bash theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
npm install @enclave-vm/ast
```

## JSAstValidator Class

Main AST validation class. It is built from an array of rules; a preset function returns such an array.

### Constructor

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
new JSAstValidator(rules?: ValidationRule[])
```

### Methods

#### validate(source, config?)

Validate JavaScript source against the rules.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
async validate(source: string, config?: ValidationConfig): Promise<ValidationResult>
```

The promise rejects in three cases:

* with `InvalidSourceError`, for a source that is not a string or is empty;
* with a `TypeError`, for a `preScan` option that names no preset or holds an invalid setting;
* with whatever a rule throws. The validator does not turn the exception of a rule into an issue, so a validation with rules of your own belongs in a `try`/`catch` (see [Using Custom Rules](#using-custom-rules)).

Every other outcome is in the result: a failed pre-scan, a parse error, the issues the rules report and a failed transform.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ValidationConfig {
  parseOptions?: acorn.Options;
  rules?: Record<string, RuleConfig | boolean>; // Enable, disable or re-rate a rule by name
  maxIssues?: number;          // Default: DEFAULT_MAX_ISSUES (100); 0 collects every issue
  stopOnFirstError?: boolean;
  transform?: TransformConfig;
  preScan?: {
    enabled?: boolean;         // Default: true
    preset?: 'agentscript' | 'strict' | 'secure' | 'standard' | 'permissive'; // Default: 'standard'
    config?: Partial<PreScannerConfig>;
  };
}

interface ValidationResult {
  valid: boolean;              // true if every rule ran and none reported an error
  issues: ValidationIssue[];   // At most maxIssues
  incomplete?: boolean;        // true if issues were left out or the validation stopped early
  rulesExecuted?: number;
  ast?: acorn.Node;
  parseError?: Error;
  transformedCode?: string;
  preScanError?: Error;
  preScanStats?: { inputSize; lineCount; maxNestingDepthFound; regexCount; scanDurationMs };
}

interface ValidationIssue {
  code: string;                // e.g. 'UNKNOWN_GLOBAL', 'DISALLOWED_SYNTAX'
  message: string;
  severity: ValidationSeverity; // 'error' | 'warning' | 'info'
  location?: {
    line: number;
    column: number;
    endLine?: number;
    endColumn?: number;
  };
  data?: Record<string, unknown>;
}
```

A validation result is bounded: at the cap of `maxIssues` the validation stops as soon as an error is on the list, and a validation that stopped early is never `valid`. An `UNKNOWN_GLOBAL` issue states the list of allowed globals once per validation.

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, createAgentScriptPreset } from '@enclave-vm/ast';

const validator = new JSAstValidator(createAgentScriptPreset());
const result = await validator.validate(`
  const x = eval('code');
`);

if (!result.valid) {
  for (const issue of result.issues) {
    console.log(`${issue.code}: ${issue.message}`);
  }
}
```

#### registerRule(rule), unregisterRule(name), getRules(), getRule(name), getStats(result, durationMs)

Manage the rules of a validator, and count the issues of a result by severity.

## PreScanner Class

Checks on the source text before it is parsed.

### Constructor

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
new PreScanner(options?: { preset?: PreScannerPresetLevel; config?: Partial<PreScannerConfig> })
```

`preset` is `'agentscript'`, `'strict'`, `'secure'`, `'standard'` (the default) or `'permissive'`; `config` overrides single settings of it. `PreScanner.forAgentScript(overrides?)`, `forStrict`, `forSecure`, `forStandard` and `forPermissive` do the same.

### Methods

#### scan(source)

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
scan(source: string): PreScanResult
```

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface PreScanResult {
  success: boolean;
  issues: PreScanIssue[];
  fatalIssue?: PreScanIssue;
  detectedRegex: DetectedRegex[];
  stats: PreScanStats;
}

interface PreScanIssue {
  code: PreScannerErrorCode;   // e.g. 'PRESCANNER_INPUT_TOO_LARGE'
  severity: 'error' | 'warning' | 'info';
  message: string;
  position?: number;
  line?: number;
  column?: number;
  data?: Record<string, unknown>;
}
```

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { PreScanner } from '@enclave-vm/ast';

const scanner = new PreScanner({ preset: 'agentscript' });
const result = scanner.scan(code);

if (!result.success) {
  console.log('Pre-scan failed:', result.fatalIssue);
}
```

`JSAstValidator.validate()` runs a pre-scan itself, with the `standard` preset unless `preScan.preset` says otherwise. See [Pre-Scanner](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/pre-scanner.md).

## Factory Functions

### createAgentScriptPreset(options?)

Create the rules of the AgentScript preset.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function createAgentScriptPreset(options?: AgentScriptOptions): ValidationRule[]
```

**Options:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface AgentScriptOptions {
  // Globals
  securityLevel?: 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE'; // Default: 'STANDARD'
  allowedGlobals?: string[];
  hostObjectGlobals?: string[];
  additionalDisallowedIdentifiers?: string[];
  reservedPrefixes?: string[];  // In addition to '__ag_' and '__safe_'

  // Tool calls
  requireCallTool?: boolean;
  staticCallTarget?: { enabled?: boolean; allowedToolNames?: (string | RegExp)[] };
  callToolValidation?: { minArgs?: number; maxArgs?: number; expectedTypes?: string[] };

  // Loops
  allowedLoops?: {
    allowFor?: boolean;
    allowForOf?: boolean;
    allowWhile?: boolean;
    allowDoWhile?: boolean;
    allowForIn?: boolean;
  };

  // Functions and syntax
  allowArrowFunctions?: boolean;
  additionalAllowedSyntax?: string[];
  requireDirectRegexMethodCalls?: boolean;
  allowDynamicArrayFill?: boolean;
}
```

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const rules = createAgentScriptPreset({
  allowedGlobals: ['callTool', 'Math', 'JSON', 'context'],
  allowedLoops: {
    allowFor: true,
    allowForOf: true,
    allowWhile: false,
  },
});
```

### createStrictPreset, createSecurePreset, createStandardPreset, createPermissivePreset, createPreset(level, options?)

The other presets, also available as `Presets.strict`, `Presets.secure`, `Presets.standard`, `Presets.permissive` and `Presets.create`. Each returns an array of rules. They are filters on source text: passing one does not make code safe to run.

### createBabelPreset(options?), getBabelConfig(level?)

The AgentScript preset with the `Babel` global, and the Babel limits of a security level. See [Babel Preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/babel-preset.md).

### createPreScannerConfig(preset, overrides?)

The configuration object of a pre-scanner preset, merged with overrides and clamped to the mandatory maxima.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function createPreScannerConfig(
  preset: 'agentscript' | 'strict' | 'secure' | 'standard' | 'permissive',
  overrides?: Partial<PreScannerConfig>,
): PreScannerConfig
```

**PreScannerConfig:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface PreScannerConfig {
  maxInputSize: number;
  maxLineLength: number;
  maxLines: number;
  maxNestingDepth: number;
  maxConsecutiveOperators: number;
  regexMode: 'block' | 'analyze' | 'allow';
  maxRegexLength?: number;
  maxRegexCount?: number;
  regexAnalysisLevel?: 'catastrophic' | 'polynomial';
  maxStringLength: number;
  maxTotalStringContent: number;
  unicodePreCheck: boolean;
  blockBidiPatterns: boolean;
  blockInvisibleChars?: boolean;
}
```

Pass the result as `config` of `new PreScanner({ preset, config })`, not in the place of the options.

### normalizeToolNamespaces(spec, options?)

Validates a `toolNamespaces` specification (`{ mail: ['list', 'send'] }` or `{ users: { get: 'users:get' } }`) and returns it as plain data. It throws a `TypeError` whose message starts with `Invalid toolNamespaces:` for a name no runtime may bind, among them the names the language calls on an object by itself: `then`, `toString`, `valueOf`, `toLocaleString` and `toJSON`, as a method name and as a namespace name.

## ValidationRule

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ValidationRule {
  readonly name: string;
  readonly description: string;
  readonly defaultSeverity: ValidationSeverity;
  readonly enabledByDefault: boolean;
  validate(context: ValidationContext): void | Promise<void>;
}

interface ValidationContext {
  ast: acorn.Node;
  source: string;
  config: ValidationConfig;
  report(issue: Omit<ValidationIssue, 'severity'> & { severity?: ValidationSeverity }): void;
  visited: Set<acorn.Node>;
  metadata: Map<string, unknown>;
}
```

## Built-in Rules

| Rule name | Class | Description |
| - | - | - |
| `no-eval` | `NoEvalRule` | Blocks `eval()`, the `Function` constructor and string timers |
| `allowed-syntax` | `AllowedSyntaxRule` | Only allows the listed ESTree node types |
| `no-global-access` | `NoGlobalAccessRule` | Blocks the global objects, `this` as a value, `constructor`, `Reflect` and the reflection statics of `Object` |
| `disallowed-identifier` | `DisallowedIdentifierRule` | Blocks identifiers and property names by name |
| `unknown-global` | `UnknownGlobalRule` | Only allows the listed globals, resolved by lexical scope |
| `reserved-prefix` | `ReservedPrefixRule` | Blocks names with the runtime's prefixes |
| `no-user-functions` | `NoUserDefinedFunctionsRule` | Blocks function declarations and function expressions |
| `forbidden-loop` | `ForbiddenLoopRule` | Blocks the loop types that are not allowed |
| `infinite-loop` | (AgentScript preset) | Reports obvious infinite loops |
| `no-async` | `NoAsyncRule` | Restricts async functions and `await` |
| `static-call-target` | `StaticCallTargetRule` | Requires a string literal as the tool name |
| `no-call-target-assignment` | `NoCallTargetAssignmentRule` | Blocks every write and declaration of a protected name |
| `required-function-call` | `RequiredFunctionCallRule` | Requires calls of the listed functions |
| `call-argument-validation` | `CallArgumentValidationRule` | Checks argument count and types |
| `no-regex-literal` | `NoRegexLiteralRule` | Blocks or analyzes regex literals |
| `no-regex-methods` | `NoRegexMethodsRule` | Blocks the methods that run a regular expression |
| `no-computed-destructuring` | `NoComputedDestructuringRule` | Blocks computed keys in destructuring patterns |
| `no-json-callbacks` | `NoJsonCallbacksRule` | Blocks JSON replacer and reviver functions |
| `resource-exhaustion` | (AgentScript preset) | Reports literal sizes that exhaust CPU or memory |
| `unicode-security` | `UnicodeSecurityRule` | Reports bidirectional, look-alike and invisible characters (in no preset) |
| `unreachable-code` | `UnreachableCodeRule` | Reports code after `return` / `throw` |

See [Security Rules](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/security-rules.md) for the options.

### AllowedSyntaxRule

A syntax allowlist: every node of the parsed script must have a type the rule was given, and any other construct is reported with the code `DISALLOWED_SYNTAX`. The [AgentScript preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/agentscript-preset.md) uses it with `AGENTSCRIPT_ALLOWED_NODE_TYPES`, so a construct no other rule names (`this`, classes, `new.target`, `debugger`, generators) is refused rather than passed.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, AllowedSyntaxRule, AGENTSCRIPT_ALLOWED_NODE_TYPES } from '@enclave-vm/ast';
import type { AllowedSyntaxOptions } from '@enclave-vm/ast';

// The AgentScript list, without template literals
const options: AllowedSyntaxOptions = {
  allowedNodeTypes: AGENTSCRIPT_ALLOWED_NODE_TYPES.filter(
    (type) => type !== 'TemplateLiteral' && type !== 'TemplateElement' && type !== 'TaggedTemplateExpression',
  ),
};

const validator = new JSAstValidator([new AllowedSyntaxRule(options)]);
const result = await validator.validate('const greeting = `hello`;');
// result.valid === false, result.issues[0].code === 'DISALLOWED_SYNTAX'
```

| Option | Type | Description |
| - | - | - |
| `allowedNodeTypes` | `readonly string[]` | ESTree node types a script may contain; every other node type is refused |
| `messageTemplate` | `string` | Message of an issue; `{nodeType}` and `{construct}` are replaced |

`AGENTSCRIPT_ALLOWED_NODE_TYPES` is the list for AgentScript v1 as the transformer produces it (a script wrapped in `async function __ag_main()`, loops rewritten). A tagged template is a call that is not a `CallExpression`: a rule that checks how a function is called has to look at `TaggedTemplateExpression` as well.

## Code Transformation

### transformAgentScript(code, config?)

Transform code for safe execution.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function transformAgentScript(
  code: string,
  config?: AgentScriptTransformConfig
): string
```

**Options:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface AgentScriptTransformConfig {
  wrapInMain?: boolean;          // Default: true
  transformCallTool?: boolean;   // Default: true
  transformLoops?: boolean;      // Default: true
  maxIterations?: number;        // Written into each loop check as a number
  additionalIdentifiers?: string[]; // Names that keep their name (custom globals)
  prefix?: string;               // Default: '__safe_'
  parseOptions?: acorn.Options;
}
```

Without `maxIterations` a loop check compares its counter with the runtime's `__maxIterations`, and a script that uses that name is refused.

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { transformAgentScript } from '@enclave-vm/ast';

const transformed = transformAgentScript(`
  const users = await callTool('users:list', {});
  for (const user of users) {
    console.log(user.name);
  }
  return users.length;
`, {
  wrapInMain: true,
  transformCallTool: true,
  transformLoops: true,
  maxIterations: 10000,
});

// Output:
// async function __ag_main() {
//   const users = await __safe_callTool('users:list', {});
//   for (const user of __safe_forOf(users)) {
//     __safe_console.log(user.name);
//   }
//   return users.length;
// }
```

See [Code Transformation](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/code-transform.md) for the other transforms (`transformConcatenation`, `rewriteImports`, ...).

## Custom Rules

### Creating a Custom Rule

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { ValidationSeverity } from '@enclave-vm/ast';
import type { ValidationRule, ValidationContext } from '@enclave-vm/ast';
import * as walk from 'acorn-walk';

class NoConsoleRule implements ValidationRule {
  readonly name = 'no-console';
  readonly description = 'Disallow console statements';
  readonly defaultSeverity = ValidationSeverity.WARNING;
  readonly enabledByDefault = true;

  validate(context: ValidationContext): void {
    walk.simple(context.ast as any, {
      MemberExpression: (node: any) => {
        if (node.object.type === 'Identifier' && node.object.name === 'console') {
          context.report({
            code: 'NO_CONSOLE',
            message: 'Console statements are not allowed',
            location: node.loc ? { line: node.loc.start.line, column: node.loc.start.column } : undefined,
          });
        }
      },
    });
  }
}
```

### Using Custom Rules

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, createAgentScriptPreset } from '@enclave-vm/ast';

const validator = new JSAstValidator([...createAgentScriptPreset(), new NoConsoleRule()]);

try {
  const result = await validator.validate(code);
  // result.valid and result.issues: what the rules reported
} catch (error) {
  // InvalidSourceError, or what a rule threw. The script was not validated: do not run it.
}
```

A rule reports a finding with `context.report()`. An exception it throws instead ends the validation: `validate()` rejects with it, and there is no result.

## Complete Example

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, PreScanner, createAgentScriptPreset, transformAgentScript } from '@enclave-vm/ast';

const validator = new JSAstValidator(createAgentScriptPreset());
const preScanner = new PreScanner({ preset: 'agentscript' });

async function transformAndValidate(code: string) {
  // Step 1: Pre-scan the script as it was written. transformAgentScript() parses its whole
  // input and has no size limit of its own, so the limits (size first) have to hold before
  // it runs.
  const scan = preScanner.scan(code);
  if (!scan.success) {
    return { valid: false, error: scan.fatalIssue?.message ?? 'Pre-scan failed', issues: scan.issues };
  }

  // Step 2: Transform. AgentScript allows a top-level return and await, which only parse
  // once the script is wrapped in its main function.
  let transformed: string;
  try {
    transformed = transformAgentScript(code, {
      wrapInMain: true,
      transformCallTool: true,
      transformLoops: true,
      maxIterations: 10000,
    });
  } catch (error) {
    return { valid: false, error: (error as Error).message, issues: [] };
  }

  // Step 3: Validate the transformed script. The pre-scan has seen the script itself
  // (step 1); its limits are not measured again on the transform's output.
  const validation = await validator.validate(transformed, {
    preScan: { enabled: false },
  });

  if (!validation.valid) {
    return { valid: false, error: 'Validation failed', issues: validation.issues };
  }

  return { valid: true, code: transformed };
}

// Usage
const result = await transformAndValidate(`
  const users = await callTool('users:list', { limit: 10 });
  return users.length;
`);

if (result.valid) {
  console.log('Transformed code:', result.code);
} else {
  console.log('Validation errors:', result.issues);
}
```

The pre-scan comes first because `transformAgentScript()` parses the whole script and has no size limit of its own. The pre-scan that `validate()` runs by default would only see the transformed script, after that parse: a recipe that takes scripts from outside bounds the script as written, as step 1 does.

A script that passes is accepted by the filter. To run it, use [`@enclave-vm/core`](https://docs.agentfront.dev/enclave/api-reference/enclave-vm), which does these steps itself and then runs the script in a sandbox.

## Related

* [Overview](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/overview.md) - Feature overview
* [AgentScript Preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/agentscript-preset.md) - Preset details
* [Custom Rules](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/custom-rules.md) - Writing rules


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.