Skip to content

TypeScript

@flowcatalyst/fn is the TypeScript and JavaScript guest SDK for functions. It has no runtime dependencies. Unlike the Go and Rust SDKs, a JavaScript function does not compile to WebAssembly: the artifact is one bundled script that the function runner runs on a shared QuickJS engine (clients/fn-js-engine, compiled once per runner). A JS function therefore costs only its own instances; the engine is not shipped inside every function.

The same contract is implemented by the Go, Rust and Java SDKs. Functions are first-party code (decision); the choice of engines is explained in one contract, several engines and the call deadline behaviour in JavaScript deadlines.

The package ships TypeScript source (main and types are src/index.ts) and the fc-fn-build bundler. It is released as tags fn-ts-sdk/vX.Y.Z in the platform repository (the current release is v0.7.0), and the release process splits it to the standalone repository flowcatalyst/fn-ts-sdk with plain vX.Y.Z tags. The package is marked private, so it is not on npm. Install it from the git tag:

Terminal window
npm install github:flowcatalyst/fn-ts-sdk#v0.7.0
npm install --save-dev esbuild typescript

fcdev fn init scaffolds a TypeScript project; its default template names an npm version (^0.1.0) that is not published, so pass --sdk-path with a checkout of the SDKs (it writes a file: dependency) until the split repository is in use.

Register endpoints at module top level, with the fn namespace. The module’s import has a side effect: it installs globalThis.__fc = { describe, handle }, which is the engine’s binding.

import { fn, FnError, isRetryable, type FnRequest } from "@flowcatalyst/fn";
const greeting = fn.config("GREETING");
fn.open("GET /healthz", () => fn.json(200, { status: "ok" }));
fn.platform("GET /hello/{name}", (req: FnRequest) =>
fn.json(200, {
message: `${greeting.get() ?? "Hello"}, ${req.params.name}`,
caller: req.caller.principal?.id,
}),
);
fn.webhook("POST /events/greeting", async (req: FnRequest) => {
const inbound = req.json() as { id?: string };
try {
await fn.emit({
type: "hello:greeting:greeting:sent",
dedupId: `greeting-sent-${inbound.id ?? req.invocation.id}`,
data: { ok: true },
});
return fn.status(202);
} catch (err) {
if (isRetryable(err)) return fn.retry(5);
return fn.reject("emit refused");
}
});
fn.emits("hello:greeting:greeting:sent");

A handler receives an FnRequest and returns a response (or a promise of one). Returning nothing means 200. A handler that throws or rejects becomes 500 {"error":"FUNCTION_PANIC"}, logged through the host.

Terminal window
node node_modules/@flowcatalyst/fn/bin/fc-fn-build.js src/index.ts --outfile dist/function.js

fc-fn-build runs esbuild with --bundle --format=iife --platform=neutral --target=es2020 and the default output dist/function.js. The hello example bundles to about 27 KB. Dependencies must be pure JavaScript that does not need browser or Node globals (see the environment below).

Call Declares
fn.webhook(pattern, handler, opts?) Webhook endpoint (signed delivery); POST only, any other method throws
fn.platform(pattern, handler, opts?) Endpoint needing a verified platform token
fn.open(pattern, handler, opts?) Unauthenticated endpoint
fn.subscribe(eventType, path, opts?) Deliveries of an event type go to the webhook at path. opts: mode, maxRetries, dataOnly, timeoutSeconds
fn.schedule(cron, path, opts?) Six-field cron (seconds first) firing at the webhook at path. opts: timezone, payload
fn.config(key), fn.secret(key), fn.db(name) Config key, secret key, database binding
fn.httpAllow(...hosts) Hosts fn.fetch may reach
fn.emits(...types) Event types the function may emit
fn.dispatches(target, path, { connection, pool? }) A dispatch target. connection is required (the call throws without it)
fn.usesPlatformToken() Permission to fetch a platform access token
fn.traceContexts({ name, description? }, ...) Named trace contexts

Endpoint options are { timeoutMs, maxBodyBytes, cors: { origins, methods, headers, allowCredentials } }. Patterns are "METHOD /path/{name}" with a trailing {rest...} allowed. The SDK does its own routing (literal beats {name} beats {rest...}, then longer beats shorter, then registration order), answers 404 or 405 with Allow, and lets a GET registration answer HEAD without a body.

FnRequest has id, method, path, query (an FnQuery), headers (an FnHeaders, case insensitive get, getAll, has), params, body (Uint8Array), text(), json(), caller and invocation (id, address, version, deadline). caller.kind is "webhook", "principal" or "anonymous", and caller.principal is a Principal with the same fields and checks as the Go SDK (hasPermission with wildcard matching, isAnchor, hasRole, canAccessClient, canAccessClientCode, canAccessApplication, canAccessApplicationCode). The request also carries the trace helpers req.trace, req.tracing and req.setReference.

Call Response
fn.json(status, value) JSON body with Content-Type: application/json
fn.text(status, s) Plain text
fn.status(code) Status only
fn.retry(seconds) 429 with Retry-After: try again later without spending an attempt
fn.reject(reason?) 422 with FlowCatalyst-Outcome: reject: give up now (reason is a plain-text body)

A handler may also return { status, headers?, body? }. A string body is sent as is, an object or array is JSON-encoded (and gets application/json unless set), a Uint8Array passes through. See delivery for how a delivery treats each answer.

config().get() and secret().get() are synchronous and return string | undefined. Everything that does I/O is async.

const main = fn.db("main"); // declare at module top level
const rows = await main.query("SELECT id FROM people WHERE name = ?", ["Aroha"]);
await main.transaction(async (tx) => {
await tx.exec("UPDATE people SET seen = ? WHERE id = ?", [new Date(), 7]);
});
  • fn.fetch(url, { method, headers, body, timeoutMs }) returns an FnResponse with status, headers, text(), json() and bytes(). It is fully buffered, reaches only declared hosts and is not the web fetch.
  • fn.emit({ type, source?, subject?, dedupId?, correlationId?, causationId?, messageGroup?, contentType?, data? }) returns the event id. data may be a string, bytes or an object. Derive dedupId from the input so a redelivery emits once.
  • fn.dispatch({ target, path, payload?, metadata?, messageGroup?, mode?, ... }) returns the job id. Declare the target first: fn.dispatches("hello.logger", "/deliver", { connection: "hello-conn" }). The connection and pool belong to the declaration. It is not de-duplicated. See Create a dispatch job from a function.
  • db(name) gives query, exec and transaction(fn); Uint8Array parameters are base64-encoded and Date parameters use toISOString(). The transaction commits when the callback resolves and rolls back if it throws.
  • fn.platformToken({ refresh? }) returns the access token of the application’s linked service account; the host caches it. Never log it (Call another service with a platform token).
  • fn.log.debug/info/warn/error(msg, attrs?); console.* is routed to the same host op.
  • Trace logs (a no-op unless an operator switches a context on; none can throw): req.trace("orders", "mapped", { lines: 3 }, { level: "debug" }), req.tracing("orders"), req.setReference(orderNo) (Switch on trace logs).

Host failures are FnError with code, message and retryable. isRetryable(err) is true only for UNAVAILABLE. Codes are the same across SDKs (NOT_DECLARED, NOT_ALLOWED, DEADLINE, TOO_LARGE, BAD_REQUEST, DB_*, UNKNOWN_OP), and every code but UNAVAILABLE is final, so return fn.reject(...) rather than fn.retry(...).

Code runs on QuickJS with an ES2020 language and library floor, which is smaller than a browser or Node. Per the stability contract:

  • Guaranteed: ES2020 built-ins (including Promise, async/await, Map, Set, BigInt, typed arrays), console.*, and the SDK itself.
  • Best effort: Date.now(), Math.random() (not for security), Intl and ES2021+ library features.
  • Not provided: global fetch, Request, URL, URLSearchParams, TextEncoder, crypto, setTimeout, Buffer, process, require, workers. There is no way to sleep, and a promise that never settles ends in a 500. Bundle any hashing you need as pure JavaScript.

Heap growth is bounded by the function’s memory setting, and exhausting it ends the call.

Handlers run on plain Node against a fake host. The SDK’s own tests use src/testing.ts (installFakeHost(handler?), which returns { calls, restore }, and resetRegistry()), driving the engine binding the way the runner does. It is not exported from the package entry, so import it from the repository by relative path (or copy the pattern):

import { installFakeHost, resetRegistry } from "./testing";
import "./index"; // your registrations
const host = installFakeHost((op, meta) => ({ code: 0, meta: {} }));
const out = await (globalThis as any).__fc.handle(
JSON.stringify({
id: "inv_1", address: "app.fn", version: 1, method: "GET", path: "/healthz",
rawQuery: "", headers: {}, caller: { kind: "anonymous" }, deadlineUnixMs: Date.now() + 5000,
}),
new Uint8Array(),
);
// out.meta is a JSON string with status and headers; out.body holds the bytes.
host.restore();

FakeHostHandler receives (op, meta, body) and returns { code, meta, body? }; the recorded calls list every host operation. There is not yet a high-level invoke helper like the Go and Rust SDKs have.

To run against the real runner without a platform, use fcdev fn dev (Develop locally); for signing and real delivery, fcdev fn deploy to a non-production platform.

Per-function defaults are 64 MB memory, 16 concurrent calls, 30 s timeout and a 1 MiB request body (Functions). The engine sets a 512 KiB native stack limit. The protocol is in the describe reference.