@ramme-io/create-app 3.2.0 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -15,15 +15,26 @@ console.log('║ The AI-Native App Builder ║');
15
15
  console.log('║ ║');
16
16
  console.log('╚═══════════════════════════════════════╝\n');
17
17
 
18
- const projectName = process.argv[2];
19
- if (!projectName) {
20
- console.error('❌ Error: Please specify the project directory.');
18
+ // Which starter. `app` (the default) is a web app on the framework; `device`
19
+ // is a Ramme server for boards on your own network — "Ramme local" in the
20
+ // monorepo's docs/superpowers/community-platform-plan.md.
21
+ const TEMPLATES = { app: 'template', device: 'template-device' };
22
+
23
+ const args = process.argv.slice(2);
24
+ const flag = args.indexOf('--template');
25
+ const templateName = flag === -1 ? 'app' : args[flag + 1];
26
+ const projectName = args.filter((_, i) => flag === -1 || (i !== flag && i !== flag + 1))[0];
27
+ if (!projectName || !TEMPLATES[templateName]) {
28
+ if (!TEMPLATES[templateName]) console.error(`❌ Error: No template called "${templateName}". There is: ${Object.keys(TEMPLATES).join(', ')}.`);
29
+ else console.error('❌ Error: Please specify the project directory.');
21
30
  console.log('\n📖 Usage:');
22
- console.log(' npm create @ramme-io/app@latest <project-name>\n');
31
+ console.log(' npm create @ramme-io/app@latest <project-name>');
32
+ // The `--` is npm's: without it npm keeps `--template` for itself.
33
+ console.log(' npm create @ramme-io/app@latest <project-name> -- --template device\n');
23
34
  process.exit(1);
24
35
  }
25
36
 
26
- const templatePath = path.resolve(__dirname, 'template');
37
+ const templatePath = path.resolve(__dirname, TEMPLATES[templateName]);
27
38
  const destinationPath = path.resolve(process.cwd(), projectName);
28
39
 
29
40
  // What the new app calls itself, in package.json and on screen.
@@ -55,16 +66,22 @@ const appSlug =
55
66
  // versions match what was just published, not merely that the build passes —
56
67
  // a stale pin builds fine, it just ships the wrong framework.
57
68
  const RELEASE_VERSIONS = {
58
- '@ramme-io/ui': '^4.1.0',
59
- '@ramme-io/kernel': '^7.0.0',
60
- '@ramme-io/shared': '^3.1.2',
69
+ '@ramme-io/ui': '^5.0.0',
70
+ '@ramme-io/kernel': '^8.0.0',
71
+ '@ramme-io/shared': '^4.0.0',
61
72
  };
62
73
 
63
74
  try {
64
75
  console.log(`\n🚀 Creating new Ramme app in: ${destinationPath}`);
65
76
 
66
- // 1. Copy template
67
- fs.copySync(templatePath, destinationPath);
77
+ // 1. Copy template — never what running it left behind. Inside the monorepo a
78
+ // template has its own node_modules, and the device server writes data.json,
79
+ // which holds that server's token; package.json's `files` keeps both out of
80
+ // the npm tarball, and this keeps them out of a copy made from a checkout.
81
+ const LEFT_BEHIND = /^(node_modules|data\.json(\.tmp)?)$/;
82
+ fs.copySync(templatePath, destinationPath, {
83
+ filter: src => !LEFT_BEHIND.test(path.basename(src)),
84
+ });
68
85
 
69
86
  // 2. Identify package.json (handle renamed source)
70
87
  let targetPkgPath = path.join(destinationPath, 'package.json');
@@ -211,7 +228,7 @@ try {
211
228
  console.log('📋 What\'s Next? (Copy & Paste)\n');
212
229
  console.log(` cd ${projectName}`);
213
230
  console.log(' pnpm install');
214
- console.log(' pnpm run dev\n');
231
+ console.log(templateName === 'device' ? ' pnpm start\n' : ' pnpm run dev\n');
215
232
 
216
233
  console.log('🎨 Happy Creating!\n');
217
234
  console.log('📚 Docs: https://ramme.io/docs');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ramme-io/create-app",
3
- "version": "3.2.0",
3
+ "version": "3.3.1",
4
4
  "description": "The official CLI to create Ramme applications.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -14,6 +14,9 @@
14
14
  "files": [
15
15
  "index.js",
16
16
  "template",
17
+ "template-device",
18
+ "!template-device/node_modules",
19
+ "!template-device/data.json*",
17
20
  "!template/node_modules",
18
21
  "!template/dist",
19
22
  "!template/.turbo",
@@ -1,5 +1,112 @@
1
1
  # ramme-starter
2
2
 
3
+ ## 2.0.25
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [2f995f7]
8
+ - Updated dependencies [1128071]
9
+ - Updated dependencies [0ec373c]
10
+ - Updated dependencies [c945eba]
11
+ - Updated dependencies [0c314cf]
12
+ - Updated dependencies [627f42a]
13
+ - Updated dependencies [b47f4b8]
14
+ - Updated dependencies [46f9a91]
15
+ - Updated dependencies [2494184]
16
+ - Updated dependencies [c1e5b05]
17
+ - Updated dependencies [d1d8c66]
18
+ - Updated dependencies [a6e89cc]
19
+ - Updated dependencies [24c6258]
20
+ - Updated dependencies [a2a516c]
21
+ - Updated dependencies [8a9919e]
22
+ - Updated dependencies [28b8475]
23
+ - Updated dependencies [aa806ca]
24
+ - Updated dependencies [f733861]
25
+ - Updated dependencies [59486f7]
26
+ - Updated dependencies [9a16afd]
27
+ - Updated dependencies [e900e1e]
28
+ - Updated dependencies [f222678]
29
+ - Updated dependencies [956663a]
30
+ - Updated dependencies [4fcd843]
31
+ - Updated dependencies [9d95cf2]
32
+ - @ramme-io/shared@4.0.0
33
+ - @ramme-io/kernel@8.0.0
34
+ - @ramme-io/ui@5.0.0
35
+
36
+ ## 2.0.24
37
+
38
+ ### Patch Changes
39
+
40
+ - Updated dependencies [57ffcf6]
41
+ - Updated dependencies [3f68c51]
42
+ - @ramme-io/shared@3.10.0
43
+ - @ramme-io/kernel@7.8.1
44
+ - @ramme-io/ui@4.2.10
45
+
46
+ ## 2.0.23
47
+
48
+ ### Patch Changes
49
+
50
+ - Updated dependencies [57daaea]
51
+ - @ramme-io/shared@3.9.0
52
+ - @ramme-io/kernel@7.8.0
53
+ - @ramme-io/ui@4.2.9
54
+
55
+ ## 2.0.22
56
+
57
+ ### Patch Changes
58
+
59
+ - Updated dependencies [c47a3dc]
60
+ - Updated dependencies [4d994ec]
61
+ - @ramme-io/shared@3.8.0
62
+ - @ramme-io/kernel@7.7.1
63
+ - @ramme-io/ui@4.2.8
64
+
65
+ ## 2.0.21
66
+
67
+ ### Patch Changes
68
+
69
+ - Updated dependencies [2220f2d]
70
+ - @ramme-io/shared@3.7.0
71
+ - @ramme-io/kernel@7.7.0
72
+ - @ramme-io/ui@4.2.7
73
+
74
+ ## 2.0.20
75
+
76
+ ### Patch Changes
77
+
78
+ - Updated dependencies [64ef780]
79
+ - Updated dependencies [f124573]
80
+ - @ramme-io/shared@3.6.0
81
+ - @ramme-io/kernel@7.6.0
82
+ - @ramme-io/ui@4.2.6
83
+
84
+ ## 2.0.19
85
+
86
+ ### Patch Changes
87
+
88
+ - Updated dependencies [e61017c]
89
+ - Updated dependencies [9c7ec2a]
90
+ - @ramme-io/kernel@7.5.0
91
+
92
+ ## 2.0.18
93
+
94
+ ### Patch Changes
95
+
96
+ - Updated dependencies [b1710ca]
97
+ - @ramme-io/shared@3.5.0
98
+ - @ramme-io/kernel@7.4.0
99
+ - @ramme-io/ui@4.2.5
100
+
101
+ ## 2.0.17
102
+
103
+ ### Patch Changes
104
+
105
+ - Updated dependencies [942892d]
106
+ - @ramme-io/shared@3.4.0
107
+ - @ramme-io/kernel@7.3.2
108
+ - @ramme-io/ui@4.2.4
109
+
3
110
  ## 2.0.16
4
111
 
5
112
  ### Patch Changes
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ramme-starter",
3
3
  "private": true,
4
- "version": "2.0.16",
4
+ "version": "2.0.25",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "vite",
@@ -7,7 +7,7 @@ import {
7
7
  useSpatialStore,
8
8
  useInspectorShortcut,
9
9
  RammeInspector,
10
- AIChatPanel
10
+ AIChatPanel,
11
11
  } from '@ramme-io/kernel';
12
12
  import { APP } from '../config/app.config';
13
13
 
@@ -0,0 +1,20 @@
1
+ # Ramme at home — agent rules
2
+
3
+ This project is a Ramme server for boards on a home network. Read `README.md` first.
4
+
5
+ ## The one rule that matters
6
+
7
+ **A board must not be able to tell this server from ramme.io.** The calls a board makes and the answers it expects are defined in `@ramme-io/shared`: `DEVICE_PROTOCOL`, `DEVICE_POLL_QUERY`, `DevicePollReplySchema`, `DeviceRegistrationSchema` and `DeviceReportSchema`. Change what `server.mjs` does, never what it answers. `pnpm test` checks it, and it must pass before you call a change done.
8
+
9
+ ## Writing apps
10
+
11
+ An app is a JSON document, validated by `AppDocumentSchema` from `@ramme-io/shared`. The server refuses one that does not parse, so validate before sending. Start from `apps/hello.json`, or `apps/probe.json` for a board's own temperature probe (the `board` source: `temperature` and `connected`).
12
+
13
+ Colours are tokens (`background`, `foreground`, `muted`, `accent`, `success`, `warning`, `danger`) or `"R G B"` integers, never hex.
14
+
15
+ ## Never
16
+
17
+ - Add firmware updates here. A board installs firmware only from ramme.io, by design.
18
+ - Commit `data.json`. It holds every board's pairing code and this server's token.
19
+ - Add a dependency for something Node already does. The server uses `node:http` and one JSON file on purpose.
20
+ - Run `npm` or `yarn`. Use `pnpm`.
@@ -0,0 +1,26 @@
1
+ # ramme-home
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [2f995f7]
8
+ - Updated dependencies [1128071]
9
+ - Updated dependencies [0ec373c]
10
+ - Updated dependencies [c945eba]
11
+ - Updated dependencies [627f42a]
12
+ - Updated dependencies [b47f4b8]
13
+ - Updated dependencies [46f9a91]
14
+ - Updated dependencies [2494184]
15
+ - Updated dependencies [c1e5b05]
16
+ - Updated dependencies [d1d8c66]
17
+ - Updated dependencies [a6e89cc]
18
+ - Updated dependencies [a2a516c]
19
+ - Updated dependencies [8a9919e]
20
+ - Updated dependencies [28b8475]
21
+ - Updated dependencies [59486f7]
22
+ - Updated dependencies [e900e1e]
23
+ - Updated dependencies [956663a]
24
+ - Updated dependencies [4fcd843]
25
+ - Updated dependencies [9d95cf2]
26
+ - @ramme-io/shared@4.0.0
@@ -0,0 +1,41 @@
1
+ # Ramme at home
2
+
3
+ Your own Ramme server. Boards on your network register, get their apps and send their readings here instead of ramme.io, and nothing leaves the house.
4
+
5
+ ## Run it
6
+
7
+ ```bash
8
+ pnpm install
9
+ pnpm start
10
+ ```
11
+
12
+ It prints this machine's address, for example `http://192.168.1.20:3000`.
13
+
14
+ ## Point a board at it
15
+
16
+ 1. On the board, tap the Wi-Fi icon in the top corner, then **Add a network**. The board restarts into setup and raises its own network, **Ramme-<board id>**.
17
+ 2. Join that network from your phone. The setup page opens; under **Advanced**, set **Server address** to the address `pnpm start` printed, and save. Leave it empty to go back to ramme.io.
18
+ 3. The board rejoins your Wi-Fi and shows up at `http://localhost:3000` within a minute.
19
+
20
+ Firmware updates still come only from ramme.io, whatever server a board talks to. A home server can send a board apps, never code.
21
+
22
+ ## Send it an app
23
+
24
+ - **From the page:** open `http://localhost:3000`, pick the board, type the code on its screen, paste an app, and press Send. `apps/hello.json` and `apps/probe.json` are examples.
25
+ - **From a coding agent:** the Ramme devkit (`npm install -g @ramme-io/devkit`) talks to this server just as it talks to ramme.io. Set the two values `pnpm start` prints, `RAMME_API_URL` and `RAMME_TOKEN`, and your agent can list your boards, read their sensors and send them apps. For Claude Code:
26
+
27
+ ```bash
28
+ claude mcp add ramme --env RAMME_API_URL=http://localhost:3000 --env RAMME_TOKEN=rmh_… -- npx -y @ramme-io/devkit mcp
29
+ ```
30
+
31
+ ## What is here
32
+
33
+ | file | what it is |
34
+ |---|---|
35
+ | `server.mjs` | the server: the four calls a board makes, your page, and the devkit's three calls |
36
+ | `server.test.mjs` | proves the server answers a board the way ramme.io does (`pnpm test`) |
37
+ | `page.html` | your boards, and a box to send an app |
38
+ | `apps/` | example apps, as JSON |
39
+ | `data.json` | everything it knows, written when it first runs; readable by hand |
40
+
41
+ Photos: put a file in `photos/`, named by its hash, in the board's own format, and an app that names that hash can show it.
@@ -0,0 +1,10 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "hello-home",
4
+ "name": "Hello from home",
5
+ "sources": {},
6
+ "blocks": [
7
+ { "type": "text", "value": { "literal": "Hello" }, "size": "display", "align": "center", "color": "accent" },
8
+ { "type": "text", "value": { "literal": "from the server on your desk" }, "size": "base", "align": "center", "color": "muted" }
9
+ ]
10
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "probe-home",
4
+ "name": "Probe",
5
+ "sources": { "probe": { "kind": "board", "units": "imperial" } },
6
+ "blocks": [
7
+ { "type": "text", "value": { "literal": "Water" }, "size": "lg", "align": "center", "color": "muted" },
8
+ {
9
+ "type": "text",
10
+ "value": { "source": "probe", "field": "temperature" },
11
+ "suffix": "°",
12
+ "size": "display",
13
+ "align": "center",
14
+ "color": "accent",
15
+ "hideWhen": { "value": { "source": "probe", "field": "connected" }, "op": "==", "than": false },
16
+ "rules": [{ "when": { "value": { "source": "probe", "field": "temperature" }, "op": ">", "than": 90 }, "color": "danger" }]
17
+ },
18
+ {
19
+ "type": "text",
20
+ "value": { "literal": "Plug the probe into the IO socket" },
21
+ "size": "base",
22
+ "align": "center",
23
+ "hideWhen": { "value": { "source": "probe", "field": "connected" }, "op": "==", "than": true }
24
+ }
25
+ ]
26
+ }
@@ -0,0 +1,5 @@
1
+ node_modules
2
+
3
+ # Your boards, their pairing codes and this server's token. Keep it off GitHub.
4
+ data.json
5
+ data.json.tmp
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "ramme-home",
3
+ "private": true,
4
+ "version": "0.1.1",
5
+ "type": "module",
6
+ "description": "Your own Ramme server: boards on your network talk to this instead of ramme.io.",
7
+ "scripts": {
8
+ "start": "node server.mjs",
9
+ "test": "vitest run"
10
+ },
11
+ "dependencies": {
12
+ "@ramme-io/shared": "workspace:*"
13
+ },
14
+ "devDependencies": {
15
+ "vitest": "^2.1.9"
16
+ }
17
+ }
@@ -0,0 +1,86 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Ramme at home</title>
7
+ <style>
8
+ :root { color-scheme: light dark; --bg: #fafafa; --fg: #111; --muted: #666; --line: #ddd; --accent: #0d6efd; }
9
+ @media (prefers-color-scheme: dark) { :root { --bg: #111; --fg: #eee; --muted: #999; --line: #333; } }
10
+ body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, sans-serif; }
11
+ main { max-width: 42rem; margin: 0 auto; padding: 1.5rem 1rem 4rem; }
12
+ h1 { font-size: 1.5rem; margin: 0 0 .25rem; }
13
+ p.lead { color: var(--muted); margin: 0 0 1.5rem; }
14
+ ul { list-style: none; padding: 0; margin: 0 0 2rem; border-top: 1px solid var(--line); }
15
+ li { padding: .75rem 0; border-bottom: 1px solid var(--line); display: flex; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
16
+ li small { color: var(--muted); }
17
+ label { display: block; font-weight: 600; margin: 1rem 0 .25rem; }
18
+ select, input, textarea { width: 100%; box-sizing: border-box; font: inherit; font-size: max(16px, 1rem); padding: .6rem; border: 1px solid var(--line); border-radius: .5rem; background: transparent; color: inherit; }
19
+ textarea { min-height: 14rem; font-family: ui-monospace, monospace; }
20
+ button { margin-top: 1rem; min-height: 44px; padding: 0 1.25rem; font: inherit; font-weight: 600; border: 0; border-radius: .5rem; background: var(--accent); color: #fff; }
21
+ #status { margin-top: .75rem; color: var(--muted); }
22
+ </style>
23
+ </head>
24
+ <body>
25
+ <main>
26
+ <h1>Your boards</h1>
27
+ <p class="lead">Boards pointed at this server, and what each is showing.</p>
28
+ <ul id="boards"><li><small>None yet. On a board's setup page, set Server to this machine's address.</small></li></ul>
29
+
30
+ <h1>Send an app</h1>
31
+ <form id="send">
32
+ <label for="board">Board</label>
33
+ <select id="board" required></select>
34
+ <label for="code">The code on its screen</label>
35
+ <input id="code" inputmode="numeric" pattern="\d{4}" maxlength="4" autocomplete="off" required />
36
+ <label for="doc">App (JSON)</label>
37
+ <textarea id="doc" spellcheck="false" required></textarea>
38
+ <button type="submit">Send</button>
39
+ <div id="status" role="status"></div>
40
+ </form>
41
+ </main>
42
+ <script>
43
+ const ago = ms => {
44
+ if (!ms) return 'never';
45
+ const s = Math.round((Date.now() - ms) / 1000);
46
+ return s < 90 ? `${s}s ago` : s < 5400 ? `${Math.round(s / 60)} min ago` : `${Math.round(s / 3600)} h ago`;
47
+ };
48
+ const text = (tag, value) => Object.assign(document.createElement(tag), { textContent: value });
49
+
50
+ async function refresh() {
51
+ const { devices } = await (await fetch('/api/device/list')).json();
52
+ if (!devices.length) return;
53
+ const list = document.getElementById('boards');
54
+ const pick = document.getElementById('board');
55
+ const chosen = pick.value;
56
+ list.replaceChildren(...devices.map(d => {
57
+ const li = document.createElement('li');
58
+ li.append(text('span', d.label || d.deviceId), text('small', `${d.showing || 'nothing sent'} · seen ${ago(d.lastPollAt || d.lastSeenAt)}`));
59
+ return li;
60
+ }));
61
+ pick.replaceChildren(...devices.map(d => Object.assign(document.createElement('option'), { value: d.deviceId, textContent: d.label || d.deviceId })));
62
+ if (chosen) pick.value = chosen;
63
+ }
64
+
65
+ document.getElementById('send').addEventListener('submit', async e => {
66
+ e.preventDefault();
67
+ const status = document.getElementById('status');
68
+ let document_;
69
+ try { document_ = JSON.parse(document.getElementById('doc').value); }
70
+ catch { status.textContent = 'That is not valid JSON.'; return; }
71
+ const res = await fetch('/api/device/send', {
72
+ method: 'POST',
73
+ headers: { 'content-type': 'application/json' },
74
+ body: JSON.stringify({ deviceId: document.getElementById('board').value, code: document.getElementById('code').value, document: document_ }),
75
+ });
76
+ const out = await res.json();
77
+ status.textContent = res.ok ? `Sent. The board shows it on its next check-in (revision ${out.revision}).` : (out.message || out.error);
78
+ refresh();
79
+ });
80
+
81
+ fetch('/apps/hello.json').then(r => r.ok ? r.text() : '').then(t => { const d = document.getElementById('doc'); if (!d.value) d.value = t; });
82
+ refresh();
83
+ setInterval(refresh, 10000);
84
+ </script>
85
+ </body>
86
+ </html>
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Your own Ramme server: boards on your network talk to this instead of ramme.io.
3
+ *
4
+ * Point a board at it from the board's setup page ("Server", e.g.
5
+ * http://192.168.1.20:3000) and it registers, asks for its app, sends its
6
+ * readings and fetches photos here. Nothing leaves your network.
7
+ *
8
+ * Two kinds of caller:
9
+ *
10
+ * boards the four calls in DEVICE_PROTOCOL (@ramme-io/shared) — the same
11
+ * calls, answered the same way, as ramme.io. server.test.mjs holds
12
+ * this file to them.
13
+ * you the page at / (your boards, and a box to send an app), and the
14
+ * three calls the Ramme devkit makes — list, parts, send — so a
15
+ * coding agent can write an app and put it on a board.
16
+ *
17
+ * Who may send: anyone who can read the board's pairing code off its screen
18
+ * (the page asks for it), or anyone holding this server's token (the devkit).
19
+ * There are no accounts. Firmware updates are not here on purpose: a board
20
+ * takes firmware only from ramme.io, whatever server it talks to.
21
+ *
22
+ * Everything is kept in one JSON file (data.json by default), readable and
23
+ * editable by hand while the server is stopped.
24
+ */
25
+ import { createServer } from 'node:http';
26
+ import { randomBytes } from 'node:crypto';
27
+ import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
28
+ import { networkInterfaces } from 'node:os';
29
+ import { dirname, join } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
31
+ import {
32
+ AppDocumentSchema,
33
+ DEVICE_PROTOCOL,
34
+ DeviceIdSchema,
35
+ DevicePollReplySchema,
36
+ DeviceRegistrationSchema,
37
+ DeviceReportSchema,
38
+ } from '@ramme-io/shared';
39
+
40
+ const HERE = dirname(fileURLToPath(import.meta.url));
41
+ const MAX_BODY = 64 * 1024;
42
+
43
+ /** A board's readings as Signals — the same mapping as deviceReadingsToSignals in @ramme-io/kernel. */
44
+ const toSignals = (deviceId, readings, receivedAt) =>
45
+ readings.map(r => ({
46
+ id: `${deviceId}:${r.key}`,
47
+ source: 'http',
48
+ domain: 'environment',
49
+ key: r.key,
50
+ value: r.value,
51
+ ...(r.unit ? { unit: r.unit } : {}),
52
+ // The board's clock only when it has plainly been set.
53
+ timestamp: r.at !== undefined && r.at >= Date.UTC(2024, 0, 1) && r.at <= receivedAt + 86_400_000 ? r.at : receivedAt,
54
+ }));
55
+
56
+ const emptyData = () => ({ token: `rmh_${randomBytes(18).toString('base64url')}`, boards: {} });
57
+
58
+ /**
59
+ * The store: one object in memory, written whole to `file` after each change.
60
+ * Written to a temporary file and renamed, so a crash mid-write cannot leave
61
+ * half a file behind.
62
+ */
63
+ const openStore = file => {
64
+ const data = file && existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : emptyData();
65
+ data.boards ??= {};
66
+ data.token ??= emptyData().token;
67
+ const save = () => {
68
+ if (!file) return;
69
+ writeFileSync(`${file}.tmp`, JSON.stringify(data, null, 2));
70
+ renameSync(`${file}.tmp`, file);
71
+ };
72
+ save();
73
+ return { data, save, board: id => (data.boards[id] ??= { deviceId: id }) };
74
+ };
75
+
76
+ const json = (status, body) => ({ status, body: body === undefined ? undefined : JSON.stringify(body), type: 'application/json' });
77
+
78
+ /**
79
+ * The server's logic, as a function from a request to an answer, so a test can
80
+ * call it without opening a port. `now` is injectable for the same reason.
81
+ */
82
+ export const createHandler = ({ file = join(HERE, 'data.json'), photos = join(HERE, 'photos'), now = () => Date.now() } = {}) => {
83
+ const store = openStore(file);
84
+ const page = () => readFileSync(join(HERE, 'page.html'), 'utf8');
85
+
86
+ const authorised = (headers, deviceId, code) => {
87
+ if (headers.authorization === `Bearer ${store.data.token}`) return true;
88
+ const board = store.data.boards[deviceId];
89
+ return Boolean(board?.code && code && String(code) === board.code);
90
+ };
91
+
92
+ const routes = {
93
+ // ── what boards call ─────────────────────────────────────────────────────
94
+ [`POST ${DEVICE_PROTOCOL.register.path}`]: ({ body }) => {
95
+ const parsed = DeviceRegistrationSchema.safeParse(body);
96
+ if (!parsed.success) return json(400, { error: 'BAD_REGISTRATION' });
97
+ const { deviceId, code, version, ...vitals } = parsed.data;
98
+ const board = store.board(deviceId);
99
+ Object.assign(board, { code, version, lastSeenAt: now(), vitals });
100
+ store.save();
101
+ return json(200, { ok: true });
102
+ },
103
+
104
+ [`GET ${DEVICE_PROTOCOL.poll.path}`]: ({ query }) => {
105
+ const id = DeviceIdSchema.safeParse(query.get('id'));
106
+ if (!id.success) return json(400, { error: 'BAD_DEVICE_ID' });
107
+ const since = Number(query.get('since') ?? 0);
108
+ const board = store.board(id.data);
109
+ board.lastPollAt = now();
110
+ const v = query.get('v');
111
+ if (v) board.version = v;
112
+ const rot = query.get('rot');
113
+ if (rot && /^[0-3]$/.test(rot)) board.rotation = Number(rot);
114
+ store.save();
115
+
116
+ const app = board.app;
117
+ if (!app) return { status: 204 };
118
+ if (Number.isFinite(since) && app.revision <= since) return { status: 304 };
119
+ // Checked on the way out as well as in: a hand-edited data.json must not
120
+ // send a board something it cannot read.
121
+ const reply = DevicePollReplySchema.safeParse({ revision: app.revision, sentAt: app.sentAt, document: app.document });
122
+ return reply.success ? json(200, reply.data) : json(500, { error: 'STORED_APP_INVALID' });
123
+ },
124
+
125
+ [`POST ${DEVICE_PROTOCOL.report.path}`]: ({ query, body }) => {
126
+ const id = DeviceIdSchema.safeParse(query.get('id'));
127
+ if (!id.success) return json(400, { error: 'BAD_DEVICE_ID' });
128
+ const report = DeviceReportSchema.safeParse(body);
129
+ if (!report.success) return json(400, { error: 'BAD_REPORT' });
130
+ const board = store.board(id.data);
131
+ board.readings = toSignals(id.data, report.data.readings, now());
132
+ store.save();
133
+ return json(202, { received: board.readings.length });
134
+ },
135
+
136
+ [`GET ${DEVICE_PROTOCOL.photo.path}`]: ({ query }) => {
137
+ // A photo is a file in photos/ named by its hash, in the board's own
138
+ // format. Only one an app on the board names, as on ramme.io.
139
+ const id = DeviceIdSchema.safeParse(query.get('id'));
140
+ const hash = query.get('hash') ?? '';
141
+ if (!id.success || !/^[0-9a-f]{64}$/.test(hash)) return json(400, { error: 'BAD_REQUEST' });
142
+ const named = JSON.stringify(store.data.boards[id.data]?.app?.document ?? {}).includes(hash);
143
+ const path = join(photos, hash);
144
+ if (!named || !existsSync(path)) return json(404, { error: 'NOT_FOUND' });
145
+ return { status: 200, bytes: readFileSync(path), type: 'application/octet-stream' };
146
+ },
147
+
148
+ // ── what you call: the page and the devkit ───────────────────────────────
149
+ 'GET /': () => ({ status: 200, body: page(), type: 'text/html; charset=utf-8' }),
150
+
151
+ 'GET /api/device/list': () =>
152
+ json(200, {
153
+ devices: Object.values(store.data.boards).map(b => ({
154
+ deviceId: b.deviceId,
155
+ ...(b.label ? { label: b.label } : {}),
156
+ lastSeenAt: b.lastSeenAt ?? 0,
157
+ ...(b.lastPollAt ? { lastPollAt: b.lastPollAt } : {}),
158
+ version: b.version,
159
+ showing: b.app?.document?.name,
160
+ })),
161
+ }),
162
+
163
+ 'GET /api/device/vitals': ({ query }) => {
164
+ const board = store.data.boards[query.get('id') ?? ''];
165
+ if (!board) return json(404, { error: 'NOT_FOUND' });
166
+ return json(200, { vitals: board.vitals ?? {}, readings: board.readings ?? [] });
167
+ },
168
+
169
+ 'POST /api/device/send': ({ headers, body }) => {
170
+ const id = DeviceIdSchema.safeParse(body.deviceId);
171
+ if (!id.success) return json(400, { error: 'BAD_DEVICE_ID' });
172
+ if (!authorised(headers, id.data, body.code)) {
173
+ return json(403, { error: 'NOT_ALLOWED', message: "Give the code on the board's screen, or this server's token." });
174
+ }
175
+ const doc = AppDocumentSchema.safeParse(body.document);
176
+ if (!doc.success) {
177
+ return json(400, { error: 'BAD_DOCUMENT', message: doc.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ') });
178
+ }
179
+ const board = store.board(id.data);
180
+ board.app = { revision: (board.app?.revision ?? 0) + 1, sentAt: now(), document: doc.data };
181
+ store.save();
182
+ return json(200, { revision: board.app.revision });
183
+ },
184
+ };
185
+
186
+ /** One request in, one answer out. `body` is already parsed JSON. */
187
+ return ({ method, url, headers = {}, body = {} }) => {
188
+ const u = new URL(url, 'http://localhost');
189
+ // The example apps, so the page can start you off with one.
190
+ const example = method === 'GET' && /^\/apps\/([a-z0-9-]+)\.json$/.exec(u.pathname);
191
+ if (example) {
192
+ const path = join(HERE, 'apps', `${example[1]}.json`);
193
+ return existsSync(path) ? { status: 200, body: readFileSync(path, 'utf8'), type: 'application/json' } : json(404, { error: 'NOT_FOUND' });
194
+ }
195
+ const route = routes[`${method} ${u.pathname}`];
196
+ if (!route) return json(404, { error: 'NOT_FOUND' });
197
+ return route({ query: u.searchParams, headers, body: body && typeof body === 'object' ? body : {} });
198
+ };
199
+ };
200
+
201
+ /** The handler on a real port. */
202
+ export const startServer = ({ port = Number(process.env.PORT ?? 3000), ...options } = {}) => {
203
+ const handle = createHandler(options);
204
+ const server = createServer((req, res) => {
205
+ const chunks = [];
206
+ let size = 0;
207
+ req.on('data', c => {
208
+ size += c.length;
209
+ if (size > MAX_BODY) req.destroy();
210
+ else chunks.push(c);
211
+ });
212
+ req.on('end', () => {
213
+ let body = {};
214
+ try {
215
+ body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
216
+ } catch {
217
+ // Left empty: each route answers a missing body with its own 400.
218
+ }
219
+ const out = handle({ method: req.method, url: req.url, headers: req.headers, body });
220
+ res.writeHead(out.status, out.type && out.status !== 204 && out.status !== 304 ? { 'content-type': out.type } : {});
221
+ res.end(out.bytes ?? out.body);
222
+ });
223
+ });
224
+ return new Promise(resolve => server.listen(port, '0.0.0.0', () => resolve(server)));
225
+ };
226
+
227
+ /** This machine's addresses on the local network: what to type on a board. */
228
+ const lanAddresses = () =>
229
+ Object.values(networkInterfaces())
230
+ .flat()
231
+ .filter(a => a && a.family === 'IPv4' && !a.internal)
232
+ .map(a => a.address);
233
+
234
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
235
+ const server = await startServer();
236
+ const { port } = server.address();
237
+ const token = JSON.parse(readFileSync(join(HERE, 'data.json'), 'utf8')).token;
238
+ console.log(`\nRamme is running on port ${port}.\n`);
239
+ for (const ip of lanAddresses()) console.log(` On a board's setup page, set Server to: http://${ip}:${port}`);
240
+ console.log(` Your boards, in a browser: http://localhost:${port}`);
241
+ console.log(`\n For the devkit: RAMME_API_URL=http://localhost:${port} RAMME_TOKEN=${token}\n`);
242
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * This server answers a board the way ramme.io does.
3
+ *
4
+ * A board cannot tell which server it is talking to, and must not need to:
5
+ * the same firmware runs against both. So these hold the server to the
6
+ * protocol in @ramme-io/shared — the same schemas ramme.io's own routes are
7
+ * checked against — rather than to what this file happens to return. If you
8
+ * change server.mjs, keep these passing and a board will keep working.
9
+ */
10
+ import { describe, it, expect, beforeEach } from 'vitest';
11
+ import { mkdtempSync, readFileSync, readdirSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { AppDocumentSchema, DEVICE_PROTOCOL, DevicePollReplySchema } from '@ramme-io/shared';
15
+ import { createHandler } from './server.mjs';
16
+
17
+ const ID = 'A7K2M9QP';
18
+ const CODE = '4821';
19
+ const HELLO = JSON.parse(readFileSync(new URL('./apps/hello.json', import.meta.url), 'utf8'));
20
+
21
+ let handle;
22
+ let file;
23
+ let clock;
24
+
25
+ beforeEach(() => {
26
+ file = join(mkdtempSync(join(tmpdir(), 'ramme-home-')), 'data.json');
27
+ clock = 1_800_000_000_000;
28
+ handle = createHandler({ file, now: () => clock });
29
+ });
30
+
31
+ const call = (method, url, body, headers = {}) => {
32
+ const out = handle({ method, url, body, headers });
33
+ return { ...out, json: out.body ? JSON.parse(out.body) : undefined };
34
+ };
35
+ const register = () =>
36
+ call('POST', DEVICE_PROTOCOL.register.path, { deviceId: ID, code: CODE, version: '2026-10-30+afe8999', board: 'freenove-esp32s3-2.8' });
37
+ const poll = since => call('GET', `${DEVICE_PROTOCOL.poll.path}?id=${ID}&since=${since}&v=2026-10-30%2Bafe8999&sh=1&rot=2`);
38
+ const send = (body, headers) => call('POST', '/api/device/send', { deviceId: ID, document: HELLO, ...body }, headers);
39
+
40
+ describe('a board', () => {
41
+ it('registers', () => {
42
+ expect(register().status).toBe(200);
43
+ expect(call('POST', DEVICE_PROTOCOL.register.path, { deviceId: 'nope' }).status).toBe(400);
44
+ });
45
+
46
+ it('hears 204 before anything is sent, then the app, then 304', () => {
47
+ register();
48
+ const none = poll(0);
49
+ expect(none.status).toBe(204);
50
+ expect(none.body).toBeUndefined();
51
+ expect(send({ code: CODE }).status).toBe(200);
52
+ const first = poll(0);
53
+ expect(first.status).toBe(200);
54
+ expect(DevicePollReplySchema.safeParse(first.json).success).toBe(true);
55
+ expect(first.json).toMatchObject({ revision: 1, document: { id: 'hello-home' } });
56
+ const current = poll(1);
57
+ expect(current.status).toBe(304);
58
+ expect(current.body).toBeUndefined();
59
+ });
60
+
61
+ it('reports readings, which come back as Signals', () => {
62
+ register();
63
+ const r = call('POST', `${DEVICE_PROTOCOL.report.path}?id=${ID}`, { readings: [{ key: 'temperature', value: 21.5, unit: '°C' }] });
64
+ expect(r).toMatchObject({ status: 202, json: { received: 1 } });
65
+ const parts = call('GET', `/api/device/vitals?id=${ID}`).json;
66
+ expect(parts.readings[0]).toMatchObject({ id: `${ID}:temperature`, source: 'http', value: 21.5, timestamp: clock });
67
+ });
68
+
69
+ it('gets only photos an app on it names', () => {
70
+ register();
71
+ const hash = 'a'.repeat(64);
72
+ expect(call('GET', `${DEVICE_PROTOCOL.photo.path}?id=${ID}&hash=${hash}`).status).toBe(404);
73
+ expect(call('GET', `${DEVICE_PROTOCOL.photo.path}?id=${ID}&hash=nope`).status).toBe(400);
74
+ });
75
+ });
76
+
77
+ describe('sending', () => {
78
+ it('needs the code on the screen, or the token', () => {
79
+ register();
80
+ expect(send({ code: '0000' }).status).toBe(403);
81
+ expect(send({}).status).toBe(403);
82
+ const { token } = JSON.parse(readFileSync(file, 'utf8'));
83
+ expect(send({}, { authorization: `Bearer ${token}` }).status).toBe(200);
84
+ });
85
+
86
+ it('refuses an app a board could not draw', () => {
87
+ register();
88
+ const r = send({ code: CODE, document: { ...HELLO, blocks: [] } });
89
+ expect(r).toMatchObject({ status: 400, json: { error: 'BAD_DOCUMENT' } });
90
+ });
91
+
92
+ it('survives a restart', () => {
93
+ register();
94
+ send({ code: CODE });
95
+ handle = createHandler({ file, now: () => clock });
96
+ expect(poll(0).json.revision).toBe(1);
97
+ });
98
+ });
99
+
100
+ describe('the devkit', () => {
101
+ it('lists boards without their codes', () => {
102
+ register();
103
+ const { devices } = call('GET', '/api/device/list').json;
104
+ expect(devices).toEqual([expect.objectContaining({ deviceId: ID, lastSeenAt: clock })]);
105
+ expect(JSON.stringify(devices)).not.toContain(CODE);
106
+ });
107
+ });
108
+
109
+ describe('the example apps', () => {
110
+ for (const name of readdirSync(new URL('./apps/', import.meta.url))) {
111
+ it(`${name} is an app a board can draw`, () => {
112
+ const doc = JSON.parse(readFileSync(new URL(`./apps/${name}`, import.meta.url), 'utf8'));
113
+ const parsed = AppDocumentSchema.safeParse(doc);
114
+ expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
115
+ });
116
+ }
117
+ });