> For the complete documentation index, see [llms.txt](https://infinitode-docs.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://infinitode-docs.gitbook.io/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference.md).

# CloakJS Reference

Complete API reference for CloakJS 1.3.0: obfuscate, obfuscateWithStats, measure, resolveOptions, presets, techniques, the stats and warnings fields, seeded reproducibility, option validation, and beh

Everything CloakJS exposes is on the single `CloakJS` object. There is no configuration file, no plugin system and no async API — every call returns synchronously.

## Methods and properties

| Member                                         | Returns                                     | Description                                                                                                                                                                                       |
| ---------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CloakJS.obfuscate(source, options?)`          | `string`                                    | Obfuscated JavaScript **source code**. Use when you only need the output.                                                                                                                         |
| `CloakJS.obfuscateWithStats(source, options?)` | `{ code, stats, warnings }`                 | The same output plus counters, the techniques applied and warnings. Prefer this while integrating.                                                                                                |
| `CloakJS.measure(source, options?)`            | `{ originalBytes, obfuscatedBytes, ratio }` | Size comparison only. Generates its own random sample, so it doesn't necessarily describe an earlier `obfuscate` call.                                                                            |
| `CloakJS.resolveOptions(options?)`             | `object`                                    | The **validated** effective settings: the chosen preset or the defaults, merged with your overrides. Returns a copy, so mutating it doesn't affect `CloakJS.presets` or `CloakJS.defaultOptions`. |
| `CloakJS.presets`                              | `object`                                    | The five presets, keyed by name. Every preset defines every key.                                                                                                                                  |
| `CloakJS.defaultOptions`                       | `object`                                    | The default settings (the `high` settings).                                                                                                                                                       |
| `CloakJS.techniques`                           | `array`                                     | Metadata for every transform: `key`, `name`, `summary`, `changesBehavior`.                                                                                                                        |
| `CloakJS.NAME`                                 | `string`                                    | `"CloakJS"`.                                                                                                                                                                                      |
| `CloakJS.VERSION`                              | `string`                                    | Library version, e.g. `"1.3.0"`.                                                                                                                                                                  |
| `CloakJS.BANNER`                               | `string`                                    | A one-line name, version and licence string.                                                                                                                                                      |

### Parameters

`source` — **required**, and must be a string of JavaScript source. Anything else throws `TypeError: CloakJS: source must be a string`. CloakJS doesn't read files: load the source yourself and pass the text.

`options` — optional, and one of:

* **omitted** — the default settings are used (the `high` settings);
* **a preset name** — `'off'`, `'low'`, `'medium'`, `'high'` or `'extreme'`;
* **an options object** — only the keys you supply override the defaults, so `{ stringEncryption: false }` leaves every other setting at its `high` value.

#### Validation

Unlike earlier releases, 1.3.0 validates options instead of silently ignoring mistakes — a typo fails loudly:

| Input                              | Thrown                                                                                       |
| ---------------------------------- | -------------------------------------------------------------------------------------------- |
| `{ stringEncrypton: true }`        | `TypeError: CloakJS: unknown option "stringEncrypton"`                                       |
| `{ stringEncryption: "yes" }`      | `TypeError: CloakJS: option "stringEncryption" must be true or false`                        |
| `{ stringEncoding: "aes" }`        | `TypeError: CloakJS: option "stringEncoding" must be one of: base64, rc4`                    |
| `C.obfuscate(source, "strongest")` | `Error: CloakJS: unknown preset "strongest". Valid presets: off, low, medium, high, extreme` |
| `C.obfuscate(source, [])`          | `TypeError: CloakJS: options must be a preset name or an options object`                     |

Validation happens before anything runs, so an invalid call never produces partial output.

## Reproducible output with `seed`

Output is randomised and differs between calls, which is what you want for a fresh release build and awkward for a pipeline. Pass a `seed` (string, number, or `null` for unseeded) to make it repeatable:

```js
const first  = CloakJS.obfuscate(source, { seed: "build-42" });
const second = CloakJS.obfuscate(source, { seed: "build-42" });

console.log(first === second); // true

const result = CloakJS.obfuscateWithStats(source, { seed: "build-42" });
console.log(result.stats.seed); // "build-42" — or null when unseeded
```

A different seed produces different output, and the seed is reported back in `stats.seed`. Everything else about the call behaves identically, and the generated code still runs in a bare sandbox.

## The `stats` object

| Field                | Type                       | Meaning                                                                      |
| -------------------- | -------------------------- | ---------------------------------------------------------------------------- |
| `identifiersRenamed` | `number`                   | Distinct spellings that were renamed.                                        |
| `identifiersEscaped` | `number`                   | Identifier occurrences rewritten with `\uXXXX` escapes.                      |
| `stringsEncrypted`   | `number`                   | String literals (and static template literals) moved into the encoded array. |
| `stringsSplit`       | `number`                   | Strings that were split into concatenated chunks.                            |
| `stringArrayEntries` | `number`                   | Entries in the emitted string array, including decoys.                       |
| `numbersEncoded`     | `number`                   | Numeric literals rewritten as expressions.                                   |
| `controlFlowBlocks`  | `number`                   | `switch` dispatchers that were generated.                                    |
| `deadCodeBlocks`     | `number`                   | Unreachable decoy blocks that were inserted.                                 |
| `opaquePredicates`   | `number`                   | Opaque conditions that were generated.                                       |
| `originalBytes`      | `number`                   | UTF-8 byte length of your input.                                             |
| `obfuscatedBytes`    | `number`                   | UTF-8 byte length of the generated code.                                     |
| `ratio`              | `number`                   | `obfuscatedBytes / originalBytes`. **Above 1 means the output grew.**        |
| `techniques`         | `string[]`                 | The technique keys actually applied to this input.                           |
| `seed`               | `string \| number \| null` | The seed that was used, or `null`.                                           |

The counters describe what *happened*, not what was configured. A pass with nothing eligible reports zero, and `techniques` omits techniques that had no effect — for example, `numberEncoding` is configured `true` at `medium`, but a source whose only literal is `2` reports `numbersEncoded: 0` and no `numberEncoding` entry, because single-digit literals are left alone.

```js
const result = CloakJS.obfuscateWithStats(source, "high");
console.log(result.stats.techniques);
// [ 'identifierMangling', 'controlFlowFlattening', 'deadCodeInjection',
//   'stringEncryption', 'stringCipher', 'selfDefending' ]
```

## The `warnings` array

`warnings` lists things CloakJS deliberately skipped. It's **advisory**: an empty array doesn't prove the output behaves like the input, and a warning doesn't necessarily mean the output is broken.

| Warning                                                                                                                                            | What happened                                                                                                                                                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Module syntax (import/export) detected: identifier mangling and escaping were skipped.`                                                           | The input uses `import`/`export`. Renaming is skipped, because the internal `new Function` parse check only accepts scripts. Strings in `from` clauses are left untouched. The output will usually also report a parse warning — see below. |
| `eval() or with() detected: identifier mangling and escaping were skipped, because dynamic scope cannot be analysed.`                              | Dynamic scope can reach local names, so renaming is unsafe. The other transforms still run.                                                                                                                                                 |
| `Function() is called with generated source: identifier mangling and escaping were skipped, because the generated code may reference local names.` | The input builds code with `new Function("…")` from a string. Same reasoning.                                                                                                                                                               |
| `Output failed to parse: …`                                                                                                                        | The generated code failed the internal `new Function` check. **Don't ship that output** — simplify the input, or disable the pass involved.                                                                                                 |

```js
const result = CloakJS.obfuscateWithStats('var x = 1; eval("x"); console.log(2);', "high");
console.log(result.warnings);
// [ 'eval() or with() detected: identifier mangling and escaping were skipped, because dynamic scope cannot be analysed.' ]
```

{% hint style="danger" %}
`warnings` never guarantees behavioural equivalence, and an empty array is not a clean bill of health. Always run your own tests against the generated code before shipping it.
{% endhint %}

## Size measurement

```js
const size = CloakJS.measure(source, "extreme");

console.log(size.originalBytes);    // input size
console.log(size.obfuscatedBytes);  // generated size
console.log(size.ratio);            // obfuscatedBytes / originalBytes
```

Decoys, flattening and the decoder all add bytes, and the decoder is a **fixed cost** that doesn't shrink with your input — so small snippets grow enormously while larger files grow more gently. Two measured examples from this documentation:

| Sample                                           | `off` | `low` | `medium` | `high` | `extreme` |
| ------------------------------------------------ | ----- | ----- | -------- | ------ | --------- |
| \~6 KB of numeric statements, few strings        | 1.00× | 1.22× | 1.69×    | 4.16×  | 5.26×     |
| \~4 KB with 40 small functions and a string each | 1.00× | 1.01× | 1.84×    | 6.37×  | 19.75×    |
| 126-byte snippet                                 | 1.00× | 1.37× | 13.98×   | 26.19× | 47.67×    |

Content matters as much as size: string-dense and function-dense files grow far more than numeric ones, because each eligible literal and statement run can attract encoding, splitting, decoys and dispatchers. Always measure your own file rather than extrapolating. If size is the constraint, use `low` or `off`, or turn off `deadCodeInjection` and `stringArrayDecoys`.

## What the generated code needs at runtime

Almost nothing — that's the point of the 1.3.0 rewrite:

* **The decoder is self-contained.** It implements its own Base64, alphabet substitution, RC4 and UTF-8 handling, so output runs in a bare sandbox with no globals, polyfills or helper files. Verified in the test suite and CI, which run every preset in an empty context.
* **`TextDecoder` and `Uint8Array` are an optional fast path.** When the host provides them, the decoder uses them; when it doesn't, it falls back to its own UTF-8 decoding.
* **`new Function` is used during generation** for the parse check, and by generated opaque predicates. If a Content Security Policy blocks `eval`-like compilation in your own build tooling, that affects generation rather than the shipped script.
* **Output is a script, not a module.** `import`/`export` input triggers the module warning and isn't supported; JSX, TypeScript, decorators and stage-3 syntax may end up only partially obfuscated.
* **A leading `"use strict";` stays a directive**, emitted in front of the generated code — and moved inside the wrapper when `wrapInIife` is used.
* **`debugProtection` calls `.unref()`** on its timer when the handle supports it, so Node.js processes can still exit.

## Behaviour that may surprise you

Read this before shipping obfuscated output.

| Situation                                                 | What happens                                                                                                                                                                                                                       |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Code reads `someFunction.name` or `this.constructor.name` | Mangling renames functions and classes, so those strings change. Set `preserveFunctionNames: true` to keep them.                                                                                                                   |
| A binding is part of a public API                         | Mangling renames top-level declarations too. Disable `identifierMangling` (or use `low` and check) when other scripts refer to them by name.                                                                                       |
| Property access through strings, e.g. `obj["count"]`      | Every spelling that appears as a property name, object key or string key is left untouched, so such code keeps working.                                                                                                            |
| `eval`, `with`, `new Function("…")`                       | Mangling and escaping are skipped, with a warning. The other transforms still run.                                                                                                                                                 |
| Output is minified after obfuscation                      | `selfDefending` throws `Error("Unexpected token")` at runtime, because a minifier renames or rewrites the generated functions. Whitespace-only reformatting is tolerated. Disable `selfDefending`, or obfuscate *after* minifying. |
| Output is obfuscated a **second** time                    | A first pass at `high` or `extreme` leaves a guard in the code, and a second pass rewrites the guarded functions — so the twice-obfuscated program throws. Output from `off`, `low` or `medium` can be obfuscated again.           |
| Empty or comment-only input                               | Returned as-is, with no guards, decoys or decoder.                                                                                                                                                                                 |
| Script completion value                                   | The last top-level statement is never moved, wrapped or followed by decoy code, so the value a script evaluates to is preserved — except with `wrapInIife`, where it becomes `undefined`.                                          |
| `debugProtection` in Node.js                              | A repeating timer is installed. It is unref'ed when possible so the process can still exit, but code that observes timers will see it.                                                                                             |
| `disableConsoleOutput`                                    | All common `console` methods become no-ops for the whole page or process, not just for your code.                                                                                                                                  |
| `wrapInIife`                                              | Top-level `var`/`function` declarations and top-level `this` stop leaking to the global object, and the completion value becomes `undefined`.                                                                                      |
| Heavily minified input                                    | CloakJS is a lexer, not a parser. It preserves what it doesn't rewrite and skips what it can't prove safe — but always test the generated code.                                                                                    |

{% hint style="info" %}
A source that declares a name CloakJS also generates is no longer a problem: generated names come from a pool that avoids reserved words, globals and every spelling already present in your input.
{% endhint %}

## Related pages

* [Options and presets](/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference/cloakjs-options.md) — every setting, with what it changes and its limits.
* [Usage examples](/documentation/package-documentation/cloakjs-package-documentation/cloakjs-usage-examples.md) — browser, Node and build-pipeline walkthroughs.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://infinitode-docs.gitbook.io/documentation/package-documentation/cloakjs-package-documentation/cloakjs-reference.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
