Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246// The desktop app's sidecar (app/sidecar/server.js), driven over HTTP the way// the page drives it, against the mock cloud.import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { spawn } from 'node:child_process';import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync, readdirSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, dirname } from 'node:path';import { fileURLToPath } from 'node:url';import { startCloudServer } from './helpers/cloud-server.js';import { PageEditor, makeLine, Pen, PenColor, readTree, pagePaint } from '../lib/index.js';
const here = dirname(fileURLToPath(import.meta.url));const SERVER = join(here, '..', 'app', 'sidecar', 'server.js');const TOKEN = 'test-token-123';
let cloud, dir, child, origin, logs = '';
async function freePort () { const { createServer } = await import('node:net'); return new Promise((resolve) => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); }); });}
before(async () => { cloud = await startCloudServer(); dir = mkdtempSync(join(tmpdir(), 'notable-app-')); const port = await freePort(); origin = `http://127.0.0.1:${port}`; child = spawn(process.execPath, [SERVER], { env: { ...process.env, NOTABLE_APP_PORT: String(port), NOTABLE_APP_TOKEN: TOKEN, NOTABLE_CONFIG: join(dir, 'config', 'cloud.json'), NOTABLE_CACHE: join(dir, 'cache'), NOTABLE_CLOUD_HOST: cloud.url, }, stdio: ['ignore', 'pipe', 'pipe'], }); child.stdout.on('data', (d) => { logs += d; }); child.stderr.on('data', (d) => { logs += d; }); const deadline = Date.now() + 15000; while (Date.now() < deadline) { try { const res = await fetch(`${origin}/health`); if (res.ok) return; } catch { /* not up yet */ } await new Promise(r => setTimeout(r, 100)); } throw new Error(`sidecar did not come up:\n${logs}`);});
after(async () => { child?.kill(); await cloud?.close(); rmSync(dir, { recursive: true, force: true });});
const headers = { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' };async function post (path, body = {}) { const res = await fetch(`${origin}${path}`, { method: 'POST', headers, body: JSON.stringify(body) }); const data = await res.json(); if (!res.ok) { const err = new Error(data.error); err.status = res.status; err.name = data.name; throw err; } return data;}async function getBytes (path) { const res = await fetch(`${origin}${path}`, { headers: { authorization: `Bearer ${TOKEN}` } }); if (res.status === 204) return null; assert.ok(res.ok, `${path}: ${res.status}`); return { type: res.headers.get('content-type'), data: new Uint8Array(await res.arrayBuffer()) };}async function put (path, data, type = 'application/octet-stream') { const res = await fetch(`${origin}${path}`, { method: 'PUT', headers: { authorization: `Bearer ${TOKEN}`, 'content-type': type }, body: data }); const json = await res.json(); assert.ok(res.ok, `${path}: ${res.status} ${json.error}`); return json;}
const stroke = () => makeLine({ tool: Pen.FINELINER_2, color: PenColor.BLUE, thickness: 2, points: Array.from({ length: 10 }, (_, i) => ({ x: i * 20, y: 400 + i, pressure: 150, width: 8 })) });
let folder, notebook, page0, pdf, authorUuid;
test('health is open; everything else needs the token', async () => { const res = await fetch(`${origin}/status`, { method: 'POST' }); assert.equal(res.status, 401); const nope = await fetch(`${origin}/nope`, { method: 'POST', headers, body: '{}' }); assert.equal(nope.status, 404);});
test('pairing and status', async () => { let s = await post('/status'); assert.equal(s.loggedIn, false); assert.match(s.settings.authorUuid, /^[0-9a-f-]{36}$/); authorUuid = s.settings.authorUuid; await assert.rejects(post('/login', { code: 'nope' }), /8 characters|code/i); s = await post('/login', { code: cloud.code }); assert.equal(s.loggedIn, true); assert.equal(s.user.email, 'robin@example.com'); assert.ok(existsSync(join(dir, 'config', 'cloud.json'))); assert.ok(existsSync(join(dir, 'config', 'app.json'))); const tree = await post('/tree'); assert.deepEqual(tree.docs, []); const settings = await post('/settings', { patch: { view: 'list', authorUuid: 'not-allowed' } }); assert.equal(settings.view, 'list'); assert.equal(settings.authorUuid, authorUuid);});
test('folders and notebooks are made, listed and described', async () => { ({ doc: folder } = await post('/folder', { name: 'Work', parent: '' })); assert.equal(folder.isFolder, true); ({ doc: notebook } = await post('/notebook', { name: 'Notes', parent: folder.id, template: 'P Grid medium' })); assert.equal(notebook.parent, folder.id); const tree = await post('/tree'); const nb = tree.docs.find(d => d.id === notebook.id); assert.equal(nb.fileType, 'notebook'); assert.equal(nb.pageCount, 1); assert.equal(nb.path, 'Work/Notes'); assert.equal(nb.cover, null); const info = await post('/doc', { id: notebook.id }); assert.equal(info.fileType, 'notebook'); assert.equal(info.pages.length, 1); page0 = info.pages[0]; assert.equal(page0.hasRm, true); assert.equal(page0.template, 'P Grid medium'); assert.deepEqual(info.author, { uuid: authorUuid, index: 1 }); assert.deepEqual(info.authors, [{ index: 1, uuid: authorUuid }]);});
test('a page round-trips through the editor and the thumbnail is kept', async () => { const got = await getBytes(`/doc/${notebook.id}/page/${page0.id}`); assert.equal(got.type, 'application/octet-stream'); const editor = PageEditor.parse(got.data); assert.equal(editor.strokes.length, 0); const author = editor.authorIndex(authorUuid, { preferred: 1 }); assert.equal(author, 1); const key = editor.addLine(stroke(), { author }); const before = (await post('/tree')).docs.find(d => d.id === notebook.id).hash; const { doc } = await put(`/doc/${notebook.id}/page/${page0.id}`, editor.write()); assert.notEqual(doc.hash, before); const again = PageEditor.parse((await getBytes(`/doc/${notebook.id}/page/${page0.id}`)).data); assert.deepEqual(again.strokes.map(s => s.key), [key]); assert.ok(pagePaint(readTree(again.write())).items.some(i => i.kind === 'segment' && i.item === key)); const info = await post('/doc', { id: notebook.id }); assert.ok(Number(info.pages[0].modified) > 0); assert.equal(info.content.sizeInBytes, String(again.write().length)); assert.equal(await getBytes(`/doc/${notebook.id}/thumbnail/${page0.id}`), null); const png = new Uint8Array([0x89, 0x50, 0x4E, 0x47, 1, 2, 3]); await put(`/doc/${notebook.id}/thumbnail/${page0.id}`, png, 'image/png'); const thumb = await getBytes(`/doc/${notebook.id}/thumbnail/${page0.id}`); assert.equal(thumb.type, 'image/png'); assert.deepEqual([...thumb.data], [...png]); const tree = await post('/tree'); assert.equal(tree.docs.find(d => d.id === notebook.id).cover, page0.id);});
test('pages are added after the current one, re-templated and removed', async () => { const { pageId: p1 } = await post('/doc/add-page', { id: notebook.id, after: page0.id }); const { pageId: pMid } = await post('/doc/add-page', { id: notebook.id, after: page0.id, template: 'Blank' }); let info = await post('/doc', { id: notebook.id }); assert.deepEqual(info.pages.map(p => p.id), [page0.id, pMid, p1]); assert.equal(info.pages[1].template, 'Blank'); assert.equal(info.pages[2].template, 'P Grid medium'); // inherited from the page before it assert.ok(info.pages.every(p => p.hasRm)); await post('/doc/template', { id: notebook.id, pageId: pMid, template: 'P Lines medium' }); info = await post('/doc', { id: notebook.id }); assert.equal(info.pages[1].template, 'P Lines medium'); await post('/doc/remove-page', { id: notebook.id, pageId: pMid }); info = await post('/doc', { id: notebook.id }); assert.deepEqual(info.pages.map(p => p.id), [page0.id, p1]); assert.equal(info.content.pageCount, 2); assert.ok(!info.files.includes(`${notebook.id}/${pMid}.rm`)); assert.equal(await getBytes(`/doc/${notebook.id}/page/${pMid}`), null); await assert.rejects(post('/doc/remove-page', { id: notebook.id, pageId: 'nope' }), (e) => e.status === 404); const tree = await post('/tree'); assert.equal(tree.docs.find(d => d.id === notebook.id).pageCount, 2);});
test('PDFs upload from disk and are replaced in place', async () => { const path = join(dir, 'Paper.pdf'); writeFileSync(path, '%PDF-1.4\n%fake one\n'); const { docs } = await post('/upload', { paths: [path], parent: folder.id }); pdf = docs[0]; assert.equal(pdf.name, 'Paper'); const tree = await post('/tree'); assert.equal(tree.docs.find(d => d.id === pdf.id).fileType, 'pdf'); const got = await getBytes(`/doc/${pdf.id}/file/pdf`); assert.equal(got.type, 'application/pdf'); assert.equal(new TextDecoder().decode(got.data), '%PDF-1.4\n%fake one\n'); await put(`/doc/${pdf.id}/pdf`, new TextEncoder().encode('%PDF-1.4\n%annotated\n'), 'application/pdf'); assert.equal(new TextDecoder().decode((await getBytes(`/doc/${pdf.id}/file/pdf`)).data), '%PDF-1.4\n%annotated\n'); const info = await post('/doc', { id: pdf.id }); assert.equal(info.fileType, 'pdf'); assert.equal(info.pages.length, 0); assert.equal(await getBytes(`/doc/${pdf.id}/file/epub`), null);});
test('organising: rename, move, trash, restore, purge', async () => { const { doc } = await post('/rename', { id: pdf.id, name: 'Paper, read' }); assert.equal(doc.name, 'Paper, read'); const { docs: moved } = await post('/move', { ids: [pdf.id], parent: '' }); assert.equal(moved[0].parent, ''); const { docs: trashed } = await post('/trash', { ids: [pdf.id] }); assert.equal(trashed[0].trashed, true); assert.equal(trashed[0].path, 'trash/Paper, read'); const { docs: restored } = await post('/restore', { ids: [pdf.id], parent: folder.id }); assert.equal(restored[0].parent, folder.id); const { doc: other } = await post('/notebook', { name: 'Scratch', parent: '' }); const { docs: purged } = await post('/purge', { ids: [other.id] }); assert.deepEqual(purged.map(d => d.id), [other.id]); assert.ok(!(await post('/tree')).docs.some(d => d.id === other.id)); await assert.rejects(post('/move', { ids: [folder.id], parent: folder.id }), /into itself/);});
test('export, download and the mirror write to disk', async () => { const svgPath = join(dir, 'out', 'notes.svg'); const { files } = await post('/export', { id: notebook.id, format: 'svg', path: svgPath }); assert.equal(files.length, 2); // one per page, numbered assert.ok(files.every(f => /notes-p0[12]\.svg$/.test(f)), files.join(', ')); assert.match(readFileSync(files[0], 'utf8'), /<svg/); const mdPath = join(dir, 'out', 'notes.md'); await assert.rejects(post('/export', { id: notebook.id, format: 'markdown', path: mdPath }), /nothing to export/); // handwriting only await assert.rejects(post('/export', { id: pdf.id, format: 'pdf', path: join(dir, 'out', 'x.pdf') }), /nothing to export/); const dl = await post('/download', { id: notebook.id, dir: join(dir, 'dl') }); assert.ok(dl.files.some(f => f.endsWith(`${notebook.id}.content`))); const res = await fetch(`${origin}/sync`, { method: 'POST', headers, body: JSON.stringify({ dir: join(dir, 'mirror'), formats: ['markdown', 'svg'], raw: true, trash: false, prune: true, dryRun: false }) }); assert.equal(res.headers.get('content-type'), 'application/x-ndjson'); const lines = (await res.text()).trim().split('\n').map(l => JSON.parse(l)); const summary = lines.at(-1).summary; assert.ok(summary, JSON.stringify(lines)); assert.equal(summary.downloaded, 2); assert.ok(lines.some(l => l.event?.type === 'download' && l.event.doc.name === 'Notes')); assert.ok(existsSync(join(dir, 'mirror', 'Work', 'Notes.svg')) || readdirSync(join(dir, 'mirror', 'Work')).some(f => /^Notes-p\d+\.svg$/.test(f))); const settings = await post('/settings'); assert.equal(settings.syncDir, join(dir, 'mirror')); assert.deepEqual(settings.syncFormats, ['markdown', 'svg']);});
test('logging out forgets the pairing', async () => { const s = await post('/logout'); assert.equal(s.loggedIn, false); await assert.rejects(post('/tree'), (e) => e.status === 401);});