// Type definitions for Mockarty functional scripts. // // Add this file to the project containing API Tester request and test scripts. // These declarations give your IDE autocomplete and type checking for mk and pm. // In a project with load-test dependencies, use a separate configuration with // "types": [] and include this file explicitly. export {}; declare global { // =========================================================================== // mk / pm — the Mockarty scripting namespace. `mk` and `pm` are THE SAME // object: every pm.* Postman-compatible call and every mk.* extension is // available under both names. // =========================================================================== const mk: Mk; const pm: Mk; /** Legacy Postman v1 global — only setNextRequest is provided. */ const postman: { /** Jump to the named request next; `null` halts the collection run. */ setNextRequest(name: string | null): void; }; // ── Variable stores ───────────────────────────────────────────────────── /** A key/value variable store (environment / variables / collection). */ interface MkVarStore { get(key: string): any; set(key: string, value: any): void; unset(key: string): void; has(key: string): boolean; /** Snapshot of the whole store. */ toObject(): Record; } /** Secret store — reads/writes go to the configured vault backend. */ interface MkVault { get(key: string): string | null; set(key: string, value: string): void; has(key: string): boolean; unset(key: string): void; } // ── Cookies (Postman-compatible jar) ──────────────────────────────────── interface MkCookie { name: string; value: string; domain?: string; path?: string; secure?: boolean; httpOnly?: boolean; expires?: string | number; } interface MkCookieJar { /** Set by (url, name, value, [cb]) or (url, cookieObject, [cb]). */ set(url: string, name: string, value: string, cb?: (err: any) => void): void; set(url: string, cookie: MkCookie, cb?: (err: any) => void): void; /** First cookie matching `name` for the URL (also passed to cb). */ get(url: string, name: string, cb?: (err: any, cookie: MkCookie | null) => void): MkCookie | null; getAll(url: string, cb?: (err: any, cookies: MkCookie[]) => void): MkCookie[]; unset(url: string, name: string, cb?: (err: any) => void): void; clear(url: string, cb?: (err: any) => void): void; } // ── Request / response ────────────────────────────────────────────────── interface MkRequest { /** Outgoing request URL (read-only accessor). */ readonly url: string; /** HTTP method. */ readonly method: string; /** Request body (string). */ readonly body: string; /** Header mutation — add/upsert take a `{key, value}` object. */ headers: { add(header: { key: string; value: string }): void; remove(name: string): void; upsert(header: { key: string; value: string }): void; }; /** Query-string mutation on the outgoing URL. */ query: { add(key: string, value: string): void; get(key: string): string | undefined; has(key: string): boolean; remove(key: string): void; }; } interface MkResponse { /** HTTP status code (read-only accessor). */ readonly code: number; /** Alias for {@link code}. */ readonly statusCode: number; /** Status line text. */ status(): string; /** Parsed JSON response body. */ json(): any; /** Raw response body as a string. */ text(): string; /** Raw response body as a string. */ body(): string; /** Response duration in milliseconds. */ readonly responseTime: number; /** Response headers: direct keys plus a case-insensitive get(). */ readonly headers: Record & { get(name: string): string | null }; /** Fluent response assertions. */ readonly to: { have: { /** Assert the HTTP status code equals `code`. */ status(code: number): void; /** Assert a header is present (and, when given, has `value`). */ header(name: string, value?: string): void; /** Assert the raw body equals / contains `expected`. */ body(expected?: string): void; /** Assert the body is valid JSON (optionally deep-equal to `expected`). */ jsonBody(expected?: any): void; /** Assert the Content-Type header contains `type`. */ contentType(type: string): void; }; }; } // ── Chainable assertions (Chai-compatible subset) ─────────────────────── /** `.and` continues the chain after a passed assertion. */ interface MkAssertionResult { readonly and: MkAssertionTo; } interface MkAssertionLengthOf { (n: number): MkAssertionResult; above(n: number): MkAssertionResult; below(n: number): MkAssertionResult; within(min: number, max: number): MkAssertionResult; at: { least(n: number): MkAssertionResult; most(n: number): MkAssertionResult; }; } interface MkAssertionHave { /** Assert an own property exists (optionally with a value). */ property(name: string, value?: any): MkAssertionResult; /** Assert `.length === n`. */ length(n: number): MkAssertionResult; /** Assert the string contains `sub`. */ string(sub: string): MkAssertionResult; /** Assert the object has (at least) the listed keys. */ keys(...keys: string[]): MkAssertionResult; all: { keys(...keys: string[]): MkAssertionResult }; any: { keys(...keys: string[]): MkAssertionResult }; lengthOf: MkAssertionLengthOf; } interface MkAssertionBe { /** Type assertion: expect(v).to.be.a('string' | 'number' | …). */ a(type: string): MkAssertionResult; an(type: string): MkAssertionResult; above(n: number): MkAssertionResult; below(n: number): MkAssertionResult; within(min: number, max: number): MkAssertionResult; at: { least(n: number): MkAssertionResult; most(n: number): MkAssertionResult; }; oneOf(values: any[]): MkAssertionResult; /** Terminal getters — the assertion fires on property ACCESS. */ readonly true: void; readonly false: void; readonly null: void; readonly undefined: void; readonly empty: void; readonly ok: void; } interface MkAssertionTo { /** Negation — same chain with inverted expectations. */ readonly not: MkAssertionTo; equal(expected: any): MkAssertionResult; eql(expected: any): MkAssertionResult; deep: { equal(expected: any): MkAssertionResult }; /** Assert `fn(value)` returns truthy. */ satisfy(fn: (value: any) => boolean): MkAssertionResult; contain(sub: any): MkAssertionResult; include(sub: any): MkAssertionResult; match(re: RegExp | string): MkAssertionResult; have: MkAssertionHave; be: MkAssertionBe; // Convenience aliases hoisted from `.be` onto `.to`: a(type: string): MkAssertionResult; an(type: string): MkAssertionResult; above(n: number): MkAssertionResult; below(n: number): MkAssertionResult; within(min: number, max: number): MkAssertionResult; oneOf(values: any[]): MkAssertionResult; at: { least(n: number): MkAssertionResult; most(n: number): MkAssertionResult; }; } interface MkAssertion { readonly to: MkAssertionTo; } // ── Shared script-call response (mk.http.send / protocols) ───────────── /** Response shape returned by mk.http.send and every mk protocol call. */ interface MkScriptResponse { statusCode: number; headers: Record; /** Raw body string. */ body: string; /** Raw body string. */ text(): string; /** Body parsed as JSON (null when not valid JSON). */ json(): any; } // ── WS / SSE sessions ─────────────────────────────────────────────────── interface MkWSMessage { data: string; type: "message"; } interface MkWSSession { readonly id: string; /** Send a text frame. */ send(message: string): void; /** Block until a frame arrives (timeout in ms, default engine-set). */ read(timeoutMs?: number): MkWSMessage | null; close(): void; } interface MkSSEEvent { id: string; event: string; data: string; } interface MkSSESession { readonly id: string; /** Read buffered events (timeout in ms). */ read(timeoutMs?: number): MkSSEEvent[]; close(): void; } // ── mk.exec (k6/execution-shaped runtime info) ───────────────────────── interface MkExec { vu: { readonly idInInstance: number; readonly iterationInInstance: number }; scenario: { name: string; iterationInTest: number; iterationInInstance: number }; instance: { vusActive: number; vusInitialized: number; iterationsCompleted: number; iterationsInterrupted: number; }; test: { /** Abort the script with an optional reason (throws). */ abort(reason?: string): never; }; } // ── mk.faker ──────────────────────────────────────────────────────────── interface MkFaker { name(): string; firstName(): string; lastName(): string; email(): string; username(): string; password(): string; phone(): string; uuid(): string; word(): string; sentence(): string; paragraph(): string; url(): string; ipv4(): string; ipv6(): string; date(): string; timestamp(): string; boolean(): boolean; latitude(): number; longitude(): number; macAddress(): string; currency(): string; /** Amount with currency, e.g. "USD 42.17". */ amount(): string; timezone(): string; creditCard(): string; domainName(): string; company(): string; city(): string; street(): string; state(): string; zipCode(): string; country(): string; /** Full address object. */ address(): { street: string; city: string; state: string; zipCode: string; country: string }; } // ── Redis result-less client (functional flavour) ────────────────────── /** * mk.redis — synchronous Redis commands. Every call takes the redis URL * (`redis://host:port` or `host:port`) as its FIRST argument; failures * log to the console tab and return null. */ interface MkRedis { connect(url: string): boolean; get(url: string, key: string): string | null; set(url: string, key: string, value: any, ttlSeconds?: number): string | null; del(url: string, ...keys: string[]): number | null; exists(url: string, ...keys: string[]): number | null; incr(url: string, key: string): number | null; incrBy(url: string, key: string, by: number): number | null; decr(url: string, key: string): number | null; decrBy(url: string, key: string, by: number): number | null; expire(url: string, key: string, seconds: number): boolean | null; ttl(url: string, key: string): number | null; hset(url: string, key: string, field: string, value: any): number | null; hget(url: string, key: string, field: string): string | null; hdel(url: string, key: string, ...fields: string[]): number | null; hgetall(url: string, key: string): Record | null; hkeys(url: string, key: string): string[] | null; hvals(url: string, key: string): string[] | null; hincrby(url: string, key: string, field: string, by: number): number | null; lpush(url: string, key: string, ...values: any[]): number | null; rpush(url: string, key: string, ...values: any[]): number | null; lpop(url: string, key: string): string | null; rpop(url: string, key: string): string | null; lrange(url: string, key: string, start: number, stop: number): string[] | null; llen(url: string, key: string): number | null; sadd(url: string, key: string, ...members: any[]): number | null; srem(url: string, key: string, ...members: any[]): number | null; smembers(url: string, key: string): string[] | null; sismember(url: string, key: string, member: any): boolean | null; zadd(url: string, key: string, score: number, member: string): number | null; zrem(url: string, key: string, ...members: any[]): number | null; zscore(url: string, key: string, member: string): number | null; zrank(url: string, key: string, member: string): number | null; zrange(url: string, key: string, start: number, stop: number): string[] | null; zcard(url: string, key: string): number | null; } // ── The main namespace ────────────────────────────────────────────────── interface Mk { // Postman-compatible core ------------------------------------------------- /** The response of the request this script is attached to (test scripts). */ readonly response: MkResponse; /** The outgoing request (pre-request scripts may mutate headers/query). */ readonly request: MkRequest; /** Environment variables — persist across requests in the run. */ readonly environment: MkVarStore; /** Short alias for {@link environment} (mk.env.set(...)). */ readonly env: MkVarStore; /** Postman-compat alias of {@link environment}. */ readonly globals: MkVarStore; /** Request-scoped variables — current request only. */ readonly variables: MkVarStore; /** Collection-scoped variables. */ readonly collectionVariables: MkVarStore; /** Secret vault (masked in logs). */ readonly vault: MkVault; /** Cookie jar access: pm.cookies.jar(). */ readonly cookies: { jar(): MkCookieJar }; /** Register a named test. Body runs assertions; a throw fails the test. */ readonly test: { (name: string, fn: () => void): void; /** Register a skipped test (reported, not executed). */ skip(name: string, fn?: () => void): void; }; /** Chai-style expectation. */ expect(actual: any): MkAssertion; /** Fire an ad-hoc request, Postman style: callback receives (err, response). */ sendRequest( urlOrOptions: string | { method?: string; url: string; headers?: Record; body?: string }, cb: (err: any, res: MkScriptResponse | null) => void, ): void; /** Script/run metadata. */ readonly info: { requestId: string; requestName: string; collectionId: string; collectionName: string; /** 0-based iteration index. */ iteration: number; iterationCount: number; /** "prerequest" | "test". */ eventName: string; }; /** Per-iteration data rows (CSV/JSON data files). */ readonly iterationData: { get(key: string): any; toObject(): Record; }; /** Workflow control (collection runs). */ readonly execution: { /** Jump to the named request next; `null` halts the run. */ setNextRequest(name: string | null): void; /** Halt the run, rendered as "skipped". */ skipRequest(): void; readonly location: { readonly currentName: string }; }; // Mockarty extensions ------------------------------------------------------ /** Fire an ad-hoc HTTP request from a script (null on failure). */ readonly http: { send(opts: { method?: string; url: string; headers?: Record; body?: string }): MkScriptResponse | null; }; /** Cross-request scratch space for the current run. */ readonly runContext: { get(key: string): any; set(key: string, value: any): void; toObject(): Record; clear(): void; }; /** Namespace-shared persistent key/value store (survives runs). */ readonly sharedData: { get(key: string): any; set(key: string, value: any): void; delete(key: string): void; has(key: string): boolean; keys(): string[]; getAll(): Record; clear(): void; size(): number; increment(key: string, by?: number): number; push(key: string, value: any): void; pop(key: string): any; getArray(key: string): any[]; }; /** Manage mocks from a script. */ readonly mocker: { get(idOrOpts: any): any; create(mock: Record): any; delete(id: string): any; }; // Protocol clients (each takes an options object; null on failure) -------- readonly grpc: { /** Unary gRPC call via server reflection. */ invoke(opts: { address: string; service: string; method: string; body?: any; metadata?: Record; useTLS?: boolean; }): MkScriptResponse | null; }; readonly graphql: { query(opts: { url: string; query: string; variables?: Record; operationName?: string; headers?: Record; }): MkScriptResponse | null; }; readonly soap: { /** SOAP call — `endpoint` + full XML `body` are required. */ call(opts: { endpoint: string; body: string; action?: string; headers?: Record }): MkScriptResponse | null; }; readonly mcp: { /** Invoke an MCP tool over the server transport. */ call(opts: { url: string; tool: string; params?: Record; headers?: Record; auth?: Record; }): MkScriptResponse | null; }; readonly kafka: { /** Publish a message. Returns the raw executor result. */ publish(opts: { brokers: string | string[]; topic: string; key?: string; value?: any; message?: any; headers?: Record; }): { published?: boolean; body?: string; [k: string]: any } | null; /** Read messages. Returns the raw executor result. */ consume(opts: { brokers: string | string[]; topic: string; groupId?: string; consumerGroup?: string; group?: string; maxMessages?: number; /** Receive timeout in milliseconds. */ timeout?: number; }): { messages?: any[] | null; count?: number; topic?: string; body?: string; [k: string]: any } | null; }; readonly rabbitmq: { publish(opts: { url: string; queue?: string; exchange?: string; routingKey?: string; /** String or JSON-serializable message to publish. */ message: unknown; }): { published?: boolean; queue?: string; exchange?: string; body?: string; [k: string]: any } | null; consume(opts: { url: string; queue: string; consumerTag?: string; maxMessages?: number; /** Receive timeout in milliseconds. */ timeout?: number; }): { messages?: any[] | null; count?: number; queue?: string; body?: string; [k: string]: any } | null; }; /** Imperative WebSocket session. */ readonly ws: { connect(url: string, opts?: { headers?: Record }): MkWSSession | null }; /** Buffered Server-Sent Events session. */ readonly sse: { connect(url: string, opts?: { headers?: Record }): MkSSESession | null }; /** Browser-step actions (recorded, dispatched after the script). */ readonly ui: { click(selector: string): void; fill(selector: string, value: string): void; navigate(url: string): void; screenshot(name?: string): void; waitFor(selector: string): void; assert(message: string): void; }; /** SQL access (rows as objects; null on failure). */ readonly db: { query(opts: { dsn: string; query: string; driver?: string; params?: any[] }): Record[] | null; exec(opts: { dsn: string; query: string; driver?: string; params?: any[] }): { rowsAffected: number } | null; }; /** Convenience wrapper over {@link db}: (dsn, sql, params?). */ readonly sql: { query(dsn: string, sql: string, params?: any[]): Record[] | null; exec(dsn: string, sql: string, params?: any[]): { rowsAffected: number } | null; }; readonly redis: MkRedis; readonly exec: MkExec; readonly faker: MkFaker; // Utilities --------------------------------------------------------------- /** Pause the script for `ms` MILLISECONDS (capped at 10 000). */ sleep(ms: number): void; uuid(): string; /** randomInt(max) or randomInt(min, max) — inclusive. */ randomInt(minOrMax?: number, max?: number): number; /** Random alphanumeric string (default length 16). */ randomString(length?: number): string; randomSentence(words?: number): string; /** Random string from a pattern ('#'=digit, '?'=letter, '*'=either). */ randomByPattern(pattern: string): string; readonly base64: { encode(input: string): string; decode(input: string): string; }; readonly crypto: { md5(input: string): string; sha256(input: string): string; /** HMAC hex digest: (secret, message, algo? = "sha256" | "sha1"). */ hmac(secret: string, message: string, algo?: string): string; }; /** Convert an XML string to a JSON-compatible object. */ xml2json(xml: string): any; /** Evaluate a JSONPath against a value. */ jsonpath(value: any, path: string): any; } // =========================================================================== // Globals installed alongside mk/pm // =========================================================================== /** k6-style check — each named predicate is also recorded as a test result. */ function check(value: any, checks: Record boolean>): boolean; /** Pause for `seconds` (k6 style — SECONDS, capped at 30; mk.sleep takes ms). */ function sleep(seconds: number): void; /** Environment variables, k6 style. */ const __ENV: Record; /** Global aliases of the mk sub-objects. */ const faker: MkFaker; const sql: Mk["sql"]; const redis: MkRedis; const exec: MkExec; // console — standard logging plus table/dir/assert/time/count/group. // (lib.dom declares console; these members exist at runtime: log, error, // warn, info, debug, table, dir, assert, clear, time, timeEnd, count, // countReset, trace, group, groupCollapsed, groupEnd.) /** * require('') — built-in module catalogue (null for unknown names): * 'mockarty/http' ('k6/http'), 'mockarty/sql' ('sql'), 'mockarty/uuid' * ('uuid'), 'mockarty/base64', 'mockarty/crypto' ('crypto'), * 'mockarty/json', 'mockarty/csv' ('csv-parse/lib/sync'), 'mockarty/xml' * ('xml2js'). */ function require(id: "mockarty/http" | "k6/http"): MkRequireHTTP; function require(id: "mockarty/sql" | "sql"): Mk["sql"]; function require(id: "mockarty/uuid" | "uuid"): { v4(): string; v7(): string; validate(s: string): boolean; default(): string }; function require(id: "mockarty/base64"): { encode(s: string): string; decode(s: string): string }; function require(id: "mockarty/crypto" | "crypto"): { md5(s: string): string; sha256(s: string): string; hmac(secret: string, msg: string, algo?: string): string }; function require(id: "mockarty/json"): { path(value: any, path: string): any; merge(a: any, b: any): any; diff(a: any, b: any): any; stringify(v: any): string; parse(s: string): any }; function require(id: "mockarty/csv" | "csv-parse/lib/sync"): { parse(input: string, opts?: Record): any[]; stringify(rows: any[]): string }; function require(id: "mockarty/xml" | "xml2js"): { parse(xml: string): any; parseString(xml: string): any; build(obj: any): string }; function require(id: string): any; /** k6-shaped HTTP module returned by require('mockarty/http'). */ interface MkRequireHTTP { get(url: string, params?: MkHttpParams): MkHttpResponse | null; post(url: string, body?: string, params?: MkHttpParams): MkHttpResponse | null; put(url: string, body?: string, params?: MkHttpParams): MkHttpResponse | null; patch(url: string, body?: string, params?: MkHttpParams): MkHttpResponse | null; del(url: string, body?: string, params?: MkHttpParams): MkHttpResponse | null; head(url: string, params?: MkHttpParams): MkHttpResponse | null; } interface MkHttpParams { headers?: Record; } /** Response returned by the require('mockarty/http') verbs. */ interface MkHttpResponse { status: number; body: string; text: string; headers: Record; timings: { duration: number }; json(): any; } }