Creating Effects
Most of your VibeLang code is just effect function declarations: return to succeed, throw for an expected failure, try to run another Effect. When you cross out to JavaScript libraries, Promises, or callback APIs, Effect gives you four crisp bridges.
1. Domain logic: return and throw
Start with an effect function whenever code can fail with a domain error, needs a service, or runs other Effects:
error Unavailable {
item: string
}
effect function reserve(item: string, available: boolean) {
if (!available) throw new Unavailable({ item })
return { item, reserved: true }
}
// Inferred: { item: string; reserved: boolean }!Unavailable
// Run in an effect function: try Console.log((try reserve("notebook", true)).item)
// Output: notebookreturnsets the success channelA.throw new Unavailable({ item })sets the error channelE(equivalent totry fail(...)).- Calling
reserve("notebook", true)builds a cold Effect without running the body;try reserve(...)runs it.
You can also use effect on arrows (effect (x: number) => ...), class or object methods (effect save() { ... }), and inline blocks (effect { ... }). Getters, setters, and class constructors cannot be effect (EK0104) — use an effect method or return an effect { ... } value instead.
Capturing an error as a value (Effect.result)
If you want to inspect a failure as ordinary data instead of jumping to catch, wrap the Effect in result(...):
effect function attemptReservation(item: string, available: boolean) {
const outcome = try result(reserve(item, available))
if (Result.isFailure(outcome)) return outcome.failure.item
return outcome.success.item
}
// Inferred: string!!
// Run in an effect function: try Console.log(try attemptReservation("notebook", false))
// Output: notebookresult moves expected errors from E into a Result<A, E> value while letting defects and interruption propagate untouched.
2. Which bridge do you need?
When calling code outside VibeLang, pick the bridge that matches what the callee does:
| What you are calling | Use in VibeLang |
|---|---|
Pure computation that cannot throw (slug, Math.max) | Call it directly — no wrapper needed |
| Built-in platform capability (files, crypto, HTTP, console) | Effect's service (FileSystem, SecureRandom, HttpClient, Console) |
Synchronous .ts/JS function that may throw (JSON.parse, statfsSync) | try Effect.try({ try: () => ..., catch: (cause) => new MyError({ cause }) }) |
Promise-returning .ts/JS function (fetchTodo, SDK calls) | try tryPromise({ try: (signal) => ..., catch: (cause) => new MyError({ cause }) }) |
| Event / callback API with cancellation | try callback<A, E>((resume) => { ...; return sync(cancel) }) |
Pure helpers need no effect modifier and no wrapper:
function slug(title: string) {
let s = title.trim().toLowerCase()
s = s.replaceAll(/[^a-z0-9]+/g, "-")
return s
}
// Run in an effect function: try Console.log(slug("Hello VibeLang"))
// Output: hello-vibelang3. Platform capabilities use services, not globals
A .vibe file cannot import node:* modules or call host globals like process or crypto.getRandomValues directly (EK4402). Instead, ask for Effect's typed service and supply the platform layer once at main:
import * as NodeCrypto from "@effect/platform-node/NodeCrypto"
effect function token() {
const random = try SecureRandom.SecureRandom
return try random.randomBytes(16)
}
// Run in an effect function: provide NodeCrypto.layer { try Console.log((try token()).length) }
// Output: 16This keeps your business logic portable across Node, Bun, Cloudflare Workers, browsers, and tests. See Platform globals for every Node/web replacement, and Experimental platform APIs for extras beyond Effect core.
4. Bridging synchronous code that may throw (Effect.try)
A plain .vibe function never throws (EK0401). For foreign .ts and JS functions, the compiler tracks thrown types via @throws:
- Built-ins known not to throw (like
Math.max) can be called directly. - Functions that may throw — including
JSON.parseand any unannotated.tsfunction (assumed@throws {unknown}) — must be wrapped inEffect.tryinside effect code (EK0403). - For synchronous invocation of a
.tsfunction,@rethrows faddsf's thrown type to the call's thrown contract. Anasyncfunction'sthrowrejects its Promise.
When an API is not covered by Effect's services (like node:fs's statfsSync), keep the Node import in a tiny .ts adapter and wrap it with Effect.try:
// platform-fs.ts
// types: node
export { statfsSync } from "node:fs"import { statfsSync } from "./platform-fs.js"
error StatFailed {
cause: unknown
}
effect function freeBlocks(path: string) {
return try Effect.try({
try: () => statfsSync(path).bavail,
catch: (cause) => new StatFailed({ cause })
})
}
// Inferred: number!StatFailed
// Run in an effect function: try Console.log((try freeBlocks(".")) > 0)
// Output: trueWait — what is the difference between
syncandEffect.try?sync(() => expr)defers a computation that cannot throw. If an expression might throw a JavaScript exception, useEffect.try(...)(ororDie(Effect.try(...))if a throw is an unrecoverable bug).
5. Bridging Promises (tryPromise)
Put async SDK or Web Crypto calls in a .ts module and wrap them with tryPromise:
// types: node
// signing.ts
export async function hmac(secret: string, text: string): Promise<ArrayBuffer> {
const encoder = new TextEncoder()
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
return await crypto.subtle.sign("HMAC", key, encoder.encode(text))
}import { hmac } from "./signing.ts"
error SigningFailed {
cause: unknown
}
effect function sign(secret: string, text: string) {
return try tryPromise({
try: () => hmac(secret, text),
catch: (cause) => new SigningFailed({ cause })
})
}
// Inferred: ArrayBuffer!SigningFailed
// Run in an effect function: try Console.log((try sign("secret", "parcel")).byteLength)
// Output: 32- Always forward the
AbortSignal(try: (signal) => sdk.get(id, { signal })) when the underlying API supports it, so fiber interruption cancels the in-flight request. - Use
promise(() => ...)only when a rejection represents a defect (bug), never an expected failure. - (For HMAC signing in real apps, prefer Effect's built-in
Macservice; here we use a.tsmodule to illustratetryPromise.)
6. Bridging callback APIs (callback)
For one-shot callback APIs (event emitters, legacy SDKs), callback<A, E> receives a resume function and returns a cleanup Effect that runs if the fiber is interrupted while waiting:
type Source = {
read: (onValue: (n: number) => void, onError: (e: Error) => void) => () => void
}
effect function nextReading(source: Source) {
return try callback<number, Error>((resume) => {
const cancel = source.read(
(n) => resume(succeed(n)),
(error) => resume(fail(error))
)
return sync(cancel)
})
}
effect function readAndReport(source: Source) {
const reading = try nextReading(source)
try Console.log(`reading=${reading}`)
return reading
}
// Run in an effect function: try Console.log(try readAndReport({ read: (onValue: (n: number) => void) => { onValue(7); return () => {} } }))
// Output: reading=7
// Output: 7resume honors the first completion and ignores subsequent calls. If the callback acquires a resource that must be closed even when arriving late, prefer acquireRelease instead (Resource Management).
Write TypeScript in a separate file
When a .ts adapter imports node:*, install Node's type declarations (npm install --save-dev @types/node or bun add --dev @types/node) and set "types": ["node"] in compilerOptions in tsconfig.json (the starter uses "types": []). Keep the node:* import inside the .ts file.
If the TypeScript helper catches all exceptions internally, annotate it with /** @throws {never} */ so VibeLang callers can invoke it directly without Effect.try:
// links.ts
// types: node
import { lstatSync } from "node:fs"
/** @throws {never} */
export function isSymbolicLink(path: string): boolean {
try {
return lstatSync(path).isSymbolicLink()
} catch {
return false
}
}import { isSymbolicLink } from "./links.js"
effect function linked(path: string) {
return try sync(() => isSymbolicLink(path))
}
// Run in an effect function: try Console.log(try linked("."))
// Output: falseBecause isSymbolicLink declares @throws {never}, linked could also call isSymbolicLink(path) directly without sync. (Inside .vibe files themselves, never write @throws or @rethrows — VibeLang functions never throw and emit @throws {never} automatically; writing those tags in .vibe is EK0406.)
Suspend work
An effect { ... } block re-runs its body every time it is executed. Returning an effect { ... } from a function lets you encapsulate per-instance mutable state or defer expensive construction until run time (as Effect.suspend does):
effect function nextCounter() {
let count = 0
return effect {
count += 1
return count
}
}
effect function counters() {
const next = try nextCounter()
return [try next, try next]
}
// Run in an effect function:
// {
// const jsonValue = try counters()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [1,2]And because effect functions run on Effect's fiber trampoline, deep recursion using try is stack-safe:
effect function countdown(n: number): number!! {
if (n <= 0) return 0
try sleep("1 millis")
return 1 + (try countdown(n - 1))
}
effect function checkedQuantity(n: number) {
if (n < 0) throw new Unavailable({ item: "quantity" })
return n
}
// Inferred: number!Unavailable
// Run in an effect function: try Console.log(try countdown(3))
// Output: 3(Plain JavaScript recursion still has JavaScript's call-stack limit.)
Coming from Effect
- Write
effect functionwithreturnandthrowinstead ofEffect.gen+Effect.succeed/Effect.fail. - Keep
sync,Effect.try,tryPromise,promise,callback, andsuspendfor bridging foreign code and lazy construction. - A return annotation on an
effectfunction must be a single Effect type (A!E!R), never bareany/unknownor a union of Effects (EK0106).
Next: Two Types of Errors — learn why some failures belong in E and bugs do not.
The matching Effect page: effect.website/docs/v4/getting-started/creating-effects