Code Generator API

relay

The helper functions for building, quoting and encoding generated code.

Declaration

relay

Overview

Every generator can use the global relay object. Relay also passes it to generate as the second argument, which generators conventionally name r. The helpers are plain JavaScript functions that take and return plain values, so you can use them anywhere in a generator's file.

function generate(req, r) {
  var b = r.builder(' \\\n  ');
  b.add('curl -X ' + req.method + ' ' + r.q.shell(req.url));
  r.allHeaders(req).forEach(function (header) {
    b.add('-H ' + r.q.shell(header.name + ': ' + header.value));
  });
  if (req.body.text !== undefined) b.add('--data-raw ' + r.q.shell(req.body.text));
  return b.join();
}

In the signatures below, Header is a { name, value } object, as in ExportRequest.

Topics

Building text

builder(joiner)

relay.builder(joiner?: string): Builder

Returns a builder that collects pieces of text and joins them with joiner, a newline by default.

A builder has these methods. add, addIf and addAll return the builder, so you can chain them.

  • add(text): Adds text.
  • addIf(condition, text): Adds text when condition is truthy.
  • addAll(items): Adds each item of the array items.
  • isEmpty(): Returns whether nothing has been added.
  • join(joiner): Returns the pieces joined with joiner, or with the builder's own joiner when you leave it out.

indent(text, spaces)

relay.indent(text: string, spaces?: number): string

Returns text with each line that isn't empty indented by spaces spaces, 2 by default.

lines(...parts)

relay.lines(...parts: (string | null | undefined | false)[]): string

Returns the parts joined with newlines, leaving out those that are null, undefined or false, so you can write relay.lines(a, condition && b, c).

Encoding values

byteLength(text)

relay.byteLength(text: string): number

Returns the length of text in UTF-8 bytes, as a Content-Length header counts it.

base64(text)

relay.base64(text: string): string

Returns the base64 encoding of text's UTF-8 bytes.

percentEncode(text)

relay.percentEncode(text: string): string

Returns text percent-encoded as Relay encodes URL components, leaving only letters, digits and -._~ unencoded.

formEncode(pairs)

relay.formEncode(pairs: Header[]): string

Returns the pairs as an application/x-www-form-urlencoded string, such as name=Widget&size=10.

json(value, spaces)

relay.json(value: any, spaces?: number): string

Returns value as JSON, indented by spaces spaces, 2 by default.

parseJSON(text)

relay.parseJSON(text: string): any

Returns the value text holds as JSON, or null when it isn't valid JSON. Objects keep their keys in the order they're written, so code built from them matches the request's body.

Quoting strings

Each function in relay.q returns its argument as a string literal for one language, with the characters that language treats specially escaped.

q.shell(text)

relay.q.shell(text: string): string

Returns a single-quoted shell string, in which nothing is expanded. A single quote inside becomes '\''.

q.shellDouble(text)

relay.q.shellDouble(text: string): string

Returns a double-quoted shell string, with ", \, $ and backticks escaped.

q.js(text), q.go(text), q.java(text), q.csharp(text), q.swift(text), q.python(text)

relay.q.js(text: string): string

Returns a double-quoted string with C-style escapes, which is valid in JavaScript, Go, Java, C#, Swift and Python.

q.kotlin(text)

relay.q.kotlin(text: string): string

Returns a double-quoted Kotlin string, with $ escaped so it isn't treated as a template.

q.powershell(text)

relay.q.powershell(text: string): string

Returns a single-quoted PowerShell string, in which nothing is expanded. Single quotes inside, including typographic ones, are doubled.

q.c(text)

relay.q.c(text: string): string

Returns a double-quoted C string, with control characters written as octal escapes and ? escaped where it would form a trigraph.

q.rust(text)

relay.q.rust(text: string): string

Returns a double-quoted Rust string, with control characters written as \u{…} escapes.

q.php(text), q.ruby(text)

relay.q.php(text: string): string

Returns a single-quoted string, with backslashes and single quotes escaped, in which PHP and Ruby don't interpolate variables.

Working with headers

allHeaders(req)

relay.allHeaders(req: ExportRequest): Header[]

Returns every header the request sends: its headers, then the headers its authentication adds, a WebSocket request's Sec-WebSocket-Protocol header and the Cookie header for its cookies. For Digest and NTLM authentication, which answer the server's challenge, it writes a warning to the console once instead.

authHeader(auth)

relay.authHeader(auth: Auth): Header | null

Returns the Authorization header for bearer or basic authentication, or null for any other type. When the credentials are redacted, the basic header holds them as they are rather than base64-encoding the placeholders.

authHeaders(auth)

relay.authHeaders(auth: Auth): Header[]

Returns every header the authentication adds: the Authorization header for bearer and basic, or the signature headers for AWS Signature, OAuth 1.0 and Hawk. Returns an empty array for none, Digest and NTLM.

authNote(auth, req)

relay.authNote(auth: Auth, req?: ExportRequest): string | null

Returns a sentence explaining authentication the generated code can't carry by itself, to add as a comment, or null when there's nothing to explain. It covers Digest and NTLM, which need a client that supports them, and AWS Signature, OAuth 1.0 and Hawk, whose signatures expire. Pass the request so a WebSocket request's note describes its handshake.

cookieHeader(cookies)

relay.cookieHeader(cookies: Header[]): Header | null

Returns a Cookie header for the cookies, or null when there are none.

hostHeader(req)

relay.hostHeader(req: ExportRequest): Header | null

Returns a Host header for the request's URL, with the port when the URL names one and an IPv6 address in brackets, or null when the URL has no host.

subprotocolHeader(req)

relay.subprotocolHeader(req: ExportRequest): Header | null

Returns the Sec-WebSocket-Protocol header for a WebSocket request's subprotocols, or null when it has none or isn't a WebSocket request.

webSocketKey

relay.webSocketKey: string

A sample Sec-WebSocket-Key value, dGhlIHNhbXBsZSBub25jZQ==, from RFC 6455. A real client sends a random key; generators that write out a handshake use this one so the code is the same each time.

headersWithout(headers, names)

relay.headersWithout(headers: Header[], names: string[]): Header[]

Returns the headers without those named in names, compared without regard to case. Use it to leave out a header the target library sets itself, such as a multipart body's Content-Type.

hasHeader(headers, name)

relay.hasHeader(headers: Header[], name: string): boolean

Returns whether headers includes one named name, compared without regard to case.

Logging

console.log(...values), console.warn(...values), console.error(...values)

console.log(...values: any[]): void

Writes the values to the generator's console, strings as they are and other values as JSON. The Preview panel shows the output above the code. For details, see generate.

See Also