Skip to content

Extending the preprocessor ​

If the built-in functions and filters are not enough, you can add your own template functions in JavaScript, for example for custom hashing or formatting.

Adding helpers ​

Put .js files into a _tera/ directory in your app:

text
my-app/
├── app.yml.jinja
├── metadata.yml
├── store-metadata.yml
└── _tera/
    └── helpers.js

All .js files in _tera/ are evaluated before a template of the app is rendered. They can register:

  • Template functions with registerTeraHandler(name, fn). fn receives one object with the named arguments of the call and returns any JSON-compatible value, or a promise for one.
  • A postprocessor with registerPostprocessor(fn). fn receives the file name and the rendered output, and must return the final content as a string. Only one postprocessor can be registered.
js
// _tera/helpers.js
registerTeraHandler("first32", (args) => {
  if (typeof args?.str !== "string") {
    return "";
  }
  return args.str.slice(0, 32);
});

registerPostprocessor((fileName, content) => {
  return content.trimEnd() + "\n";
});
yaml
# app.yml.jinja
environment:
  SHORT_KEY: "{{ first32(str=derive_entropy(identifier='key')) }}"

Runtime ​

Helpers run in Boa, a JavaScript engine embedded in n5i, without file system or network access. The built-in objects of the language are available, plus:

  • console.log, console.warn, console.error, which write to n5i's logs
  • crypto.getRandomValues() and crypto.randomUUID()
  • TextEncoder and TextDecoder
  • URL
  • setTimeout and structuredClone

import is not supported, so bundle any libraries into the file. Each call must finish within 2 seconds.

Random values differ on every render. For values that must stay the same, such as passwords, use derive_entropy.

Free and open-source software under the GNU AGPL 3.0 or later.