Code Generator API

generate

The function that turns a request into code.

Declaration

function generate(req: ExportRequest, r: relay): string

Overview

Every generator defines a top-level function named generate. Relay calls it each time the Preview panel needs code for a request: when you select the request or the generator, after you pause typing, and when you copy or save the preview. An AI agent's generate_code tool calls it the same way.

var manifest = { id: 'httpie-short', name: 'HTTPie (Short)', group: 'Shell', language: 'shell', fileExtension: 'sh', order: 13 };

function generate(req, r) {
  var b = r.builder(' \\\n  ');
  b.add('http ' + req.method + ' ' + r.q.shell(req.url));
  r.allHeaders(req).forEach(function (header) {
    b.add(r.q.shell(header.name + ':' + header.value));
  });
  if (req.body.type !== 'none' && req.body.type !== 'multipart') {
    b.add('--raw ' + r.q.shell(req.body.text));
  }
  return b.join();
}

Parameters

Prop

Type

Return Value

The generated code as a string. Relay shows it in the Preview panel exactly as returned, highlighted as the manifest's language.

Discussion

Errors

When generate throws, or returns something other than a string, the Preview panel says the generator could not generate this request and shows the error message, with its line number when there is one. A generator that runs for more than two seconds is stopped and the panel shows Script timed out. Relay doesn't run that generator again until its source changes.

To explain something the code can't express, prefer a comment in the generated code, or a console.warn, to throwing.

Console

console.log, console.warn and console.error take any number of values. Strings are written as they are and other values as JSON. Relay shows each call's output above the code as a line starting with //, with warning: or error: before messages from console.warn and console.error. An AI agent's generate_code tool returns them separately from the code, as logs.

Sandbox

Generators run in JavaScriptCore with nothing added but the relay helpers and console. They have the standard built-ins, such as JSON, Math, Date, RegExp, String and Array, and no fetch, XMLHttpRequest, require, setTimeout, btoa or file system access. Use relay.base64 for base64 and relay.byteLength for UTF-8 lengths.

A generator can't change the request or anything else in Relay. Relay may keep a generator's top-level variables between calls, so compute everything from req on each call rather than storing state.

Request kinds

Relay calls generate only with requests of the manifest's kind. A WebSocket generator receives requests whose kind is 'websocket', with webSocket set.

See Also

  • ExportRequest: The resolved request a generator turns into code.
  • relay: The helper functions for building, quoting and encoding generated code.
  • manifest: The object that names a generator and says which requests it exports.