The reference chapter of the Neblla guide — every SDK method, event and property, module by module, plus the complete template. The base contract is in core.txt; when Neblla is the right answer at all is in empezar.txt. # API reference Nothing hangs from the root of `neblla`: everything lives in a module (`neblla.message`, `neblla.room`, `neblla.shop`…), and here each section is one module, in the same order as the dashboard's reference. Every method says where it can be called from: (CLIENT), (SERVER) or (BOTH). In the `server/` files, `neblla` carries the same modules with what a server has: no `neblla.auth`, no `neblla.room.me`, no DOM. **Events: each module listens to its own.** `neblla..on(name, callback)` / `neblla..off(name, callback)` **(BOTH)**: `neblla.room.on('joined', cb)`, `neblla.shop.on('purchase', cb)`. `.off(name)` without a callback removes every listener of that name; `.off()`, every listener of the module. A name the module does not have throws `unknown_event`. Messages and state take no name: `neblla.message.on(cb)` and `neblla.state.on(cb)`. The root of `neblla` has no `.on` and no `.off`. ## neblla.message — messages `neblla.message.send(data)` **(BOTH)** — to EVERYONE in the room. From CLIENT it reaches you too, with `fromMe: true` (a peer-to-peer broadcast). From SERVER it reaches every client with `from: 'server'` — that is the room's authoritative voice, and there is no "me" to reflect it back to. `neblla.message.to(target, data)` **(BOTH)** — to part of the room. `target` is a member's id, a list of ids, a role (`'presenter'`, `'master'`, `'board'`) or a group (its members who are in the room); from CLIENT, also `'server'`; from SERVER, also a player's alias in an anonymous game. An id that is not in the room is taken as a group name. - **To a single member:** `neblla.message.to(userId, data)`, from CLIENT or SERVER, reaches only that member of the room, with `private: true`; it is not broadcast and does not go into the chat history. It travels over P2P when the channel is open and, otherwise, Neblla forwards it to that person only. - **To the presenter:** `neblla.message.to('presenter', data)` **(CLIENT)** — it only reaches the device whose `isPresenter === true`, with `to: 'presenter'`. Not broadcast to anyone else. - **To the server:** `neblla.message.to('server', data)` **(CLIENT)** — a private message to the server (the device running the `server/` file for the current phase). It arrives with `to: 'server'` at `server/room.js` if the room is `running`, at `server/gathering.js` if it is `gathering`, at `server/lobby.js` if you are in the lobby. Not broadcast to the other clients. `neblla.message.on(callback)` / `neblla.message.off(callback)` **(BOTH)** — every message, one event: `{ from, to, data, user, time }`. `from` is the sender's id, or `'server'`; `to` is `null` (the whole room), an id, a list, `'server'`, `'presenter'`, a role or a group, as it was sent. It also carries `fromMe` and `p2p`. On the client you get the room's messages, the ones from `server/` (`from === 'server'`) and, on the presenter's device, the ones sent to `'presenter'`. In `server/` you get the ones sent with `message.to('server', …)` (`to === 'server'`, only at `room.js`, or `lobby.js` / `gathering.js` depending on the room's state) and the ones a client sends to the whole room. ## neblla.state — the room's state `neblla.state.set(state)` **(SERVER)** — publish the new authoritative state. Every device in the room gets it in `neblla.state.on` and `neblla.state.get()` is updated on each of them. It travels P2P between the devices, which costs no quota; when Neblla has to relay it to a device without P2P, its bytes count once against the daily quota. It is public: secrets go in a No-code envelope (`neblla.tools.envelope`, see servidor.txt). `neblla.state.merge(obj, { mode }?)` **(SERVER)** — folds `obj` into the current state and publishes it as `set` does, with the modes of `neblla.db.save`: `'over'` (the default), `'under'`, `'delete'`. `neblla.state.get()` **(BOTH)** — the last state the server published. Useful on standby peers when they are promoted — `room.js` starts with the latest value already there. `neblla.state.on(callback)` / `neblla.state.off(callback)` **(BOTH)** — the server published a new state with `state.set()`; the payload IS the state. Every device receives it (including the backups holding `room.js`, ready to be promoted). You listen right away (`neblla.state.on(cb)`, it can be rewound) or to final state only (`neblla.state.on(cb, { final: true })`). ## neblla.room — the room you are in ### Lifecycle New rooms start in the `gathering` state (you enter with `neblla.rooms.join`, see `neblla.rooms`) — `neblla.room.start()` moves them to `running` and starts `room.js`. `neblla.room.leave()` **(CLIENT)** — leave the current room and go back to the lobby. Fires `room.on('left')`. `neblla.room.start(name?)` **(CLIENT, or `server/gathering.js`)** — from a client only the presenter may call it; `server/gathering.js` may also call it to auto-start the room. Moves the room from `gathering` to `running`. The SDK picks the server peer and starts `room.js`. With a `name` argument it does `rooms.join` + `room.start` in one operation. `neblla.room.persist({ name, type, whitelist?, ttlInactivity? })` **(CLIENT)** — promotes a freshly booked room from `ephemeral` to `public` or `private`. `ttlInactivity` (whole days 0–3650, `0` = never): how long this room lasts without activity before it is deleted, instead of its type's time (salas.txt); out of range, `invalid_ttl`. A `public` room cannot go past the app's time for public rooms (nor be `0`, unless that time is `0`): otherwise `invalid_ttl` with `min: 1` and `max` = the app's time. Call it between `rooms.book` and the first `rooms.join` — once anybody is in, the type is fixed. The room keeps what `rooms.book` gave it (`config`, the master password and `requireLogin`) and its `data` from the first moment: when it comes back after being empty, it comes back the same. The whitelist (for `private`) bootstraps the initial members (the caller is added as the first owner). Whitelist ids are **per-app userIds** (the `id` of `neblla.room.users[i]`), not personIds — they only resolve against users online in this app at that moment. Offline people are added later with `neblla.social.inviteToRoom`. `neblla.room.setData(data, { now? })` **(CLIENT)** — any member, or only its moderators if the room has them (otherwise `room.on('dataError')` with `not_moderator`). Merges `data` into `neblla.room.data`, key by key at the top level (keys you leave out stay; send a key as `null` to clear it) (persisted in `public`/`private` rooms: Neblla holds it in memory and writes it at the key moments; `{ now: true }` writes it at once, once every 10 s per room at most). Every member of the room gets `room.on('data')`. Subject to the `maxDataSize` anti-abuse limit (10 KB by default; you change it or turn it off in the room settings); going over emits `room.on('dataError')`. `neblla.room.now()` **(BOTH)** — the room's shared time, the same on every device. In `server/`, use it instead of `Date.now()`. ### Private rooms, membership `neblla.room.members(name?)` **(CLIENT)** — `private` only. Returns `{ members[], invites[] }`. `neblla.room.kick(targetUserId)` **(CLIENT)** — kick someone from the current private room. Owner or moderator only. `neblla.room.abandon(roomName?)` **(CLIENT)** — give up membership of a private room. Different from `room.leave`: leave means "I am disconnecting now", abandon means "take me off the whitelist". `neblla.room.promote(targetUserId)` / `neblla.room.demote(targetUserId)` **(CLIENT)** — owner management. Owner only. You cannot demote yourself if you are the last one. Invitations are answered with `neblla.rooms.acceptInvite` / `rejectInvite`. ### Room roles (master and board) Two optional **front-of-house** roles, not server ones: none of this changes who runs the `server/` files, and taking one does not start the room. They need the `multiplayer` feature and do not exist in the lobby (`not_in_room`). They take a **per-app userId**, so an anonymous user can hold them too. `neblla.room.transferMaster(targetUserId)` **(CLIENT)** — passes the *master* role to another member of the room. The current master may call it; while there is no master yet, so may the presenter (a fallback so a room is never stuck without one). Once a master exists the presenter loses that power — otherwise the role would be takeable back at will. In a room with a master password the presenter never has it (`master_protected`). Errors: `not_authorized`, `master_protected`, `target_not_found`, `not_in_room`. `neblla.room.claimMaster(password)` **(CLIENT)** — takes the *master* role with the password the room was booked with (`neblla.rooms.book({ masterPassword })`, 1–128 characters). Errors: `wrong_password`, `too_many_attempts` (with `retryInMs`), `no_master_password`, `not_in_room`. `neblla.room.setBoard(targetUserId | null)` **(CLIENT)** — marks a member as the *board*: the display device (the shared screen, the board on the table). Same authority as `transferMaster`. It is **exclusive**: giving it to one takes it from the other. `null` clears it. Events: `room.on('master')` / `room.on('board')` **(CLIENT)** — `{ user, isMe, room }`, with `user: null` when the role is left vacant. Properties: `neblla.room.master` and `neblla.room.board` (the user, or `null`); and on each user, `isMaster` / `isBoard`. `neblla.room.me.isMaster` is the usual way to branch the UI. ```javascript // The presenter names the big screen and hands over direction neblla.room.setBoard(tabletUserId); neblla.room.transferMaster(anotherPlayerId); // Re-render on every role change and branch on the CURRENT roles, never on `isMe`: // on a vacancy (user: null) no device has isMe true, so a bare isMe check leaves // nobody rendering the table. See the branch rule in empezar.txt. let inLobby = true; // no event carries it except room.on('joined'), so track it yourself const isTable = () => !inLobby && (neblla.room.me.isBoard || (!neblla.room.board && neblla.room.me.isPresenter)); const paint = () => isTable() ? renderTableView() : renderHandView(); neblla.room.on('joined', (e) => { inLobby = e.isLobby; paint(); }); // the value flips HERE too neblla.room.on('board', paint); neblla.room.on('presenter', paint); ``` ### Chat history (persistent rooms) `neblla.room.history({ name?, before?, limit? })` **(CLIENT)** — pages through persisted chat. Newest first. Default limit 50, max 200. Deleted messages come back with `body: null` and `deleted: true`. `neblla.room.deleteMessage(messageId, name?)` **(CLIENT)** — soft delete. Author, owner or moderator. Emits `room.on('messageDeleted')` to everyone. ### P2P files `neblla.room.sendFile(file, opts?)` **(CLIENT)** — a P2P (WebRTC) file transfer to the other peers in the room **that already have an open P2P channel** — it does not open a new one. Without `to`, peers without one are skipped (it resolves with `{ fileId, sent }`, and `sent` says who got it; with nobody reachable it rejects with `no_p2p_peers`). With `to`, if any named peer has no channel it rejects the whole send with `peer_not_p2p` and the list in `peers`. It never falls back to the server relay. **Limits**: 100 MB per file (anything larger rejects with `file_too_large` and the maximum in `max`) and up to 4 transfers at a time from one sender to each receiver — several files are best sent one after another. Emits `room.on('fileStart')` / `('fileProgress')` / `('file')` so receivers can show progress and read the final blob. It does not pass through Neblla — it goes straight between devices. The sender sends the file's SHA-256; the receiver verifies it against the reassembled blob before emitting `'file'`. If it does not match (a truncated or corrupted transfer) it emits `'fileError'` instead — it never hands over a broken blob in silence. ### Properties `neblla.room.name` **(BOTH)** The current room's name. `neblla.room.type` **(BOTH)** `ephemeral`, `public` or `private`. `neblla.room.phase` **(BOTH)** `gathering` or `running`. `neblla.room.users` **(BOTH)** An array with the room's users. `neblla.room.config` **(BOTH)** The open JSON passed to `rooms.book` (this is how those settings reach `gathering.js` / `room.js`). `neblla.room.data` **(BOTH)** The persistent `room.data` of a public/private room. `neblla.room.me` **(CLIENT)** You in the room: the same object as in `neblla.room.users`. You in the app (also as a guest) is `neblla.auth.me`. `neblla.room.presenter` **(BOTH)** The current presenter user. `neblla.room.master` / `neblla.room.board` **(BOTH)** The user holding that role, or `null`. `neblla.room.masterProtected` **(CLIENT)** `true` if the room was booked with a `masterPassword`; the password never travels. Your alias in an anonymous game (`neblla.tools.anonymize()`, see servidor.txt) reaches you alone in `neblla.room.on('alias', ({ alias }) => …)` and stays in `neblla.room.me.alias`. There is no `user.isServer` — the server is opaque on purpose. The user object exposes `{ id, publicInfo, isPresenter, isMaster, isBoard, isMe, purchases }`. `publicInfo` is **always an object** — `{}` until the user calls `neblla.db.setPublicInfo()`, never `undefined`, so `u.publicInfo.name` is safe. ### Events: `neblla.room.on(name, cb)` `'joined'` **(CLIENT)** — you entered a room (also on a reload, with `isReconnect: true`). `{ room, isLobby }` `'started'` **(BOTH)** — the room moved to `running`. It does NOT mean the presenter pressed anything: the caller may have been the presenter or `server/gathering.js`, which is the normal path with `matchmaking.mode: "nocode"`. Do not use this event to attribute the start to a person. `room.js` starts on the server peer. `isMe` is true if you are that peer. `{ room, isMe }` `'server'` **(BOTH)** — the leading Fog changed (the previous one left). One of the followers already had the state and the timers, and carries on seamlessly. `{ room, isMe }` `'flagged'` **(CLIENT)** — the room was marked suspicious. Once per room (anti-troll). `{ room, reason, flaggerId, userCount }` `'left'` **(CLIENT)** — `{ room, user }` `'userJoined'` **(BOTH)** — `{ user, room, isLobby, alreadyPresent }`. `alreadyPresent` is true for the people who were already there when you arrived (the initial roster). `'userLeft'` **(BOTH)** — `{ user, room }` `'userAway'` / `'userBack'` **(BOTH)** — `{ user, room }`. A player lost the connection but keeps their seat (`user.away = true`) / is back. See rooms. `'presenter'` **(CLIENT)** — the presenter changed. `{ user, isMe, room, isLobby }`. `'publicInfo'` **(CLIENT)** — `{ user, publicInfo }`. `'data'` **(BOTH)** — somebody called `room.setData(...)`. `{ room, data }`. `'dataError'` **(CLIENT)** — your `room.setData(...)` was refused (size cap or otherwise). `'closed'` **(CLIENT)** — the app went past its daily quota and the 10 % margin, and the server closed the room and took you out. `{ room, reason: 'quota_exceeded', resetsAt }` (`room: null` when the tab was away when it closed). What you save here waits in the browser until the quota is back; at the reset you go back to the lobby (`room.on('joined')`). `'leftOut'` **(CLIENT)** — this device reaches nobody in the room: no direct P2P, nor through the TURN relay if the app has it, and forwarding through the server is off (`connections: 'p2p'`, what a new app is born with). The others' messages do not reach it. Neblla has already told the user with a notice; your app may add something of its own. `{ room, turn }`. Once per room. `'connection'` **(CLIENT)** — the state of this device's connection to the room: `{ phase, reason, room }`. `phase`: `joining` (asking to enter), `ready` (in, and it reaches someone directly or is alone), `degraded` (in, but nobody reaches it over P2P: everything goes through Neblla's server, `reason: 'no_p2p'`), `reconnecting` (the socket fell and is coming back, `reason: 'server_unreachable'`) and `lost` (`reason`: `timeout`, `server_unreachable`, `no_p2p` when forwarding through the server is off, `kicked`, `room_closed`). Entering never waits for ever: within 10 s at most it is `ready`, `degraded` or `lost`, with its reason. If the app does not listen to the event, Neblla warns on screen (`timeout` and `server_unreachable`) with «Retry» and «Leave». The current one is `neblla.room.connection`, and `neblla.room.retryConnection()` cuts the socket and comes back in. `'fileStart'` / `'fileProgress'` / `'file'` / `'fileError'` **(CLIENT)** — the P2P transfer from `room.sendFile`. `'file'` carries the complete blob, already verified by SHA-256. `'fileError'` (`{ reason: 'checksum_mismatch' | 'size_mismatch' | 'peer_disconnected', ... }`) fires when the reassembled blob does not match what the sender declared, or with `reason: 'peer_disconnected'` (and `received`) when the peer drops mid-transfer; on the sender, `sendFile` rejects with `peer_disconnected`. **`fileProgress` is asymmetric**: the receiver gets `{ received, total, fromMe: false }` and the sender gets `{ sent, total, fromMe: true }`. Same idea, different field, so a progress bar has to read both — `const done = event.received ?? event.sent;` — or it will sit at zero on one of the two ends. Persistent rooms **(CLIENT)**: `'userInvited'` — an owner added people to the pending invites. `'inviteAccepted'` / `'inviteRejected'`. `'userKicked'` — removed from the whitelist by an owner or moderator. `'userAbandoned'` — they took themselves off. `'ownerAdded'` / `'ownerRemoved'`. Persisted chat **(CLIENT)**: `'messageSaved'` — the echo carrying the id you need in order to delete it, `{ room, id, from, time, pending? }` (`pending: true`: the line waits to be written, store full or not answering; it is written by itself). `'messageDeleted'` — render a tombstone. `'messageDropped'` — to the author only: the message was not persisted (too_large or rate_limited) or not sent (`room_lost`, `not_sent`), `{ room, error, m }`. `'messageSent'` — Neblla confirmed your message, `{ room, m, dup? }` (the local echo carries `pending: true` and `m`; see salas.txt). Anonymous games and notices: `'alias'` **(CLIENT)** — `{ alias, room }`, your alias for the game. `'announce'` — what a player says in public through `neblla.tools.announce` (see servidor.txt). `'hook'` — an incoming webhook or an Automation delivered data to the room (see core.txt). ### The `server/` files `neblla.server.on('start' | 'stop', callback)` **(SERVER)** — `{ file }`. `'start'` fires once the file (`lobby.js`, `gathering.js` or `room.js`) has run its top-level code; `'stop'`, before it is stopped, to clear timers or send the last word. On the client there is no `neblla.server`. ## neblla.rooms — all rooms `neblla.rooms.book({ config?, length? })` **(BOTH)** — books a unique room name. Returns `Promise`. `length` (3–12, 5 by default) sets how many characters the code has, e.g. `{ length: 3 }` if your UI has three boxes. It does **not** enter the room — call `neblla.rooms.join(name)` afterwards. The optional `config` is persisted on the future room and exposed as `neblla.room.config` inside `gathering.js` and `room.js`. `neblla.rooms.join(roomName)` **(CLIENT)** — enter a room. Fires `room.on('joined')`. New rooms start in the `gathering` state — the presenter calls `neblla.room.start()` to move to `running` and start `room.js`. `neblla.rooms.list({ type? })` **(CLIENT)** — the persistent rooms the user can reach. Each entry: `{ name, type, creator, memberCount, activeUsers, lastActivityAt }`. `neblla.rooms.get(name?)` **(CLIENT)** — inspect a room by name (the current one by default). `neblla.rooms.delete(name?)` **(CLIENT)** — delete a persistent room. Moderators (any room) and owners of private ones (theirs). Everyone is sent back to the lobby and `rooms.on('deleted')` is emitted. `neblla.rooms.setType(name, type)` **(CLIENT)** — move between `public` and `private`. Moderators only. `neblla.rooms.acceptInvite(roomName)` / `neblla.rooms.rejectInvite(roomName)` **(CLIENT)** — answer an invitation (`room.on('userInvited')`). `neblla.rooms.gathering` **(CLIENT, lobby)** — the rooms currently forming, visible from the lobby, each `{ name, config, users }`. Kept in sync by `rooms.on('gathering')`. `neblla.rooms.follow(name?)` / `neblla.rooms.unfollow(name?)` **(CLIENT)** — follow or stop following a persistent room you are a member of (the current one by default); `follow` returns its entry. Errors: `login_required`, `not_whitelisted`, `room_not_found`, `not_followable`, `follow_limit_reached` (200). Details in salas.txt, "Following a room". `neblla.rooms.followed()` **(CLIENT)** — asks the server for the rooms you follow and refreshes `neblla.rooms.following`. `neblla.rooms.markRead(name?)` — sets its new messages to 0 without entering (`not_following`). `neblla.rooms.direct(friend)` **(CLIENT)** — the private room of the two of you with a friend (`friend` or `friend.id`, from `neblla.social.friends`): created the first time, the same one after; never deleted for inactivity, and both follow it. Returns `{ name, created }`; enter it with `rooms.join(name)`. Errors: `login_required`, `scope_missing`, `not_friends`, `self`, `invalid_friend`, `type_not_allowed_by_policy`, the private rooms' limits. Recipe in salas.txt. `neblla.rooms.following` **(CLIENT)** — the rooms you follow, `[{ name, type, unread, lastMessageAt, lastReadAt, followedAt }]`, the most recent first. It arrives by itself on signing in and is kept current with `rooms.on('following')`; `[]` without a session. ### Events: `neblla.rooms.on(name, cb)` `'gathering'` **(CLIENT, lobby)** — a refresh of the rooms currently forming. `{ rooms: [{ name, config, users, present }] }`. Mirrored in `neblla.rooms.gathering`. `'joinError'` **(CLIENT)** — entering a room failed (`code: 'room_full'` when it already holds `matchmaking.maxPlayers` users, `code: 'quota_exceeded'` when the app spent its quota for the day, `code: 'invalid_room_name'` when the name is not 1-64 characters of text, whitelist, kick, and so on). `'invite'` **(CLIENT)** — `{ from, roomName, appId, type }`. `'kicked'` **(CLIENT)** — pushed straight to the person kicked. `'deleted'` **(CLIENT)** — `{ room, reason, by? }`. `'typeChanged'` **(CLIENT)**. `'followedMessage'` **(CLIENT)** — someone wrote in a room you follow while you were not inside. `{ room, unread, from: { id, publicInfo }, time }`. `'following'` **(CLIENT)** — `neblla.rooms.following` changed. `{ rooms }`. ## neblla.auth — who the user is `neblla.auth.login(opts?)` **(CLIENT)** — SSO. `opts.scopes` lists the permissions asked for: `email`, `friends`, `discoverable`, `profile`. Call it inside the user's click: the sign-in window opens right then (so the browser does not block it) and, if the user already had a session, closes by itself. With `{ token }`, signs in with your own login: the single-use token your server asked Neblla for (see identidad.txt). `neblla.auth.logout()` **(CLIENT)** — signs out of this app. It does not end the Neblla SSO session. `neblla.auth.idToken()` **(CLIENT)** → `{ token, expiresIn }`, a JWT signed by Neblla so your server knows who the user is (see identidad.txt). `neblla.auth.requestErasure()` **(CLIENT)** — opens the Neblla window where the user asks you to erase what they gave your app (see identidad.txt). `neblla.auth.me` **(CLIENT)** — you in the app, also as a guest: `{ id, publicInfo, grantedScopes, loggedIn, profile }`. Your role in the room is in `neblla.room.me`. ### Events: `neblla.auth.on(name, cb)` `'login'` **(CLIENT)** — `{ type, data, grantedScopes, appUserId, email?, profile? }` (`appUserId`: the user’s id in your app, the same on all their devices). `'logout'` **(CLIENT)** — `{}`. `'scopes'` **(CLIENT)** — the user changed in their Neblla account what your app may read of them while signed in: `{ grantedScopes, profile }` (`profile` is `null` once revoked). `'expired'` **(CLIENT)** — the session expired. `{}`. `'error'` **(CLIENT)** — `{ code: 'popup_blocked', url }`: the browser blocked the sign-in window. Render a button that opens `url` (a click is a fresh gesture, and the browser allows it). `{ code: 'store_unavailable' }`: the app's own database (BYODB) does not answer and the sign-in cannot happen, whatever the way in; it also comes on `neblla.app.on('error')` (see below), and `neblla.auth.login({ token })` / `({ jwt })` reject with that code. The user stays a guest. `{ code: 'no_socket' }`: Neblla does not answer (the server is down); `login()` waits 8 s. If nobody listens to this event, the SDK shows a small notice at the bottom, in the language of `` (server, blocked window with an «Open» link, and the same for `roomJoinError`: room full, no invitation, Login needed); turn it off with `window.NEBLLA_NOTICES = false`. Same when the app will not let the player in or cannot save: out of today's quota (with the hour it comes back), no room, being updated, too many tries, or gone; and the room closed by quota. If progress waits more than 10 minutes (in the server's queue because the app is full, or on this device), the player sees it once; the app hears `neblla.db.on('pending', ({ since, where }))` (`where`: `'server'` or `'device'`) and `neblla.db.on('setAside', ({ until }))` when the server sets held saves aside. `'cancelled'` **(CLIENT)** — the player closed the Login window without signing in: drop your «Signing in…». `'switch'` / `'tokenExpired'` **(CLIENT)** — an account switch, and your own login's token expired (see identidad.txt). ## neblla.db — what the user keeps `neblla.db.save(json, opts?)` **(CLIENT)** — persists data. Locally or on the server depending on login. By default it only touches what you send (`mode: 'over'`) and only that is charged. `opts.mode` = `'over'` | `'under'` | `'full'` | `'delete'`; `opts.empty` = what counts as empty (`'null'`, `'emptyArray'`, `'emptyString'`); `opts.arrays` = `'replace'` | `'push'` | `'pull'` | `'complete'` (or per field, with `unique` and `sort`); `opts.crdt` = newest wins per field across devices; `opts.at` = when the change happened (`Date` or ms), to send late what was done offline: turns `crdt` on, `'over'` only; `opts.table` = a row in a table of yours (see identidad.txt); `opts.now` = send it now. With a login, the save waits in the browser and goes at the key moments (closing or leaving the page, changing tab, leaving a room, signing in elsewhere, `now`, every 10 minutes at most); consecutive `over` saves fold. Returns a promise: at once `{ data, mode, pending, onDevice: true }`; with `now`, once the server stored it (`onDevice: false`), or it rejects with `code` (`save_too_large`, `invalid_save`, `invalid_at`, `login_required`, `quota_exceeded`, `save_loop`; with `onDevice: true` when it still waits). When a batch lands, `neblla.db.data` is updated and `db.on('merged')` fires. `neblla.db.data` **(CLIENT)** — your saves. `neblla.db.waiting` **(CLIENT)** — how many of this user's saves wait on this device to go (see identidad.txt). `neblla.db.pending` **(CLIENT)** — `true` while your saves wait in the queue because the app's store is full (see publicar.txt); your data already shows them, and they are written when there is room. `false` as soon as one reaches the store. With the store full, a row saved with `{ table }` comes back with `pending: true` and its `id`, and `db.delete()` with `{ removed: true, pending: true }`. `neblla.db.setPublicInfo(info)` **(CLIENT)** — your public profile (visible to the whole room). Names, avatars, colours. `neblla.db.load({ table, group?, where?, orderBy?, limit? })` / `neblla.db.delete({ table, group?, id })` **(CLIENT, login)** — your rows, or your group's according to your role; written with `neblla.db.save(data, { table, group?, id? })` (see identidad.txt, "Tables"). `neblla.db.watch(…)`, `shareLink`, `openLink`, `links`, `revokeLink`, `pendingLink` **(CLIENT)**: live notices and read-only links (`openLink` without a login). In `server/`, `neblla.db.load`, `save` and `delete` with `{ table }` **(SERVER)**; in `save`, `{ user }` says which user of the room the row belongs to. With your own database a table can be **free** (`kind: 'free'`: your own columns, key and limits; `neblla.session.freeTables`; see identidad.txt, "Free tables"). `neblla.db.dataOf(user)` / `neblla.db.loadOf(user, { table, where?, orderBy?, limit?, offset? })` **(CLIENT)** — what of another user your app lets others see (`neblla_update_app({ visible })`): the part of their `db.data` marked for whoever reads (an object, `{}` when none is for them) and their rows of a marked table, without owner. `user`: their id in the app, their id in the room, the `id` of a friend from `neblla.social.friends`, or the object (a community `author`, a room user, a friend). Errors: `not_visible` (the app marks nothing, or not that table), `not_friends` (a friends-only table), `user_not_found`, `unknown_table`. See identidad.txt, "What other users see". `neblla.db.offer({ to, give, get, expires? })` / `neblla.db.offers({ status?, limit? })` / `neblla.db.acceptOffer(id)` / `neblla.db.declineOffer(id)` / `neblla.db.cancelOffer(id)` **(CLIENT, login)** — trades between users (`neblla_update_app({ trade })`): offer something of theirs (`give`) for something of the other's (`get`); each thing is `{ table, id }` (a row of theirs) or `{ product, amount }` (units of what they bought). `offer` returns the offer (`{ id, from, to, give, get, status: 'pending', expiresAt, mine: 'sent' }`); `offers` theirs, pending by default (`status: 'all'` or one: `done`, `declined`, `cancelled`, `expired`, `failed`); `acceptOffer` moves everything at once or nothing, and returns the offer `done`. `neblla.db.on('offer', ({ action, offer }) => …)`: `new`, `done`, `declined`, `cancelled`, `failed`, on both users' devices. See identidad.txt, "Trades between users". ### Events: `neblla.db.on(name, cb)` `'merged'` **(CLIENT)** — the server resolved a `db.save()`. `{ data, mode, pending }` — `data` is the resulting document (already copied into `neblla.db.data`); `pending: true` when the store is full and the save waits in the queue (not an error: the game goes on with it). `'error'` **(CLIENT)** — a `db.save()` was not stored. `{ reason }`, for example `invalid_save` if `data` is not an object, `invalid_at` if `at` is not a time or the mode is not `'over'`, `save_too_large` (with `bytes` and `max`), `save_loop` (more than 1000 waiting on the device), or a row's error (`too_many_rows`…); the ones the server will never take carry `save` (`{ k: 'doc' }` or `{ k: 'row' | 'del', table, id }`) and are dropped. ## neblla.scores — scores of a game for one `neblla.scores.start(ranking, { fresh }?)` **(CLIENT, login)** — starts a game on Neblla: `{ run, seed, startedAt, until }`. On a ranking with `runsPerDay` or `seed: 'daily'`, if the user already has an open, unexpired game it is returned as it was (same `run`, `seed`, `startedAt` and `until`, with `resumed: true`) and no other is counted: a reload or a double click does not burn the day, and the clock is the server's (reloading gives no more time). `{ fresh: true }` forces a new one (closes the open one and counts one): call it from a «new game» button. Wait for `start` before the game begins. On other rankings it closes the user's open game and opens another, as always. `neblla.scores.current(ranking)` **(CLIENT, login)** — the user's open game `{ run, seed, startedAt, until }` or `null`, to resume after a reload without `localStorage`. Rejects with `runs_per_day` (with `max`), `unknown_board`, `login_required`. `neblla.scores.submit(game, value, { data? })` **(CLIENT, login)** — sends that game's score (what `start` gave, or its `run`), once. Neblla checks it with the ranking's limits and, if you declared one, with your own check (`check`, which gets `data`). `{ ok: true, value, best, newBest, place }` when it enters; `{ ok: false, reason }` when not: `below_min`, `over_max`, `too_soon`, `too_fast`, `check_refused` (they mark the user), `invalid_value`, `run_expired`, `run_used`, `run_closed`, `run_not_found`, `check_unavailable` and `run_pending` (with `retry: true`: they can be repeated; `run_pending` = the first send of that game is still being checked). `neblla.scores.top(ranking, { period?, limit?, friends? })` **(CLIENT)** — the best: `period` `'all'` (default) or `'day'` (today: UTC, or the ranking's `timeZone`); `limit` up to 100; `friends: true`, only the user and their friends who gave the app the friends permission, placed among themselves (needs a login and the friends permission: `login_required`, `scope_missing`). `[{ place, player, value, at, info?, me? }]` (`player`, the user's id in the app; `info`, their `publicInfo`; `me: true` on your own row). Guests too. `neblla.scores.mine(ranking)` **(CLIENT, login)** — your own standing: `{ best, bestAt, dayBest, runs, place }` or `null`. Rankings are declared with `neblla_update_app({ scores })` or in the panel, Features › Scores and rankings (see identidad.txt, "Scores of a game for one"). ## neblla.media — the app's photos, textures and sounds The app's media (a gallery's photos, a game's textures, sounds, videos, `glb` models), many, apart from its files: the developer uploads them with `neblla_media` or in the panel (Build › Media), with no versions and no `neblla_promote`, and the app always reads them as they are now, in pre and in pro. No login. `neblla.media.collection(name)` **(CLIENT)** — one collection, by its name ("Weddings") or its key ("weddings"), in its order: `{ collection, key, changedAt, items: [{ id, kind, mime, title, text, alt, fields, width?, height?, color?, url, srcset?, variants?, original }] }`. `fields` are the developer's own fields (`{ year: 2023, size: "70 x 45 cm", price: 520, available: true }`); `url`, the WebP variant up to 1280 px; `srcset`, all of them (320, 640, 1280, 2048, never wider than the original); `original`, the file as it was uploaded; `color`, the dominant colour, for the background while it loads. It is read from Neblla every time (with an ETag: unchanged, it costs almost nothing), so a change of the developer's shows on the next read without touching the code. Rejects with `collection_not_found`. `neblla.media.collections()` **(CLIENT)** — `[{ collection, key, count, changedAt, cover }]`, `cover` the first item or `null`. `neblla.media.img(item, { sizes?, loading? })` **(CLIENT)** — a ready ``: `src`, `srcset` with `sizes` (`'100vw'` by default), width and height (no jumps while loading), `alt` (or the `title`), `loading: 'lazy'` and the dominant colour as background. ```js const { items } = await neblla.media.collection('Work'); for (const it of items) grid.append(neblla.media.img(it, { sizes: '(min-width: 800px) 33vw, 100vw' })); ``` **Files for sale** (C230): a private item says `private: true`, `bytes`, `unlockedBy: { products, credits }` and `original: null`; whoever has the right downloads it with `neblla.media.download(id)` **(CLIENT, login)**, a link of 5 minutes (more for big files) straight from the bucket (`{ url, expiresAt, name, mime, bytes, via }`; `{ open: false }` only returns it), spends a credit on one with `neblla.media.unlock(id, kind?)`, and reads what is theirs with `neblla.media.mine()`, also the private content of what they bought (`content`: a link or a text, C330). The whole story, in pagos.txt, "Files for sale". ## neblla.app — the app's notices `neblla.app.on('error', cb)` **(CLIENT)** — the SDK's general error channel: the server blocked something and your events would otherwise go silently dead. `{ code }`, where `code` is `'quota_exceeded'` (the app spent its daily budget; it resets at 00:00 UTC; it carries `resetsAt` and `stage`: `'grace'` while running rooms go on and only new things are refused, `'closed'` once they closed), `'player_quota_exceeded'` (this user spent their share of the app's day, `playerQuota`; also until 00:00 UTC), `'storage_full'` (the app's store is full and writes are queued: nobody new comes in until the developer makes room), `'store_unavailable'` (the app's own database, BYODB, is not answering: signing in, saving and buying pause until it is back; the user cannot sign in by any way in and stays a guest, and Neblla's window tells them why; whoever is already in goes on; it also logs a console warning), `'app_not_found'` (the developer deleted the app; it also logs a console warning) or `'app_maintenance'` (the app's database is moving; a call that waits for an answer gets it too, as `{ error: 'app_maintenance' }`, and the saves waiting in the browser are retried later). The quota case also logs a console warning. Listen for it if you want to show the user a "we are out for today" screen instead of a frozen app. `neblla.app.on('outdated', cb)` **(CLIENT)** — the page runs an old SDK (a tab left open for days, a PWA) and the server already has another for the app's modules. `{ current, loaded }` (the names of the two fixed parts). If you do not listen to it, the SDK handles it: with no live room it reloads the page once (at most once every 10 minutes), and with a live room it does not cut it: it shows a «There is a new version · Reload» bar in the language of `` (`window.NEBLLA_NOTICES = false` turns it off). If you listen to it, it does neither: you decide. It is not emitted in the editor's pre or in compiled apps. `neblla.app.on('maintenance', cb)` **(CLIENT)** — the developer is migrating the app's database to another backend (see identidad.txt). Your socket will disconnect in about 2 seconds; the SDK connects again by itself after `retryInSeconds` (5 s at least). If it comes back before it ends, it hears another `maintenance` and is let go again; there is no "it ended" notice: getting back in means it is over. Use it to show something like "we are under maintenance, back in a moment". `{ reason: 'byodb_migration', retryInSeconds: 30 }`. `neblla.app.permission(name, opts?)` **(CLIENT)** — asks for a browser permission: `'microphone'`, `'camera'`, `'geolocation'` or `'midi'` (`{ sysex: true }` also asks for SysEx). Resolves `'granted'` or `'denied'` (an unknown name, `'denied'`). Your app runs inside an iframe in the gallery, so Neblla's page asks for the permission and the browser prompt says "neblla"; if you call `getUserMedia` or geolocation directly, the SDK does the same for you the first time. `neblla.app.devPreview` **(CLIENT)** — `true` only in the app's pre (its private link, or your page on `localhost`); never for the users of pro. Use it to show developer shortcuts, such as "set up products". `neblla.app.dashboardUrl({ tab?, section? } | { account })` **(CLIENT)** — a link to this app's dashboard (`{ tab: 'products' }`) or to a tab of your account (`{ account: 'claude' }`). Pairs well with `devPreview`. `neblla.app.debugging` **(CLIENT)** — on by default: the SDK emits `neblla.app.on('debug', cb)` with `{ label, data }` at its internal steps. Set it to `false` to silence it. ## neblla.social — friends and invitations Needs the `friends` scope, except `inviteToApp`. `neblla.social.request(target)` — a request to a user online in this app, or `neblla.social.request({ code })` with their friend code even while they are offline (it waits in their inbox). `neblla.social.code()` → the user's own code, or `null`. `neblla.social.accept(requestId)` / `neblla.social.reject(requestId)`. `neblla.social.remove(friendId)` — works while they are offline. `neblla.social.inviteToRoom(target)` — add someone to the whitelist of your private room. `neblla.social.inviteFriend(target)` — a casual invitation to a friend to join your room (any type). `neblla.social.inviteToApp()` — opens a Neblla popup to invite a Neblla friend TO YOUR APP (the app never sees the friend list). Needs a login. Fire and forget: the invitation lands in the friend's inbox on play.neblla.com (it expires in 24 hours) and brings them to your app. Does not need the `friends` scope. `neblla.social.list()` — a manual refresh of `friends` and `requests`; returns the friends. `neblla.social.friends` **(CLIENT)** Friends visible in this app. `neblla.social.requests` **(CLIENT)** Requests received. `neblla.social.invitedBy` **(CLIENT)** Who invited you to this app through the Neblla inbox, or `null`. `{ id, name, picture, slug, userId|null }`. ### Events: `neblla.social.on(name, cb)` `'updated'` **(CLIENT)** — `{ friends }`. `'request'` **(CLIENT)** — `{ requestId, from }`. `'accepted'` / `'removed'` **(CLIENT)**. `'appInvite'` **(CLIENT)** — a Neblla friend invited you to this app (you arrived through the inbox link, or they invited you while you were already inside). `{ from }` with `from = { id, name, picture, slug, userId|null }`. It also fills `neblla.social.invitedBy`. If the `?nbla_invite=` link expired (24 h) or is not valid, the event arrives as `{ from: null, expired: true }` so the app can say so. ## neblla.shop — purchases `neblla.shop.buy(productId, amount?, opts?)` **(CLIENT)** — opens the checkout. A guest buys with a light account; with `emailCheckout: false`, they sign in first, in the same window. `opts.series`: the timetable chosen of a fixed place with several (`series_required` with `choices` when missing). `neblla.shop.consume(productId, amount)` **(CLIENT)** — spends units. `neblla.shop.validate(userId, productId)` **(BOTH)** — checks ownership. `neblla.shop.products()` **(BOTH)** — lists the products. `neblla.shop.manage(productId)` **(CLIENT, login)** — opens the subscriber's Stripe portal (see pagos.txt). `neblla.shop.restore(email)` **(CLIENT)** — with the light account (`emailCheckout`, on by default), mails a link to that email; the device that opens it (not the one that asked) joins that account's purchases. `neblla.shop.purchases` **(CLIENT)** — your purchases, keyed by productId. Other users' do not travel: check them with `shop.validate`. `neblla.shop.on('purchase', cb)` **(CLIENT)** — `{ userId, productId, slug?, type, purchases }` (`slug`: the product's own name, if it has one), only on the buyer's devices. ## neblla.inbox — communications with the developer `neblla.inbox.send({ message, data?, dateFrom?, dateTo?, thread? })` **(CLIENT)** — sends a message to the back office. `neblla.inbox.update(commId, {...})` **(CLIENT)** — edit it (while it is not `read`). `neblla.inbox.delete(id)` **(CLIENT)** — delete your own. `neblla.inbox.messages` **(CLIENT)** — the user's communications. `neblla.inbox.on('messages', cb)` **(CLIENT)** — the initial sync. `neblla.inbox.on('updated', cb)` **(CLIENT)** — `{ communication, action }`: every change, also those from while you were away (`'messages'` is the list). ## neblla.ai — AI `neblla.ai.prompt(text, { preset?, model?, provider?, userToken? }?)` **(CLIENT)** — returns `Promise<{ text, usage, quota }>`. `provider`: `'claude'` | `'openai'` | `'deepseek'`, the app's by default; another one only when the user pays (see ia.txt). `neblla.ai.on('reply', cb)` **(CLIENT)** — the answer from `neblla.ai.prompt()`. ## neblla.api — third-party APIs and keys `neblla.api.call(name, path, body?, { method }?)` **(BOTH)** — calls an external API with a secret saved with `neblla_set_api_secret`; Neblla fills the secret in and only calls under its base URL. Returns `{ status, contentType, body }`. From the client, and from `room.js` on a Fog (which runs as the player's client), only if the secret has `fromClient: true` (see core.txt). `neblla.api.key(name)` **(BOTH)** — the current value of a key the developer set in the back office or with `neblla_update_app({ keys })`. Public: never secrets (see core.txt). ## neblla.anticheat — anti-cheat `neblla.anticheat.confirm(eventName, value)` **(CLIENT)** — needs the `anticheat` module (`features: { anticheat: true }`) — witness and report. `neblla.anticheat.flag(reason?)` **(SERVER)** — mark the room as suspicious. The players see it in `room.on('flagged')`. ## neblla.groups — groups `neblla.groups.mine()` **(CLIENT, login)** — your groups, `[{ group, role }]`; `create`, `invite`, `join`, `leave`, `members` and `pendingInvite` if the app allows it. On Server, `neblla.groups.create`, `delete`, `add`, `remove`, `list`. ## neblla.community — community All return a promise and reject with `err.code`. Detail in comunidad.txt. `neblla.community.publish({ title, summary?, category?, tags?, lang?, contentType, payload, parentId?, visibility? })` **(CLIENT, login)** → `entry`. Born `published` or `pending` depending on the moderation mode. `neblla.community.update(entryId, patch)` **(CLIENT, login)** → `entry`. Author or moderator only. `neblla.community.unpublish(entryId)` **(CLIENT, login)** — the author withdraws their entry (a real delete). `neblla.community.mine(opts?)` **(CLIENT, login)** → `{ entries, next }`, your own entries in every state. `neblla.community.list({ q?, category?, tags?, lang?, contentType?, owner?, parent?, sort?, cursor?, limit? })` **(BOTH)** → `{ entries, next }`, only `published`, without the payload. `neblla.community.facets(['category'|'tags'|'lang'|'contentType'], { parent? })` **(BOTH)** → counts per value. `neblla.community.get(entryId)` **(BOTH)** → `{ entry, payload }`. `neblla.community.relate(entryId, { favorite?, rating?, review?, data? })` **(CLIENT, login)** → `{ relation, stats }`. A partial merge; `null` clears one slot. `data` is yours: a free JSON object of up to 4 KB on that user's relation with that entry (a bookmark, a note, their best time); it comes back in `relation.data` and never counts in the stats. An author cannot rate or review their own. `neblla.community.vote(entryId, 1 | -1 | null)` **(CLIENT, login)** → `{ vote, stats }`. One vote per person and entry: `1` for (what a bare `vote(entryId)` does), `-1` against only when the app turns it on (`community.downvotes: true`; otherwise `downvotes_off`), `null` or `0` takes it back. It counts in `stats.upvotes`, `stats.downvotes` and `stats.score` (for minus against); `list({ sort: 'votes' })` orders by it. An author cannot vote their own (`own_entry`). `neblla.community.relation(entryId)` **(CLIENT, login)** → `{ favorite, rating, review, reported, vote }`. `neblla.community.favorites(opts?)` **(CLIENT, login)** → `{ entries, next }`, your published favourites. `neblla.community.reviews(entryId, opts?)` **(BOTH)** → `{ reviews, next }`, the public reviews. `neblla.community.report(entryId, { reason, message? })` **(CLIENT, login)** → `{ ok, suspended }`. One per user per entry; at the threshold the entry goes back to `pending`. `neblla.community.shareLink(entryId, { uses?, expiresInDays?, deleteEntry? })` **(CLIENT, login, author)** → `{ token, key, expiresAt, uses }`. A link that carries the key to an entry; the key goes after the `#` in your URL and never reaches the server (a `publish({ ..., visibility: 'private' })` is end-to-end encrypted and never listed). `neblla.community.openLink(token, key)` **(CLIENT, login)** → `{ entry, payload }`; spends one use and decrypts in the browser. Unknown, spent or expired → `link_not_found`. `neblla.community.deviceLink()` **(CLIENT, login)** → `{ url }`. A link (or QR code) with your personal key, to read your private entries on another device of yours. `neblla.community.links({ entryId? })` **(CLIENT, login)** → your links `[{ id, entryId, usesLeft, expiresAt, createdAt, deleteEntry }]`, newest first. `id` is the hash of the token (it opens nothing). `neblla.community.revokeLink(id)` **(CLIENT, login)** → `{ revoked: true }`. Author only (`not_owner`); unknown → `link_not_found`. With `deleteEntry`, revoking the last link deletes the entry. `neblla.community.cardUrl(entryId)` **(CLIENT)** → `'https://play.neblla.com/c//'`, the public (Open Graph) card of a published entry; any other gives 404. `neblla.community.linkedEntry()` **(CLIENT)** → the `?entry=` the page was reached with from a card, or `null`. `neblla.community.counterNotice(entryId, statement)` **(CLIENT, the entry's author)** → `{ cases }`: answers every open formal notice about that entry; it does not restore it. `neblla.community.noticeUrl(entryId)` → the public formal-notice form for that entry. `neblla.community.queue({ status?, cursor? })` / `neblla.community.moderate(entryId, { action, reason?, message? })` **(CLIENT, the app's moderators)** — the queue and the actions `approve` | `reject` | `remove` | `restore` | `suspend`. ### Events: `neblla.community.on(name, cb)` `'updated'` **(CLIENT)** — moderation touched an entry of yours in the community. `{ entry, action }`, where `action` is one of `published` | `pending` | `rejected` | `removed` | `restored` | `modified` | `suspended`; `entry.moderation` carries `{ reason, message }`. `'reportClosed'` **(CLIENT)** — the case on an entry I reported was closed. `{ entryId, outcome }`, `outcome` is `upheld` | `dismissed`. ## neblla.business — business: bookings and credits (details and errors in core.txt) `neblla.business.booking.*` **(CLIENT, login)** — bookings: `services()` (the business's services, sites and professionals), `slots(set, { from, to })` (with `left` and, when the slot belongs to a repeating series, `series`; `earlyUntil` on a new session still only for whoever has the service's product, `early`), `times(set, { from, to, site, staff, step })` (the free times of a `'times'` or `'open'` service), `reserve(set, slotId, { for, party })` (in a set paid at booking, `{ booking, held, holdUntil, url }` and it opens the checkout), `reserveAt(set, { start, site, staff, for, party })` (at a free time: the session is made for them, or it is their open match), `cancel(set, slotId, { for })`, `mine(set)` (with `room`, the session's chat, and `standing` when it came from a fixed place), `standing(set?)` (their running fixed places), `changeStanding(productId, series, { when: 'now' | 'next' })` (another of their fixed place's timetables, with no payment), `move(set, slotId, toSlotId, { for })` (a booking to another session of the service, when it has `moveHours`), `closures({ from, to })` (the business's closed days, to paint them; their sessions come in `slots` as `state: 'cancelled'` with `reason`), `on('update', fn)` (the paid booking, confirmed or cancelled; or `{ set, standing }` when a fixed place books its cases). `neblla.business.credits.balance(kind)` **(CLIENT, login)** — the credits balance. ## neblla.tools — No-code (details in servidor.txt) `neblla.tools.seal(userId)` **(CLIENT)** — names another player in secret in an anonymous game; the server receives their alias, never the name. `neblla.tools.anonymize()` **(SERVER)** — anonymous game: each player gets an alias and `room.js` only sees aliases. `neblla.tools.unmask(userId)` **(SERVER)** returns someone's alias when the game makes it public (quorum of two Fogs). `neblla.tools.deck.*` **(BOTH)** — deck: `create`, `shuffle`, `draw`, `holders`, `add(...).assign/draw`, `muck`, `show`. Drawing without repeats. `neblla.tools.random.*` **(BOTH)** — chance: `create`, `roll`. Drawing with repeats; every roll is announced to the room. `neblla.tools.envelope.*` **(BOTH)** — envelopes: `create`, `seal`, `open`. Any JSON, sealed until a condition is met (`mode: 'p2p'` or `'nocode'`). `neblla.tools.zones.*` **(BOTH)** — zones: `create`, `move`. Who is with whom, without the server knowing where. `neblla.tools.counter.*` / `neblla.tools.score.*` **(BOTH)** — capped counters (`create`, `add`, `read`) and score limits for leaderboards (`create`, `submit`). Only the Fog creates them. By default only the Fog adds to a `counter` and players read it (to let them add, create it with `player: 'add|read'`); players submit to a `score`. The room's shared time, for Fog, is `neblla.room.now()` (in `neblla.room`). ## neblla.world — Mundo, the 3D engine (detail in mundo.txt) With the `world` module. `neblla.world.create(opts)` **(CLIENT)** → `Promise`: downloads the engine the first time. `world.add(spec)`, `world.load(src)` → `Promise`, `world.scatter(model, transforms, opts)`, `world.control(character)`, `world.camera.use(preset, opts)` (`side`, `top`, `iso`, `third`, `first`, `chase`), `world.on(event, fn)` (`touch`, `enter`, `leave`, `collect`, `fall`, `step`), `world.after(s, fn)`, `world.every(s, fn)`, `world.onFrame(fn)`, `world.state()`, `world.hash()`, `world.start()`, `world.stop()`, `world.destroy()`; the catalogue of pieces: `world.catalog.search(text, opts)`, `world.catalog.get(id)`, `world.catalog.list(opts)` and `world.load('catalog:')`; the standard doll: `world.doll(body)` → `Promise` (`{ height, width, legs, torso, arms, head }`), `world.add({ doll })`, `doll.play(move)`, `doll.stop()`; each person's doll (their Neblla account): `neblla.avatar.get(userId?)` → `Promise`, `neblla.avatar.doll(world, userId?)` → `Promise` dressed, `world.avatar(look)`, `doll.dress(look)`; an obby from its JSON (mundo.txt, «Obby as JSON»): `world.obby(json, { doll })` → `Promise` (`game.start()`, `game.on('finish', fn)`) and `world.checkObby(json)` → `{ ok, errors, warnings }`; `world.three`, `world.rapier` and `world.sim` to drop down a layer. `neblla.world.engine()` → the engine's module. ## neblla.cloud — save to your cloud (detail in nube.txt) With the `cloud` module. `neblla.cloud.providers()` **(CLIENT)**, `neblla.cloud.connect(provider)` **(CLIENT, from a click)**, `neblla.cloud.disconnect(provider)` **(CLIENT)** and `neblla.cloud.put(provider, source, { name?, mime?, size?, folder?, to? })` **(BOTH)** → a thenable with `.on('progress', fn)` and `.abort()`; `neblla.cloud.putToApp(source, opts)` saves in the developer's cloud. `neblla.cloud.list(provider, folder?)` **(CLIENT)** → `{ folders, files: [{ name, size, hash, modified }], root: [segments] }` of the app's folder; `neblla.cloud.hash(blobOrFile, 'blocks'|'whole')` → hex (Dropbox content_hash / SHA-256); `neblla.cloud.cleanName(name)` → the name as the server normalizes it. The bytes do not pass through Neblla and the SDK checks the hash end to end. ## The complete template — a room with a referee A complete, working skeleton of an app with rooms where the server validates every move (the "referee" recipe in salas.txt). The other shapes start from here, with the adaptations at the end. ### index.html ```html My App
Connecting…
``` ### main.css ```css body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; } #players .player { padding: .25rem .5rem; } #players .player.presenter::before { content: "★ "; } #players .player.me { font-weight: bold; } ``` ### client.js ```javascript let isLobby = true; window.onNeblla = (neblla) => { const $ = (id) => document.getElementById(id); $('status').textContent = 'Connected. In: ' + neblla.room.name; $('roomControls').hidden = false; // login is a feature toggle: if it is off for this app the call is refused // (feature_disabled), which is a setting to change, not a bug to code around. $('loginBtn').onclick = () => neblla.auth.login().catch((e) => { $('status').textContent = 'Sign-in is not available in this app.'; console.warn('login refused', e); }); $('logoutBtn').onclick = () => neblla.auth.logout(); $('createRoomBtn').onclick = async () => { // rooms.book reserves the code but does NOT enter; rooms.join puts you in. // The room starts in `gathering` — nothing in server/room.js runs until // room.start() is called (by the presenter here, or by server/gathering.js). const code = await neblla.rooms.book({ length: 5 }); await neblla.rooms.join(code); $('status').textContent = 'Room ' + code + ' — waiting for players'; }; $('startRoomBtn').onclick = () => neblla.room.start(); $('leaveRoomBtn').onclick = () => neblla.room.leave(); $('joinRoomBtn').onclick = () => { const code = $('roomCodeInput').value.trim(); if (code) neblla.rooms.join(code); }; // A mistyped code is the most likely thing to happen. Handle it: without this // listener a failed join looks like nothing happening at all, and there is no // runtime log to debug it with. neblla.rooms.on('joinError', (event) => { $('status').textContent = 'Could not join that room. Check the code.'; console.warn('rooms.join failed', event); }); // The SDK's general error channel. Without it, a spent daily quota just makes // every event stop working with no signal. neblla.app.on('error', (event) => { if (event.code === 'quota_exceeded') { $('status').textContent = 'This app is out of budget for today.'; } }); neblla.room.on('joined', (event) => { isLobby = event.isLobby; $('status').textContent = 'In room: ' + event.room.name; $('leaveRoomBtn').hidden = isLobby; renderPlayers(); if (isLobby) { $('game').innerHTML = ''; } else { // render game board (neblla.state.get() has the state if the game is running) } }); // Authoritative state travels ONLY through state.set → state.on. // Never publish state as a generic message (see servidor.txt). neblla.state.on((state) => { // render(state); }); // Messages from server/room.js (from === 'server') are for one-off // announcements ("wrong answer", "your turn"), never for the state itself. neblla.message.on(({ from, data }) => { if (from !== 'server') return; // if (data.type === 'toast') showToast(data.text); }); neblla.room.on('userJoined', renderPlayers); neblla.room.on('userLeft', renderPlayers); neblla.room.on('publicInfo', renderPlayers); neblla.room.on('presenter', renderPlayers); // Only the presenter may start the room. const syncStart = () => { $('startRoomBtn').hidden = !(neblla.room.me?.isPresenter && !isLobby); }; neblla.room.on('joined', syncStart); neblla.room.on('presenter', syncStart); neblla.room.on('started', () => { $('startRoomBtn').hidden = true; }); neblla.auth.on('login', () => { $('loginBtn').hidden = true; $('logoutBtn').hidden = false; }); neblla.auth.on('logout', () => { $('loginBtn').hidden = false; $('logoutBtn').hidden = true; }); function renderPlayers() { const el = $('players'); el.innerHTML = ''; neblla.room.users.forEach(u => { const div = document.createElement('div'); div.className = 'player' + (u.isPresenter ? ' presenter' : '') + (u.isMe ? ' me' : ''); div.textContent = (u.publicInfo.name || u.id.slice(0, 8)) + (u.isMe ? ' (you)' : ''); el.appendChild(div); }); } }; ``` ### room.js ```javascript // Top-level code. `neblla` is a global. No DOM. No neblla.auth and no neblla.room.me. let gameState = neblla.state.get() || initialState(); neblla.message.on((m) => { if (m.to !== 'server') return; // only what a client sent with message.to('server', …) if (m.data.type === 'action') { gameState = applyAction(gameState, m.user.id, m.data); neblla.state.set(gameState); } }); neblla.room.on('userJoined', () => { if (gameState) neblla.state.set(gameState); }); ``` ### Adaptations Each has its complete recipe, with code, in salas.txt ("Recipes: three shapes of room"). - **Screen + phones**: in `client.js`, branch on `neblla.room.me.isBoard || (!neblla.room.board && neblla.room.me.isPresenter && !isLobby)` — a bare `isPresenter` check is only right while no `board` is pinned, and it moves the host screen to a phone when the presenter is lost. See empezar.txt. - **All at once**: `room.js` is empty. Every peer is equal. `neblla.message.send` for local changes, apply the incoming ones in `neblla.message.on`. - **Solo + save**: `room.js` empty, no rooms. Just `neblla.db.save()` and `neblla.db.data`. ## Every error code, in one place Errors reach you three ways, and knowing which is which saves a lot of guessing. **Promise rejections** come back from the call you made (most of the community and rooms API). **Named events** fire on their own (`neblla.rooms.on('joinError')`, `neblla.room.on('dataError')`, `neblla.room.on('fileError')`, `neblla.auth.on('expired')`, `neblla.app.on('maintenance')`). And the **general `neblla.app.on('error')` event** carries `{ code }` for the cases where the server blocks you and your events would otherwise just stop working: `quota_exceeded` (the daily budget is spent; it resets at 00:00 UTC, so do not retry in a loop) and `app_maintenance`; and `store_unavailable` when a sign-in cannot happen because the app's own database does not answer. Everything else is a rejection code on the call that caused it: - **Calls to the server that do not arrive (network, sleep, deploy):** every SDK call always ends, with an answer or a rejection with a `code`: `offline` (no connection, and what you pressed will not run later: try again), `not_connected` (the connection dropped with the call in flight), `timeout` (no answer in time), `server_error` (a Neblla failure, no internal details) and `store_unavailable` (the store is not answering now: later). A call that ended in `timeout` or `not_connected` may have reached Neblla; the writes that need it are idempotent by `opId`. Server refusals carry all their extras (`max`, `cost`, `expected`…). The SDK repeats `scores.submit` by itself when your server's `check` does not answer (`check_unavailable`: after 3, 10 and 30 s, same `run` and `value`) before telling the game. In tables, accepting again an offer you already accepted returns the `done` offer, not `offer_closed`. In tokens, `neblla.tokens.spend`/`spendOrder` repeat once by themselves with the same `key` after a cut and, if they do not recover, reject with a `code` and the `key` used (repeat with it and nobody is charged twice); with no network, paying rejects `offline` at once and does not run later. In the queue, a call with no answer in 15 s rejects with `queue_timeout`; `take`, `spendOrder`, `markServed` and `refund` repeat once by themselves after reconnecting (the same number, `replayed`). The queue's authority sends the money (delivered, refunds) through an outbox that retries until Neblla answers and survives a page reload; its taps (`next`, `setState`, `soldOut`, `close`…) reject `queue_not_authority` without the command or without a connection; a `remake` with no answer repeats by itself when the connection returns and leaves one sale; and the numbers do not restart at midnight while the queue is open (only a queue forgotten open for more than 20 h starts a new series). In purchases: `shop.buy()` and `cart()` run one at a time per page (pressing the same Buy twice returns the same promise; another product while one is being bought rejects `buy_in_progress`), a server that does not answer in 10 s is `server_down` and the window closes, a window closed before it opened rejects `checkout_closed`, and `shop.consume()` is idempotent (the same `opId` never spends twice). In `neblla.business`, booking, cancelling and the other writes with no network reject `offline` at once and do not run later; reads wait for the session (10 s at most). - **Session and features:** `store_unavailable` (the app's own database does not answer: nobody can sign in, buy or spend until it is back), `login_required` (the call needs a signed-in user), `feature_disabled` (that module is off for the app; the error names it in `module` — a setting to change, never something to work around), `user_banned`, `community_muted`, `user_terminated`. - **Rooms:** `not_in_room`, `not_authorized`, `rooms_data_loss` (a config change would destroy user data — ask the developer before repeating it with `confirmRoomsChange`), `db_bytes_exceeded`. - **Saving (`db.save()`, also on `db.on('error')`):** `save_too_large` (carries `bytes` and `max`), `invalid_save`, `invalid_at`, `login_required`, `save_loop`; `quota_exceeded` is not lost: it waits in the browser. A full store is not an error: what a user already inside saves waits in the queue (`pending`), table rows included. - **Community:** `title_required`, `contentType_required`, `payload_required`, `payload_too_large` (carries `bytes` and `max`), `category_not_allowed` / `content_type_not_allowed` (carry `allowed`), `too_many_tags` (carries `max`, which is 20), `entry_limit_reached`, `moderators_only`, `not_owner`, `entry_not_found`, `parent_not_found`, `already_suspended`, `own_entry`, `invalid_reason` (carries `allowed`), `message_required`, `community_storage_exceeded` (carries `current` and `cap`), `link_not_found`, `rules_declined`, `popup_blocked` (carries `url`). - **Another user's (`db.dataOf`, `db.loadOf`):** `not_visible`, `not_friends`, `user_not_found`, `unknown_table`. - **Trades (`db.offer` and the rest):** `trade_off`, `not_friends`, `self`, `not_owned`, `not_tradable` (carries `table` or `product`), `invalid_offer`, `invalid_amount`, `invalid_expires`, `insufficient_amount`, `too_many_offers`, `offer_not_found`, `offer_expired`, `offer_closed` (carries `status`); on accepting, also `offer_changed`, `too_many_rows`, `already_owned`. - **Tables only Neblla writes and draws (`db.draw`):** `table_read_only` (carries `table`), `unknown_draw`, `no_free_open` (carries `nextAt`), `not_enough_credits` (carries `cost` and `nextFreeAt`), `invalid_pay`, `too_many_rows`, `draw_table_not_read_only` (the table stopped being Neblla's); when declaring them, `invalid_draws` (carries `field`, `draw` and `reason`) and `invalid_draw_name`. - **A deck of each player's own (`tools.deck` with `fromRows`):** `invalid_from_rows`, `table_not_read_only`, `not_owned` (carries `id`), `repeated_card`, `invalid_deck_size` (carries `min` and `max`), `already_brought`, `not_brought`, `not_in_hand`, `deck_empty`. - **Purchases:** `insufficient_amount`, plus the `neblla.shop.buy()` rejections above (`login_required`, `feature_disabled`). - **Inbox:** `communications_full` (carries `cap` and `current`). - **Scores (`neblla.scores`):** `unknown_board`, `runs_per_day` (carries `max`), `data_too_large`, `invalid_period`, `login_required`; a send that does not enter does not reject: it resolves with `{ ok: false, reason }`. - **Media (`neblla.media`, `neblla_media`):** `collection_not_found`; when uploading and ordering, `media_storage_off`, `media_quota_exceeded` (carries `scope`, `used`, `limit`, `needs`), `media_too_large` (carries `max`), `media_type_not_supported`, `media_fetch_failed` (carries `reason`), `collection_exists`, `collection_full`, `collection_not_empty`, `media_not_found`, `invalid_fields`; when reducing, `invalid_resize`, `ids_or_collection_required`; private originals (C230), `media_private_storage_off`, `invalid_public_width`, `not_private`, `product_cannot_unlock`, `login_required`, `not_entitled` (carries `unlockedBy`), `no_credits_unlock_it`, `kind_required` (carries `kinds`), `kind_does_not_unlock`, `not_enough_credits`. - **Shop, units and orders (`neblla.shop`):** `sold_out` (carries `left`), `country_required` (carries `zones`), `country_not_shipped` (carries `countries`); `neblla_create_product` / `neblla_update_product`, `invalid_stock`, `invalid_shipping`; `neblla_orders`, `order_not_found`, `invalid_status`, `invalid_transition`, `tracking_required`, `invalid_tracking_url`. - **Config and plan, from MCP:** `git_conflict` (the app follows a repo and that file changed on GitHub since the last sync), `not_linked`, `foreign_commit`, `unknown_branch`, `no_files`. Two rules worth following whatever the code: never route around `feature_disabled`, and never retry `quota_exceeded`.