The reMarkable cloud api for JavaScript and TypeScript. Every call runs the
Rust core of the
rmapi monorepo, compiled to WebAssembly:
a client that reads and edits the account one call at a time, an offline
library that edits without a network and merges with the account when it
syncs, and .rm pages read, drawn on, written back byte for byte and merged.
npm install rmapi-js
Register a device once, with the code from https://my.remarkable.com/device/browser/connect, and keep its token:
import { Client, DeviceToken } from "rmapi-js";
const device = await DeviceToken.register("abcdefgh");
await save(device.toString());
const client = new Client(DeviceToken.parse(await load()));
The client reads and writes one item at a time. Each item is named by a
reference to its state, and an edit fails with a HashChangedError if another
device changed the item since it was read:
const listing = await client.listItems();
for (const { item, metadata } of listing.items) {
console.log(item.kind, metadata.name, metadata.lastModified);
}
const pdf = await client.createDocument("paper", { kind: "pdf", body: bytes });
const renamed = await client.rename(pdf, "a better name");
const content = await client.content(renamed);
content.addTag("to read").setMargins(100);
const tagged = await content.push("merge");
A file read through the client holds the item's reference: each setter records
an edit with its time, and push writes the edits and moves the reference on.
If the account's file changed since the read, push() fails with a
HashChangedError and leaves the file as it was, push("merge") merges the
edits onto the newer file and writes that, and pull() makes that merge
without a write. client.batch() gathers many files, refusing another
client's file or a second copy of one as it is added; its push writes their
edits, a new page with the .content that adds it among them, in one write,
all or none, and its pull pulls them together. client.pushAll(files) and
client.pullAll(files) do the same for a list. intoInner() gives back the
reference and the plain file, with the page's id between them for a page, its
layer names or its highlights, which putContent, putMetadata and
putTemplate write to a reference given.
const notebook = await client.content(document);
const added = notebook.addPage("end");
using page = client.blankPage(document, added, "RM110");
page.edit().drawingLayer().addStroke(stroke);
await client.batch().add(notebook).add(page).push();
The offline library keeps a copy of the account, edits it at once without a network, and sends the edits on the next sync:
import { Library } from "rmapi-js";
using library = await Library.load(client);
await library.sync();
for (const entry of library.root().children()) {
console.log(entry.name);
}
const folder = library.root().createFolder("inbox");
library.document(id)?.moveTo(folder);
await library.sync();
The library holds the account's templates too, as LibraryTemplate items:
definition() reads one's .template offline, and putDefinition queues the
edits made to it.
const template = library.template(id);
if (template !== undefined) {
const definition = await template.definition();
await template.putDefinition(definition.setAuthor("me"));
}
A page of a library document opens for writing, and closes with
await using, which hands its edits to the next sync:
const page = await library.document(id)?.page(pageId);
if (page !== undefined) {
await using open = await page.open("RM110");
open.edit().drawingLayer().addStroke({ pen: 17, color: 0, points });
}
await library.sync();
Page.parse reads a .rm file on its own, and toBytes writes it back. A
version 3 or 5 page is read only; legacy() gives its layers of strokes as
the file stores them. Under a version 6 page, blocks.BlocksPage holds every
block of the file as a plain object, written back byte for byte, and
resolve() gives the scene they show; Page.fromBlocks makes an editable
page of them. A damaged page reads, shows nothing, and says why in damage,
a ResolveError naming the item it stopped at.
client.raw() is the protocol under the client: the root, the indexes and
the blobs. An index keeps the lines it cannot read and writes them back, so
an edit made here loses nothing another client wrote:
const raw = client.raw();
const root = await raw.root();
const index = await raw.rootIndex(root.hash);
const files = await raw.itemIndex(item);
const staged = raw.stageText(item.id, { type: "pagedata" }, "Blank\n");
files.insert(staged.itemFile!);
const { entry, blob } = raw.stageItemIndex(item.id, files, root.schemaVersion);
index.insert(entry);
const top = raw.stageRootIndex(index);
await raw.uploadMany([staged, blob, top]);
await raw.putRoot(top.hash, root.generation, "notify");
A library page gives what a reader draws: its strokes' points in the same
units whichever way the file stores them, frame to carry them onto the page
as it is shown, over a notebook page or a PDF page, and the template it is
drawn over, which templateDrawing lays out into the lines, shapes and text
to draw behind it. Template.builtIn has rmapi's version of each of the
tablet's papers, upright and landscape, and a template item is drawn as its
definition:
import { displayRgb, isEraser, penTool } from "rmapi-js";
const page = await library.document(id)?.page(pageId);
const drawn = await page?.read();
if (page !== undefined && drawn !== undefined) {
const { orientation } = await page.document.content();
const template = await page.template();
const size = drawn.size(orientation);
const behind = template && (await library.templateDrawing(template, size));
for (const mark of behind?.marks ?? []) {
// draw each shape and text on a canvas
}
const frame = drawn.frame(orientation, "notebook");
for (const stroke of drawn.layers().flatMap((layer) => layer.strokes())) {
const tool = penTool(stroke.pen);
if (frame === undefined || (tool !== undefined && isEraser(tool))) continue;
const color = displayRgb(stroke.color);
for (const point of stroke.points()) {
const [x, y] = frame.point(point.x, point.y);
// draw to x, y in color, frame.width(point.width) wide
}
}
}
rmapi does not draw the marks. To draw them as the tablet does, set text in
IBM Plex Sans, bold where bold is set: it is
free under the Open Font License, and near reMarkable Sans, whose widths place
the text. Stroke with square (projecting) caps and bevel joins, dashed by
dash; a strokeWidth of 0 is the thinnest line the screen can draw.
Hairlines come out 0.5 pixels wide in gray #c0c0c0.
The module loads when rmapi-js is first imported, with a top-level await:
from disk in node, bun and deno, and by fetch of wasm/rmapi_wasm_bg.wasm
beside the module in a browser, which bundlers that understand
new URL(..., import.meta.url) (Vite, webpack 5) copy for you. Node 22 or
later.
Where a top-level await is not allowed, as in a service worker, import
rmapi-js/lazy: the same exports, and nothing works until init has loaded
the module, which the package also exports as rmapi-js/wasm:
import { init, Client, DeviceToken } from "rmapi-js/lazy";
await init(chrome.runtime.getURL("rmapi_wasm_bg.wasm"));
const client = new Client(DeviceToken.parse(token));
Everything the core needs from where it runs is one Platform: requests in
batches, bodies sent and read, hashing, the notification socket, a blob
store and the library's saved state. fetchPlatform builds the one the
package ships, out of fetch, crypto.subtle, WebSocket, a Store and a
StateStore; the client takes its options (fetch, maxTransientRetries,
store, state, connect) or a whole platform. In a browser, keep blobs
and the library in IndexedDB, in databases of the device's account, which
another account signed in on the same browser never sees:
import { Client, IndexedDbState, IndexedDbStore } from "rmapi-js";
const client = new Client(device, {
store: await IndexedDbStore.open(device.account),
state: await IndexedDbState.open(device.account),
});
The databases are named rmapi-blobs- and rmapi-state- followed by
device.account.storageName, the hex SHA-256 of the account's id, and
library.signOut() deletes both, and the client forgets its session and device
token, so a later call through it, or through a file read through it, throws an
UnauthorizedError and sends nothing; a push with no edits still succeeds. It
ends any changes() loop waiting on the library. A library loaded with a client of another
device, as after signing in again, starts empty in place of what the old
sign-in saved, whose unsent edits cannot be sent from the new one, and keeps
the blobs.
reMarkable authorizes the notification socket with a header, which a
browser's WebSocket cannot send. In a Chrome extension connect installs a
declarativeNetRequest session rule that adds it; the manifest needs
declarativeNetRequestWithHostAccess and the notification host
(https://eu.tectonic.remarkable.com/*) among its host permissions. Call
removeSocketAuthorization() when signing out.
rmapi-js/testing, in node and bun, is a reMarkable account held in memory,
to run an app's tests against without a network. It is the Rust core's own
test cloud, in a WebAssembly module of its own that only this entry loads, so
the module rmapi-js loads holds none of it. It refuses what the account
refuses: a token that proves nothing, a blob whose name, checksum or hash is
wrong, a root write at another generation:
import { Client, SessionToken } from "rmapi-js";
import { FakeCloud, sessionToken, testHosts } from "rmapi-js/testing";
const cloud = new FakeCloud();
cloud.seeding().folder(cloud.newItemId(), "a folder").put();
const client = Client.fromSession(SessionToken.parse(sessionToken()), {
...testHosts(),
fetch: cloud.fetch,
connect: cloud.connect,
});
Its switches make the account fail as a real one does, such as
cloud.setOffline(true), cloud.stealRaces(2) or cloud.serverErrors(3),
and cloud.items(), cloud.file(id, name) and cloud.isWhole() read back
what a client left.
The cloud api is reverse engineered, so fixes to what it reads are welcome.
rust/ is the crate that exports the core to WebAssembly, in a cargo workspace
of its own with rust/testing/, which exports the core's fake cloud for
rmapi-js/testing. bun run build:wasm builds a module from each, in a cargo
run of its own so the fake cloud's features never reach the core's module;
bun test runs the specs, and bun doc:md writes Markdown docs to docs-md/.
bench/ times the package over the real pages in ../testdata/private (see
../testdata/README.md; without it, or with RMAPI_BENCH_COMMITTED set, the
small pages in ../testdata/rm) and an in-memory account of 1,400 or 5,000
items in the Rust core's fake cloud, its checks off, behind a fetch. Each
scenario runs in a process of its own, once for timings and once for memory;
they are in bench/scenarios.ts. The times leave out the cloud: what it takes
to answer each request, on the one JavaScript thread, comes off each wall and
processor time. The wasm memory figure is the core's module alone; the
runtime's own figures still hold the cloud's account.
bench/baselines/ holds the figures of this build, to compare against.
bench/compare.ts checks a run of this build against bench/baseline.json.
They run by hand, not in CI.
bench/network.ts runs the operations of ../bench/network.json over the
simulated network it describes — 80 ms round trips with 25% jitter, 50 Mbit/s,
sixteen requests in flight — and prints, for a listing, an upload, a sync and
a notification, how many calls crossed from the core into the platform, how
many requests went out, and the time on the clock and on the processor. It
fails when an operation sends another number of requests than that file, which
the Rust network benchmark checks against too. bench/pages.ts times opening
and drawing on pages of 100 and 5,000 strokes, and listing.
bun run build:wasm
bun bench/run.ts results.json # bun and node
bun bench/compare.ts js results.json # add --write to refresh the baseline
bun bench/run.ts results.json --only=codec --runtimes=node
bun bench/node.ts list.metadata.1400 time # one scenario, printed
bun bench/pages.ts pages.json --only=page.draw
bun bench/network.ts network.json --only=list
The browser numbers come from headless Chromium, through a Playwright installed anywhere outside this package:
(cd /tmp/pw && npm i playwright && npx playwright install chromium)
PLAYWRIGHT=/tmp/pw/node_modules/playwright/index.mjs bun bench/chromium.ts chromium.json