# `Alternera.PluginWasmFramework.Language`
[🔗](https://github.com/10e-ab/alternera-wasm/blob/v0.9.0/alternera_plugin_wasm_framework/lib/alternera/plugin_wasm_framework/language.ex#L1)

What every language step shares, the way `PluginHosts.Step` is shared by
the plugin hosts' steps: a language plugin holds a `%Language{}` naming
itself and its module, and delegates its callbacks here.

    def language do
      %Language{
        plugin: __MODULE__,
        name: "JavaScript",
        module_path: Application.app_dir(:alternera_plugin_javascript, "priv/javascript.wasm"),
        editor_mode: "javascript",
        starter: %{request: "return req.body", response: "return res.body"},
        editor: Alternera.Plugins.Javascript.Editor,
        help: &Alternera.Plugins.Javascript.Editor.help/1,
        format_worker: "/assets/js/js_format_worker.js",
        body_factor: 12
      }
    end

    def init(settings), do: Language.init(language(), settings)
    def load(settings), do: Language.load_step(language(), settings)
    def call(inputs, opts, context), do: Language.call(language(), inputs, opts, context)
    def editor, do: Alternera.Plugins.Javascript.Editor

`language/0` builds the struct per call rather than holding it in a
module attribute, so `module_path` is the installation's path, not the
build machine's.

The plugin declares `directional: true, stoppable: true, run_in_task:
true, body_handles: true` and no `streams:`. It also implements
`Plugin.Provisional.Editing`: `initial_settings(side)` from
`initial_settings/2` here, so a step just added starts from the
language's starter, and `configuration_toggle?/0` true, since the
editor draws a Configuration toggle.

Its editor is a LiveComponent of its own that hands the language and
its callbacks to the shared `PluginWasmFramework.StepEditor`:

    defmodule Alternera.Plugins.Javascript.Editor do
      use Phoenix.LiveComponent

      alias Alternera.Plugins.Javascript
      alias Alternera.PluginWasmFramework.StepEditor

      @impl true
      def update(assigns, socket),
        do: StepEditor.update(Javascript.language(), assigns, socket)

      @impl true
      def handle_event(event, params, socket),
        do: StepEditor.handle_event(Javascript.language(), event, params, socket)

      @impl true
      def handle_async(name, result, socket),
        do: StepEditor.handle_async(Javascript.language(), name, result, socket)

      @impl true
      def render(assigns), do: StepEditor.render(Javascript.language(), assigns)

      # What the Help disclosure shows; `direction` and `prefix` given.
      def help(assigns), do: ~H"<p>The script reads req and, on the response, res.</p>"
    end

## Settings

Close to Script's, so what a user knows carries over:

  * `direction`: `request` or `response` (`answer` in an Implementation
    of own steps, as Script);
  * `source`: the script, at most 64 KiB of UTF-8, checked on save by
    the module's `alternera_check` (a syntax error refuses the save with
    its line); blank, the step does nothing;
  * `target`, or the To list `targets` (`Plugin.Targets`): where the
    returned value goes (the direction's whole body when neither is
    given; a body target is a whole body, never a path in it), and
    `outputs` rows, each a name the script sets in `outputs`;
  * `reads_body`: whether the step holds its direction's body for the
    script. Script works this out from its Lua text; a language step
    declares it. On by default, since a body transform is the common
    case; off, the step runs on the head and holds no body (unless its
    target is its own whole body, which it then replaces without having
    read it);
  * `memory_limit`: `PluginWasmFramework.MemoryLimit`.

A step's time limit is not a setting here, as it is not in Script: the
call runs within the step's time left (`time_left_ms`).

## What the script gets

The request frame's env (`PluginWasmFramework.Frame`): `req` (headers
with lower-case names, query, content type, the request facts a
template reads, `path_params`), in a response step `res` (headers,
content type, status), `vars`, `steps`, `input`, `context`, `err` in a
catch or On error, `own` (`req` or `res`), and `mode`: `string` when the
target takes a string (a body, a header, a query parameter), `value`
when it takes any JSON value (a variable). Each message has
`body_size`, nil when the step holds no body of it; the script reads a
held body through `body_read`. A response step does not hold the
request body.

## Results, as `Plugins.Script` maps them

  * a returned value goes to the target: a string for a string target
    (any other JSON value there is `invalid_result`), any JSON value
    for a variable; returning the whole body unchanged writes nothing;
  * nothing returned leaves the target as it was (`{:skip,
    :no_result}`);
  * a content type with a whole body sets the message's
    `Content-Type`; with any other target it is ignored;
  * `outputs` are the step's `outputs` output, written by its To rows;
    what it returned is its `body` output;
  * `fail(type, message, status)` is that error, on purpose;
  * a script error is `script_error` with its line (`line N: …`);
  * a trap is `script_error`, `timeout` past the time left, and a
    refused allocation (whatever the script did with it) is
    `memory_limit`, naming the setting that applied;
  * an unusable result is `invalid_result`;
  * a host call's failure the script did not handle fails the step
    with its type (`store_*`, `unresolved_variable`, a called
    pipeline's).

After a read from a store marked secret the step marks every place it
wrote as secret and scrubs its failures (`HostCalls`, `Plugin.Provisional.SecretReads`),
as Script does. The guest's memory at the end of the call is the
step's summary `memory` ("3 of 4 MiB").

## A module uploaded into the step

A language with `step_module?: true` runs no shipped interpreter: the
user uploads a compiled module into the step (`PluginWasmFramework.Upload`,
stored through `Plugin.Provisional.Files`), and the step's settings pin
it by digest:

  * `module`: `%{"digest" => "sha256:<hex>", "name" => "transform.wasm"}`;
    the digest alone decides which file runs, the name is the step's
    label for it;
  * `bindings`: for each kind (`stores`, `pipelines`, `variables`,
    `secrets`), the module's declared parameter names to the tenant's
    real names (`PluginWasmFramework.Uses`); a save refuses a declared
    parameter left unbound;
  * `source` is the step's configuration text, handed to the module as
    the request frame's source and checked on save by its
    `alternera_check`; empty is an empty text, not "do nothing".

A run checks first that the step's tenant stored the file
(`Files.info/3`, remembered per node), so a step never runs a digest
only another tenant uploaded, though the compiled module is shared by
digest (`UploadedModules`). On a miss the module compiles before the
call, one compile at a time on the node, waiting at most
the step's time left less a margin, and at most
`UploadedModules.compile_wait_ms/0` (then `module_not_ready`); the
wait comes out of the time the run then has. Host calls go through the
module's declaration and the step's bindings (`Uses.translate/3`).
`init/1` has no tenant: it checks the configuration and the bindings
against the file found by digest alone (`Files.any_bytes/2`); that the
tenant stored it is checked by the application when the pipeline is
saved (`pinned_files/1`).

## Memory and the held-bytes budget

Before the call the step claims what it brings into the call against
the application's held-bytes budget (`Plugin.Host.claim_held_bytes/2`,
one byte per byte: the request frame and the body it holds) and gives
it back after. The guest's own memory is not claimed: it is bounded per
call by the memory limit and the node's ceiling, and claiming the whole
limit for every call would refuse steps under load that use a fraction
of it. A refused claim fails the step as the application's own refusals
do (`Plugin.Host.claim_refusal/2`).

# `t`

```elixir
@type t() :: %Alternera.PluginWasmFramework.Language{
  body_factor: pos_integer(),
  editor: Alternera.Plugin.editor(),
  editor_mode: String.t(),
  format_worker: String.t() | nil,
  help: (map() -&gt; Phoenix.LiveView.Rendered.t()) | nil,
  module_path: Path.t() | nil,
  name: String.t(),
  plugin: module(),
  starter: %{request: String.t(), response: String.t()},
  step_module?: boolean()
}
```

A language: its plugin module, the name a user sees ("JavaScript"),
the path of its built `.wasm`, the starter source for each side and
the step editor (its own LiveComponent over `StepEditor`). For that
editor:

  * `editor_mode`: the `data-language` the proxy's code editor gets,
    a language the plugin registers in the code editor ("javascript");
    one it does not know is plain text;
  * `help`: a function component (`&Mod.help/1`) shown under the
    editor's Help disclosure, given the assigns `direction`
    (`"request"`, `"response"` or `"answer"`) and `prefix`; nil, no
    Help disclosure;
  * `format_worker`: the static path of the Web Worker the Format
    button formats the source with (`"/assets/js/js_format_worker.js"`);
    nil, no Format button;
  * `step_module?`: true for a step whose module the user uploads into
    the step (`module_path` nil): see "A module uploaded into the step";
  * `body_factor`: the multiple of the body a Body × memory limit
    starts at, and takes when a setting names none: about what the
    interpreter needs for a JSON body it decodes and encodes again
    (`MemoryLimit`); 8 unless the language says otherwise.

# `bound_pipelines`

```elixir
@spec bound_pipelines(map()) :: [String.t()]
```

For a module uploaded into the step: the pipelines its bindings name,
the only ones it can call, so the flow draws them and a cycle check
sees them. A renamed pipeline is not renamed in the bindings: the
binding then names a pipeline that no longer exists, and the call
answers `not_found` until the step is bound again.

# `bound_stores`

```elixir
@spec bound_stores(map()) :: {[String.t()], [String.t()]}
```

For a module uploaded into the step: the named stores its bindings
name, as `{reads, writes}` (`Plugin.Provisional.Analysis.stores/1`).
The operations a module declares on a store are in the module, not in
the settings, so every bound store counts as read and written.

# `call`

```elixir
@spec call(t(), Alternera.Plugin.Inputs.t(), map(), map()) :: term()
```

Runs the step once (`Alternera.Plugin.call/3`). `context` may carry
`:runtime_limits` (`%{timeout_ms:, memory_bytes:}`) to replace the
call's limits, for a test.

# `check`

```elixir
@spec check(t(), String.t()) :: :ok | {:error, [String.t()]}
```

Compiles `source` without running it (the module's `alternera_check`):
`:ok`, or the problems as `"line N: message"`.

# `check_with`

```elixir
@spec check_with(t(), Alternera.PluginWasmFramework.Modules.t(), String.t()) ::
  :ok | {:error, [String.t()]}
```

As `check/2`, with the module given: a module uploaded into a step
(`UploadedModules`) checks its configuration this way.

# `describe`

```elixir
@spec describe(t(), term()) :: String.t()
```

`Response: JavaScript, 12 lines`.

# `init`

```elixir
@spec init(t(), term()) :: {:ok, map()} | {:error, [String.t()]}
```

Checks a step's settings and prepares them (`Alternera.Plugin.init/1`),
the source compiled by the module's `alternera_check`.

# `initial_settings`

```elixir
@spec initial_settings(t(), :request | :response) :: map()
```

The settings a new step starts with on `side`: the language's starter.

# `load`

```elixir
@spec load(t()) ::
  {:ok, Alternera.PluginWasmFramework.Modules.t()} | {:error, String.t()}
```

Compiles the language's module once on this node (`Modules.load/2`):
call it from the plugin package's application `start/2`, so the first
request does not wait 150 to 500 ms for it.

# `load_step`

```elixir
@spec load_step(t(), term()) :: {:ok, map(), [String.t()]} | {:error, [String.t()]}
```

Prepares saved settings for a run (`Alternera.Plugin.load/1`) as
`init/2` does, without compiling the source again: it was checked when
it was saved, and a load prepares every step of a tenant's pipelines.
A source that no longer compiles fails its runs as a `script_error`.

# `max_source_bytes`

```elixir
@spec max_source_bytes() :: pos_integer()
```

The largest source a step takes, in bytes.

# `outputs`

```elixir
@spec outputs() :: [Alternera.Plugin.output()]
```

What a step produces: the returned value (`body`) and the named `outputs`.

# `pinned_files`

```elixir
@spec pinned_files(map()) :: [Alternera.Plugin.Provisional.Files.pinned()]
```

The stored files a step's settings pin
(`Plugin.Provisional.Files.pinned_files/1`): its module's, with the
step's name for it.

# `pipelines_called`

```elixir
@spec pipelines_called(map()) :: [String.t()]
```

`[]`: a script may call any pipeline by a name built at run time, and
the proxy cannot read the calls out of a source it does not parse. A
list, even empty, says the step calls with inputs the proxy cannot see
(`Plugin.Provisional.Analysis.pipelines_called/1`): no pipeline's input
is reported as never passed, and no pipeline counts as uncalled because
of it. Callees are found by name when the call runs, and a release
holds every pipeline of the tenant, so nothing needs the names ahead.
The cost: the flow draws no edge to a callee, and a renamed pipeline is
not renamed in the source.

# `produces_response?`

```elixir
@spec produces_response?(map()) :: boolean()
```

As Script: a step that names no place, or whose To rows write the response, makes one.

# `raises`

```elixir
@spec raises(t(), map()) :: [String.t() | :others]
```

The errors a step may fail with (`Alternera.Plugin.raises/1`): the
limits', a script error, and `:others`, since the types a script's
`fail` names cannot be read from a source the proxy does not parse.

# `rename_bound`

```elixir
@spec rename_bound(map(), atom() | tuple(), String.t(), String.t()) ::
  {:ok, map()} | :unknown
```

For a module uploaded into the step: `settings` with every store
binding that names `old` naming `new` (`Plugin.Provisional.Analysis.rename/4`).
A store is the only name of the proxy's the bindings hold that
`stores/1` reports, so any other kind is `:unknown`.

# `settings_schema`

```elixir
@spec settings_schema(t()) :: [Alternera.Plugin.schema_field()]
```

The settings schema (`Alternera.Plugin.settings_schema/0`).

# `signature`

```elixir
@spec signature(map(), Alternera.Plugin.Signature.t()) ::
  Alternera.Plugin.Signature.t()
```

The step's signature (`Alternera.Plugin.signature/2`). Nothing can
be read from a source the proxy does not parse, so the step reads the
whole exchange (`reads_any`: the variables and step outputs as parts),
may read the tenant's variables by any name and hand on a secret's
reference. Its own body is read when `reads_body` is on or its target
is that whole body; with a whole-body target the step writes it and its
`Content-Type`.

# `signature`

```elixir
@spec signature(t() | nil, map(), Alternera.Plugin.Signature.t()) ::
  Alternera.Plugin.Signature.t()
```

As `signature/2`, for `lang`: a module uploaded into the step reads the
tenant variables and secrets its bindings name and no others, so they
are its templates (a save checks them, a release lists them), and it
reads the tenant's variables only when it binds one.

# `tenant_vars_unseen?`

```elixir
@spec tenant_vars_unseen?(map()) :: boolean()
```

True: a script may read a tenant variable by a name built at run time.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
