Data
Data
Data
data.md

Data

Examplea whole program
shape Post
id: number
title: string
state saved: number[] = []
state note = ""
resource posts: Post[] = net.get("posts.json") else []
action restore
saved = db.get("saved")? ?? []
note = fs.text("notes/last.txt") else ""
action keep(id: number)
if saved.includes(id) return
saved.push(id)
db.set("saved", saved)?
task
restore()
column gap=8 padding=16
for p in posts key=p.id
row gap=8
text p.title flex=1
button (saved.includes(p.id) ? "Kept" : "Keep") press=keep(p.id) disabled=saved.includes(p.id)
text note color=dim

Mental model#

A file read as the program is built#

persist and store#

net#

net.send#

To and from files#

Examplea whole program
// A large file sent in parts of 8 MB, each with its progress (to a service that takes parts).
state f: picked? = none
state sent = 0
state said = ""
action choose
f = fs.pick("*", {read: false})?
action moved(n: number)
sent = n
action upload
if f == none return
let from = 0
while from < f.size
sent = 0
let a = net.send("PUT", `/parts/${from}`, {body: {file: f, from, length: 8000000}, progress: (s, t) => moved(s), timeout: 120000})?
if !a.ok fail(`${a.status}: ${a.text}`)?
from += 8000000
said = `${Math.min(from, f.size)} of ${f.size} bytes sent`
column gap=8 padding=16
button "Choose" press=choose
button "Send" press=upload disabled=(f == none || pending(upload))
text `${said} (this part: ${sent})`

An address a person gave#

net.stream#

Examplea whole program
state prompt = ""
state reply = ""
server fn ask(prompt: string): string requires signedIn
let me = auth.me()?
let s = net.stream("POST", "https://api.example.com/v1/answers", {headers: {authorization: `Bearer ${env("API_KEY")}`}, body: {prompt, stream: true}, timeout: 30000})?
if !s.ok fail(`${s.status}: ${s.rest()?}`)?
let all = ""
while true
let e = s.event()?
if e == none
break
if e.event == "delta"
all += e.data
emitTo(me?.id ?? "", "token", e.data)
return all
on token(piece: string)
reply += piece
action send
reply = ""
ask(prompt)?
column gap=8 padding=16
input value=prompt submit=send
text reply
text (failure(send) ?? "") color=danger

check#

Examplea whole program
shape Amount
value: number
currency: string
shape Charge
id: string
amount: Amount
refunded: bool
note: string?
server fn charges(): Charge[]
let a = net.send("GET", "https://api.pay.example/v1/charges", {timeout: 10000})?
return check(a.json?.data, [Charge])?
action load
let cs = charges() else []
log(cs.length)
button "Load" press=load

db#

Storage that stays#

Examplea whole program
state kept = false
state room = ""
task
kept = db.persisted() else false
let r = db.room() else none
room = r == none ? "" : `${Math.round(r.left / 1048576)} MB left`
action keep
kept = db.persist() else false
action save(photo: bytes)
fs.write("roof.jpg", photo) else err => (err.kind == "full" ? toast("No room left on this phone.") : toast(`${err}`))
column gap=8 padding=16
if !kept
button "Keep my photos on this phone" press=keep
text room color=dim
button "Save" press=save(bytes.new(1000))

sql#

Examplea whole program
shape Row
id: number
name: string
state rows: Row[] = []
state said = ""
action seed
let d = sql.open("shop")?
sql.run(d, "create table if not exists wood(id integer primary key, name text)")?
sql.run(d, "insert into wood(name) values (?)", ["oak"])?
sql.batch(d, [["insert into wood(name) values (?)", ["ash"]], ["update wood set name = upper(name)"]])?
rows = sql.run(d, "select id, name from wood where id > ?", [0])?
let file = sql.bytes(d)?
said = `SQLite ${sql.version()?}, ${file.length} bytes`
column gap=8 padding=16
button "Seed" press=seed
for r in rows key=r.id
text `${r.id}: ${r.name}`
text said color=dim
text (failure(seed) ?? "") color=danger

fs#

The camera#

Files not read yet#

Examplea whole program
state photos: picked[] = []
state notes: string[] = []
action choose
photos = fs.pickMany("image/*", {read: false})?
action small
notes = []
for f in photos
let im = img.decode(f, {fit: 1600}) else err => none
notes.push(im == none ? `${f.name} could not be read` : `${f.name}: ${im.width} by ${im.height}`)
column gap=8 padding=16
button "Choose photos" press=choose
for f in photos
text `${f.name}, ${Math.round(f.size / 1024)} KB`
button "Shrink them" press=small disabled=pending(small)
for n in notes
text n color=dim

Large files#

Examplea whole program
// A mail archive of many gigabytes, a message at a time; where it got to is kept, so a reload
// (or a closed tab) goes on from there once the file is picked again.
state archive: picked? = none
state offset = 0 persist
state count = 0 persist
state said = ""
shape Read
offset: number
count: number
// Messages from where `r` is, each from its "From " line to the next one's, a thousand at most.
fn messages(r: reader, count: number): Read
let n = count
while n < count + 1000
let start = r.at
let next = r.find("\nFrom ")?
let m = r.read(next == none ? 100000000 : next + 1 - start)?
if m == none break
n += 1
return {offset: r.at, count: n}
action choose
archive = fs.pick(".zip", {read: false})?
action more
if archive == none return
let r = zip.open(archive, "Takeout/Mail/All mail.mbox")?
r.seek(offset)?
let got = messages(r, count)?
r.close()
offset = got.offset
count = got.count
said = `${count} messages, ${Math.round(offset / 1000000)} MB in`
column gap=8 padding=16
button "Choose the archive" press=choose
button "A thousand more" press=more disabled=(archive == none || pending(more))
text said

Archives#

Examplea whole program
state said = ""
// Each entry of a .tgz: its name, and the first line of each text file.
action look
let f = fs.pick(".tgz,.tar.gz", {read: false})?
if f == none return
let t = tar.entries(zip.gunzipStream(fs.open(f)?)?)?
let lines: string[] = []
let e = t.next()?
while e != none
if e.kind == "file" && e.name.endsWith(".txt")
lines.push(`${e.name}: ${e.line()? ?? ""}`)
else
lines.push(`${e.name} (${e.kind}, ${e.size ?? 0} bytes)`)
e = t.next()?
t.close()
said = lines.join("\n")
button "Look inside a .tgz" press=look
text said white-space=pre-line

Writing as it is made#

Sealed files#

Examplea whole program
state said = ""
// A file of the device sealed under a key that cannot be read back, and read a line at a time.
action keep
let key = crypto.aes.key(crypto.randomBytes(32))?
let w = fs.writer("notes/today.sealed", {seal: key})?
w.write("first line\n")?
w.write("second line\n")?
w.close()?
let r = fs.open("notes/today.sealed", {seal: key})?
said = `${r.size ?? 0} bytes: ${r.line()? ?? ""}`
r.close()
button "Keep and read" press=keep
text said

What runs where#

Going on after a reload#

clipboard#

Examplea whole program
state names: string[] = []
state said = ""
action many
let files = fs.pickMany("image/*")?
names = files.map(f => f.name)
action folder
let files = fs.pickFolder(".txt,.md")?
names = files.map(f => `${f.path} (${f.data.length})`)
action share
clipboard.put(names.join("\n"))?
said = "copied"
action read
said = clipboard.text() else err => `refused: ${err}`
column gap=8 padding=16
row gap=8
button "Pictures" press=many
button "A folder" press=folder
button "Copy the names" press=share
button "What is on the clipboard?" press=read
for n in names
text n
text said color=dim

share#

Examplea whole program
app "Shop" "Cabinets drawn by you."
state said = ""
action table
said = share({title: "Oak table", text: "Drawn by Ada", url: route.link("/t/7")})
action photo
let f = fs.pick("image/*")?
if f == none return
said = share({files: [f], title: f.name})
column gap=8 padding=16
button "Share" press=share()
button "Share the table" press=table
button "Share a photo" press=photo
text said color=dim

crypto#

Keys of the page's own#

Examplea whole program
state sealed = ""
state opened = ""
// A key from a passphrase, a nonce that is new each time, and the note bound to its id.
fn seal(passphrase: string, id: string, note: string): string
let key = crypto.argon2id(passphrase, "a salt of this user's", {bytes: true})?
let nonce = crypto.randomBytes(12)
let made = crypto.aes.seal(key, nonce, note, {aad: id})?
return bytes.join([nonce, made]).base64()
fn open(passphrase: string, id: string, kept: string): string
let key = crypto.argon2id(passphrase, "a salt of this user's", {bytes: true})?
let all = bytes.base64(kept)?
return crypto.aes.open(key, all.slice(0, 12), all.slice(12), {aad: id})?.text()
action go
sealed = seal("correct horse", "note-1", "the plan")?
opened = open("correct horse", "note-1", sealed)?
button "Seal and open" press=go
text sealed
text `${opened}${failure(go) ?? ""}`

A key that cannot be read back#

A derived key that is never bytes#

Examplea whole program
state said = ""
// A passkey's PRF output (here, 32 bytes for the example) held by the host at once; a key for
// each use derived from it; none of them ever bytes.
action go
let material = crypto.hkdf.key(crypto.randomBytes(32))?
let notes = crypto.hkdf(material, {salt: "app/v1", info: "notes", as: "aes"})?
let nonce = crypto.randomBytes(12)
let sealed = crypto.aes.seal(notes, nonce, "the plan", {aad: "note-1"})?
db.set("material", material)?
said = crypto.aes.open(notes, nonce, sealed, {aad: "note-1"})?.text()
button "Derive and seal" press=go
text `${said}${failure(go) ?? ""}`

Key bytes kept or shown#

Signatures with a key pair#

Examplea whole program
state said = ""
// What a service that signs people in says of someone, as a token (a JWT): taken only
// when one of that service's own keys signed it, and it is for this app, and not over.
server fn whoIs(token: string): string requires anyone limit 20 per minute by ip
let keys = net.get(env("ISSUER_KEYS_URL"))?
let claims = crypto.jwt.verify(token, keys, {iss: env("ISSUER"), aud: env("CLIENT_ID")})?
return `${claims.email ?? claims.sub}`
// A receipt this back end signs, which anyone with its public key can check.
server fn receipt(order: string): string requires signedIn
let signature = crypto.sign(secret("RECEIPT_KEY"), order, {alg: "ES256"})?
return `${order}.${signature.hex()}`
server fn receiptHolds(order: string, signature: string): bool requires anyone
return crypto.verify(env("RECEIPT_PUBLIC_KEY"), order, bytes.hex(signature)?, {alg: "ES256"})?
action ask
said = receipt("order-17")?
button "Receipt" press=ask
text `${said}${failure(ask) ?? ""}`

Certificates read whole, and their chains#

cbor#

xml#

Examplea whole program
state said = ""
action read
let doc = xml.parse("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Contents><Key>a &amp; b.png</Key><Size>12</Size></Contents><IsTruncated>false</IsTruncated></ListBucketResult>")?
let keys = xml.all(doc, "Contents").map(c => `${xml.text(c, "Key")} (${xml.text(c, "Size")} bytes)`)
let made = xml.write(xml.of("Delete", {Object: [{Key: "a"}, {Key: "b"}], Quiet: true}, {xmlns: "http://s3.amazonaws.com/doc/2006-03-01/"})?)
said = `${keys.join(", ")} in ${doc.ns}; ${made}`
button "Read" press=read
text said

zip#

Examplea whole program
model Note
title: string
body: string
read, add anyone
server fn exportNotes(): bytes
let notes = Note.find({}, {order: "title"})?
let files = notes.map(n => ({name: `${n.title}.txt`, data: bytes(n.body)}))
return zip.pack(files)?
// Served as a file: a link to it downloads it.
server route GET "/export.zip"(req)
return {bytes: exportNotes()?, headers: {"content-type": "application/zip", "content-disposition": "attachment; filename=\"notes.zip\""}}
// Or asked for by the page, as bytes, and saved from there.
action save
fs.save("notes.zip", exportNotes()?)?
link "Download" href="/export.zip" download="notes.zip"
button "Save a copy" press=save
Examplea whole program
state said = ""
action pack
let z = zip.gzip("hello hello hello")?
let back = zip.gunzip(z)?
let archive = zip.pack([{name: "a.txt", data: "hello"}, {name: "b.bin", data: back}])?
let files = zip.unpack(archive)?
fs.save(archive, "both.zip")?
said = `${z.length} bytes gzipped; ${files.map(f => f.name).join(", ")}`
button "Pack" press=pack
text said

Notifications without a back end#

Pitfalls#

Where a new call goes#

In the source#

esc
Reading the docs…A heading's words count for more than what stands under it.
↑↓move
↵open
ranked by BM25, in the page