# Postman Script Support

Kusho supports commonly used Postman scripting patterns in pre-request and post-response scripts. This makes it easier to reuse scripts from Postman collections and to write scripts using familiar Postman APIs.

Postman-style scripting is available in both pre-run scripts and post-run scripts.

You can use Postman-style scripts to set variables, modify requests before they are sent, inspect responses, run assertions, and make helper requests.

## Supported Postman APIs

The following commonly used Postman APIs are supported:

```javascript
pm.environment.get("token");
pm.environment.set("token", "abc123");

pm.variables.get("userId");
pm.variables.set("userId", "123");

pm.request.headers.upsert({
  key: "Authorization",
  value: "Bearer abc123"
});

pm.request.url.query.upsert({
  key: "source",
  value: "kusho"
});

pm.request.body.update(JSON.stringify({
  name: "Alice",
  role: "admin"
}));

pm.test("status is 200", function () {
  pm.expect(pm.response.code).to.equal(200);
});
```

You can also use helper requests:

```javascript
const response = await pm.sendRequest({
  method: "POST",
  url: "https://api.example.com/auth",
  header: {
    "Content-Type": "application/json"
  },
  body: {
    mode: "raw",
    raw: JSON.stringify({
      username: "test-user",
      password: "test-password"
    })
  }
});

const token = response.json().token;
pm.environment.set("authToken", token);
```

## Common Use Cases

### Set a Token Before a Request

Use a pre-request script to fetch a token and attach it to the outgoing request:

```javascript
const authResponse = await pm.sendRequest({
  method: "POST",
  url: "https://api.example.com/login",
  header: {
    "Content-Type": "application/json"
  },
  body: {
    mode: "raw",
    raw: JSON.stringify({
      email: "test@example.com",
      password: "password"
    })
  }
});

const token = authResponse.json().token;
pm.environment.set("authToken", token);

pm.request.headers.upsert({
  key: "Authorization",
  value: `Bearer ${token}`
});
```

### Modify the Request Body

Use `pm.request.body.update(...)` to change the body before the request is sent:

```javascript
const body = JSON.parse(pm.request.body.raw || "{}");

body.requestId = crypto.randomUUID();
body.timestamp = new Date().toISOString();

pm.request.body.update(JSON.stringify(body));
```

### Validate the Response

Use `pm.test(...)` and `pm.expect(...)` in post-response scripts:

```javascript
pm.test("request succeeded", function () {
  pm.expect(pm.response.code).to.equal(200);
});

pm.test("response has user id", function () {
  const data = pm.response.json();
  pm.expect(data.user.id).to.exist;
});
```

## Variables

Variable APIs such as `pm.environment.set(...)`, `pm.variables.set(...)`, and Kusho's `setVariables(...)` are available during the current run.

Values set in a script can be used later in the same run:

```javascript
pm.environment.set("userId", "123");
```

You can then use the variable in a later request:

```json
{
  "user_id": ""
}
```

In an E2E workflow, variables set by one API's script are available to later APIs in that workflow run.

### Variable Persistence

Variable changes made during script execution are available during the current run, including later requests in an E2E workflow. They are not persisted back to the environment after the run yet.

If you need a variable to be available across future runs, create or update it in the Kusho environment variables section.

## Script Run Frequency

Pre-request scripts run for executed test cases or workflow nodes in the current flow.

If you are coming from Postman and rely on collection-level "run once" behavior, verify the flow after import or setup. In Kusho, request-specific scripts are usually run before the request they are attached to, especially when the script needs access to the current request object.

## Kusho Helpers

Kusho script helpers are also available:

```javascript
setVariables({ token: "abc123" });

const variables = getVariables();
debug("Current token", variables.token);

const response = await makeRequest({
  method: "GET",
  url: "https://api.example.com/health",
  headers: {},
  query_params: {},
  json_body: {}
});
```

You can use either Postman-style APIs or Kusho helpers. For new scripts copied from Postman, prefer the `pm.*` APIs.

## Supported Helper Libraries

Common helper libraries and browser-safe utilities are available for scripts, including:

- `CryptoJS`
- Lodash (`_` / `lodash`)
- `moment`
- `dayjs`
- `Ajv`
- `tv4`
- `Buffer`
- `URL`
- `URLSearchParams`
- `querystring`
- `path`
- `uuid`
- `faker`

Example:

```javascript
const signature = CryptoJS.HmacSHA256("payload", "secret").toString();

pm.request.headers.upsert({
  key: "X-Signature",
  value: signature
});
```

## What Is Not Supported

Some Postman desktop/runtime features are not supported in Kusho scripts. Most of these features require Postman's desktop runtime, local filesystem access, or Postman's internal execution model. Kusho scripts run in a browser/extension environment, so those APIs cannot behave the same way.

### Cookie Jar APIs

Postman cookie jar APIs such as `pm.cookies.jar()` and domain-scoped cookie persistence are not supported.

Browser/extension execution does not provide the same cookie jar model as Postman desktop. If your API relies on cookies, use explicit headers or variables where possible.

### Postman Vault

Postman Vault APIs such as `pm.vault.*` are not supported.

Use Kusho environment variables or secrets where available.

### Flow Control APIs

Postman flow-control APIs are not supported:

```javascript
pm.execution.setNextRequest(...);
pm.execution.skipRequest();
pm.execution.runRequest(...);
```

Kusho E2E workflow order is controlled by the workflow graph, not by script-level Postman flow-control commands.

### Package Loading and Node Runtime APIs

Package/module loading is not supported:

```javascript
pm.require(...);
require(...);
```

Local filesystem and Node runtime APIs are also not supported:

```javascript
fs
process
http
https
stream
child_process
```

Scripts run in the browser/extension environment, so they cannot access the local filesystem or Node runtime directly.

### Full Postman SDK Object Parity

Kusho supports the commonly used methods on `pm.request`, `pm.response`, headers, variables, URLs, and request bodies. However, Kusho does not provide exact parity with every internal Postman SDK object or every edge case of the Postman runtime.

For most API workflows that use variables, request mutation, response parsing, helper requests, and assertions, scripts should work as expected. Advanced Postman desktop/runtime features may need small adjustments.

## Troubleshooting

### A Variable Did Not Resolve

Make sure the variable exists in the selected Kusho environment, or that it is set earlier in the same run.

```javascript
console.log("authToken", pm.environment.get("authToken"));
```

### A Script Works in Postman but Not in Kusho

Check whether the script uses unsupported Postman desktop features such as cookie jars, `pm.vault`, `pm.execution`, `pm.require`, `require`, or local filesystem APIs.

If the script uses Node's `crypto` package, use `CryptoJS` instead:

```javascript
const hash = CryptoJS.SHA256("payload").toString();
```

### Request Changes Are Not Applied

If you are modifying the outgoing request, make sure the script is configured as a pre-request script and that it runs for the request you are executing.

```javascript
pm.request.headers.upsert({
  key: "X-Debug",
  value: "script-ran"
});
```
