AssemblyScript SDK
@codetje/assemblyscript is for writing modules in AssemblyScript, a TypeScript-like language that compiles to WebAssembly. The console's editor uses it to build in your browser, and codetje-as build does the same from the command line. Both give identical bytes.
A module is a directory whose code is in assembly/index.ts. See Getting started to set one up.
Handlers
import { Request, Response, JSON, fetch, env, println, asString } from "@codetje/assemblyscript";
export function handle(req: Request): Response {
if (req.path == "/hello") {
const name = req.param("name");
return Response.text("Hello, " + (name !== null ? name : "world") + "!\n");
}
const api = env("API_URL");
if (api === null) return Response.text("API_URL isn't set\n", 500);
const upstream = fetch(api + "/status");
if (upstream.error !== null) return Response.text("upstream failed: " + upstream.error! + "\n", 502);
println("status " + upstream.status.toString()); // goes to the package's logs
const status = upstream.json<JSON.Obj>();
if (status === null) return Response.text("upstream didn't send a JSON object\n", 502);
const state = asString(status.get("state"));
return Response.text(state !== null ? state + "\n" : "unknown\n");
}
handle(req: Request): Response, exported fromassembly/index.ts, makes the module an HTTP handler.- Any other function exported from
index.tsorexports.tsis for other packages to call. See Calling other packages.
API
Requesthasmethod,url(path and query),path,query,headers,param(name)(a decoded query parameter, or null),bytes(),text()andjson<T>().Responsetakes(status, body). It hasheaders, and the constructorsResponse.text,html,jsonandredirect.Response.jsontakes JSON text, such as the result ofJSON.stringify, andResponse.htmltakes a string orHtml(see HTML). Responses fromfetchalso haveok,text()andjson<T>().Headershasget,has,set,appendanddelete. Names compare case-insensitively.fetch(url, init?)sends a request and waits for the whole response.FetchInitholdsmethod,headersandbody. AssemblyScript has no exceptions, so a failure returns status 0 and setserror, for example tohttp-request-deniedwhen the origin isn't in the package's settings.env(name)andenvVars()read the package's environment.printlnandeprintlnwrite to the logs. A failedassert, or any other abort, writesabort: <message> at <file>:<line>:<column>to stderr and ends the request with a 500.manifest.json, next toindex.ts, is embedded in the component. See The manifest.
AssemblyScript doesn't support ?? or ?., so nullable values (string | null) need explicit checks.
HTML
Write pages with html templates. Whatever they insert is escaped, unless it's already markup:
import { Html, Request, Response, html, raw } from "@codetje/assemblyscript";
const STYLE = "td { padding: 0 1em }";
function row(name: string, size: f64): Html {
return html`<tr><td><a href="/p/${name}">${name}</a></td><td>${size}</td></tr>`;
}
export function handle(req: Request): Response {
const rows: Html[] = [];
for (let i = 0; i < 3; i++) rows.push(row("pkg<" + i.toString() + ">", 1.5));
const q = req.param("q"); // null inserts nothing
return Response.html(html`<!doctype html>
<style>${raw(STYLE)}</style>
<h1>Results for ${q}</h1>
<table>${rows}</table>`);
}
- A template makes an
Htmlvalue, which goes into another template as is. So helpers that returnHtmlcompose, and the type tells markup from text. - Strings are escaped, and
nullinserts nothing. Numbers and booleans are inserted as text (anf64of 3 as3.0).Html[]is inserted as is, andstring[]is escaped item by item. Anything else fails the build, so convert it first. raw(markup)inserts markup you trust, such as your own stylesheet. Never use it for text from a request, an API or a user.- Escaping makes text safe in element content and in quoted attributes. It doesn't make a URL safe in
href(thinkjavascript:), and nothing inserted into<script>or<style>is safe that way. - AssemblyScript has no closures, so
items.map((i) => html`…${prefix}…`)doesn't compile when the function uses an outside variable. Push to anHtml[]in a loop instead.
JSON
req.json<T>(), res.json<T>() and parseJson<T>(text) return null, rather than aborting, when the text isn't valid JSON, is null, or has the wrong shape at the top level. JSON is re-exported from json-as, and @json classes work without setup.
For data you don't control, use JSON.Obj and the as* accessors. They check every value, so an unexpected response can't crash the request:
const doc = res.json<JSON.Obj>();
if (doc === null) return Response.text("not an object\n", 502);
const items = asArr(doc.get("items")); // null if missing or not an array
if (items === null) return Response.text("no items\n", 502);
for (let i = 0; i < items.length; i++) {
const item = asObj(items[i]); // null if not an object
if (item === null) continue;
const name = asString(item.get("name")); // null if missing or not a string
const size = asNumber(item.get("size"), 0); // the fallback if missing or not a number
}
Don't call .get<T>() on a value without checking it, since it doesn't check the type. Numbers in dynamic values are always f64.
For data whose shape you trust, use a class. It's shorter, and field order, unknown fields and missing fields (which keep their defaults) don't matter:
@json class Pkg { name: string = ""; size: f64 = 0; note: string | null = null; }
const all = res.json<Pkg[]>();
if (all !== null) println(JSON.stringify<Pkg[]>(all));
Only the top level is checked, though. A string field holding null or a number aborts the request, and an i64 field holding 1.5 is silently wrong. So declare anything that can be null as T | null, and numbers from outside as f64.
Files
A module can have files besides code: .md, .css, .html, .js, .json, .txt, .svg, .xml and .csv. In the console's editor, add them with the new-file button. The build puts them into the module, so nothing reads files at run time:
import { Request, Response, html, include, markdown, raw } from "@codetje/assemblyscript";
const STYLE = include("style.css"); // the file's text, as a string
const INTRO = markdown("content/intro.md"); // rendered to HTML by the build
export function handle(req: Request): Response {
return Response.html(html`<!doctype html>
<title>${INTRO.title}</title>
<style>${raw(STYLE)}</style>
${INTRO.html}`);
}
- Paths are string literals, relative to the file making the call. A missing file fails the build.
markdowngives youtitle(the text of the first#heading),summary(the first paragraph, for a description),html, andheadings(each withlevel,idandhtml) for a table of contents. It's GitHub-flavoured Markdown, and headings get ids.- Links between pages are checked. Link to another Markdown file, like
[Tags](publishing.md#tags), and the build checks that the file and the heading exist, then turns the link into one to its page,publishing#tags. So serve each page at its file's path without.md(index.mdat its directory). A broken link fails the build. - HTML inside Markdown is kept as is, since the file is yours.
These docs are built this way: they're a module of Markdown files, and you can open their source in the console.
Memory
Nothing is freed during a request, which is fine because the instance is thrown away afterwards. But it means memory grows with everything you allocate, up to the limit.
The thing to avoid is += on a string in a loop: it keeps every intermediate string, so memory grows with the square of the length. Push to an array and join it, or push to an Html[], which a template joins once.
Verifiable builds
The same sources and SDK version always build the same bytes, in Node or in a browser. codetje-as build writes <out>.source.json next to the module, and rt publish --source stores it with the version. The registry never compiles anything, so stored source is a claim until someone rebuilds it and compares the digest, which a browser can do. Stored source is as readable as the package, so keep secrets in settings, not in code.
Limitations
- Bodies are buffered in both directions, with no streaming, and
fetchhas no timeout option. - Handlers can only return a
Response, not awasi:httperror. - Between packages,
char, tuples, variants, enums, flags and resources aren't supported yet.