first commit
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s
This commit is contained in:
commit
6fc0a01c56
51 changed files with 11319 additions and 0 deletions
176
tests/api.test.js
Normal file
176
tests/api.test.js
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createApp } from "../server/app.js";
|
||||
import { openDatabase } from "../server/db.js";
|
||||
import { checkPassword, hashPassword } from "../server/auth.js";
|
||||
import { emptyNutrients } from "../shared/domain.js";
|
||||
|
||||
const password = "test-only-password-123";
|
||||
const origin = "http://localhost:3000";
|
||||
async function fixture(t, secureCookies = false) {
|
||||
const store = openDatabase(":memory:");
|
||||
const app = createApp({
|
||||
store,
|
||||
username: "test",
|
||||
passwordHash: hashPassword(password),
|
||||
origin,
|
||||
secureCookies,
|
||||
dist: ".local/nonexistent",
|
||||
});
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
const base = `http://127.0.0.1:${server.address().port}/api`;
|
||||
t.after(
|
||||
() =>
|
||||
new Promise((resolve) =>
|
||||
server.close(() => {
|
||||
store.close();
|
||||
resolve();
|
||||
}),
|
||||
),
|
||||
);
|
||||
const request = (path, body, cookie = "", customHeaders = {}) =>
|
||||
fetch(base + path, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: origin,
|
||||
"X-Calio-Request": "1",
|
||||
Cookie: cookie,
|
||||
...customHeaders,
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const signIn = async () => {
|
||||
const response = await request("/login", { username: "test", password });
|
||||
assert.equal(response.status, 200);
|
||||
return response.headers.get("set-cookie").split(";")[0];
|
||||
};
|
||||
return { store, request, signIn };
|
||||
}
|
||||
test("passwords use salted scrypt hashes and reject incorrect values", () => {
|
||||
const hash = hashPassword(password);
|
||||
assert.notEqual(hashPassword(password), hash);
|
||||
assert.ok(checkPassword(password, hash));
|
||||
assert.equal(checkPassword("wrong", hash), false);
|
||||
assert.equal(checkPassword(password, "garbage"), false);
|
||||
});
|
||||
test("journal endpoints require authentication and never allow cross-origin writes", async (t) => {
|
||||
const { request, signIn } = await fixture(t);
|
||||
assert.equal((await request("/records")).status, 401);
|
||||
assert.equal((await request("/sync", { records: [] })).status, 401);
|
||||
const cookie = await signIn();
|
||||
assert.equal(
|
||||
(
|
||||
await request("/sync", { records: [] }, cookie, {
|
||||
Origin: "https://evil.example",
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [] }, cookie, { "X-Calio-Request": "" }))
|
||||
.status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await request("/records", undefined, cookie)).status, 200);
|
||||
assert.equal(
|
||||
(await request("/records", undefined, cookie)).headers.get("cache-control"),
|
||||
"no-store",
|
||||
);
|
||||
});
|
||||
test("invalid credentials, schema errors, invalid clocks and oversized bodies are rejected", async (t) => {
|
||||
const { request, signIn } = await fixture(t);
|
||||
assert.equal(
|
||||
(await request("/login", { username: "test", password: "wrong" })).status,
|
||||
401,
|
||||
);
|
||||
const cookie = await signIn();
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [{ id: "bad" }] }, cookie)).status,
|
||||
400,
|
||||
);
|
||||
const record = {
|
||||
id: "one",
|
||||
type: "entry",
|
||||
data: {
|
||||
date: "2026-10-20",
|
||||
meal: "Lunch",
|
||||
name: "Test",
|
||||
serving: "1 serving",
|
||||
quantity: 1,
|
||||
nutrients: emptyNutrients(),
|
||||
},
|
||||
updatedAt: new Date(Date.now() + 600000).toISOString(),
|
||||
deleted: false,
|
||||
};
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [record] }, cookie)).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
"/sync",
|
||||
{ records: [], padding: "a".repeat(2100000) },
|
||||
cookie,
|
||||
)
|
||||
).status,
|
||||
413,
|
||||
);
|
||||
});
|
||||
test("login issues secure HttpOnly SameSite cookies and logout revokes sessions", async (t) => {
|
||||
const { request } = await fixture(t, true);
|
||||
const response = await request("/login", { username: "test", password });
|
||||
const header = response.headers.get("set-cookie");
|
||||
assert.match(header, /__Host-calio=/);
|
||||
assert.match(header, /HttpOnly/);
|
||||
assert.match(header, /Secure/);
|
||||
assert.match(header, /SameSite=Strict/);
|
||||
const cookie = header.split(";")[0];
|
||||
assert.equal((await request("/session", undefined, cookie)).status, 200);
|
||||
assert.equal((await request("/logout", {}, cookie)).status, 200);
|
||||
assert.equal((await request("/session", undefined, cookie)).status, 401);
|
||||
});
|
||||
test("sync is idempotent and returns winning edits to a stale device", async (t) => {
|
||||
const { request, signIn } = await fixture(t);
|
||||
const cookie = await signIn();
|
||||
const record = {
|
||||
id: "one",
|
||||
type: "food",
|
||||
data: {
|
||||
name: "Oats",
|
||||
serving: "40 g",
|
||||
nutrients: { ...emptyNutrients(), calories: 150 },
|
||||
},
|
||||
updatedAt: "2026-01-01T10:00:00.000Z",
|
||||
deleted: false,
|
||||
};
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [record] }, cookie)).status,
|
||||
200,
|
||||
);
|
||||
const changed = {
|
||||
...record,
|
||||
updatedAt: "2026-01-01T11:00:00.000Z",
|
||||
data: { ...record.data, name: "Updated oats" },
|
||||
};
|
||||
await request("/sync", { records: [changed] }, cookie);
|
||||
const result = await (
|
||||
await request("/sync", { records: [record, record] }, cookie)
|
||||
).json();
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0], changed);
|
||||
});
|
||||
test("login is rate limited", async (t) => {
|
||||
const { request } = await fixture(t);
|
||||
for (let i = 0; i < 10; i++)
|
||||
assert.equal(
|
||||
(await request("/login", { username: "bad", password: "wrong" })).status,
|
||||
401,
|
||||
);
|
||||
assert.equal(
|
||||
(await request("/login", { username: "test", password })).status,
|
||||
429,
|
||||
);
|
||||
});
|
||||
136
tests/client-sync.test.js
Normal file
136
tests/client-sync.test.js
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import "fake-indexeddb/auto";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { openDB } from "idb";
|
||||
import { compareRecords, emptyNutrients } from "../shared/domain.js";
|
||||
|
||||
// Exercise the real browser store against IndexedDB with controllable network timing.
|
||||
globalThis.window = new EventTarget();
|
||||
globalThis.document = Object.assign(new EventTarget(), { hidden: false });
|
||||
Object.defineProperty(globalThis, "navigator", {
|
||||
value: { onLine: false },
|
||||
configurable: true,
|
||||
});
|
||||
globalThis.BroadcastChannel = class {
|
||||
addEventListener() {}
|
||||
postMessage() {}
|
||||
};
|
||||
const originalInterval = globalThis.setInterval;
|
||||
globalThis.setInterval = () => 0;
|
||||
const client = await import("../src/store.ts");
|
||||
globalThis.setInterval = originalInterval;
|
||||
|
||||
const remote = new Map();
|
||||
let pause = null;
|
||||
let arrived = null;
|
||||
let fail = false;
|
||||
let unauthorized = false;
|
||||
globalThis.fetch = async (url, options) => {
|
||||
if (fail) throw new Error("Connection unavailable");
|
||||
if (unauthorized && url.endsWith("/sync"))
|
||||
return Response.json(
|
||||
{ error: "Sign in to sync your journal" },
|
||||
{ status: 401 },
|
||||
);
|
||||
if (url.endsWith("/login") || url.endsWith("/logout"))
|
||||
return Response.json({ ok: true });
|
||||
const { records } = JSON.parse(options.body);
|
||||
const gate = pause;
|
||||
pause = null;
|
||||
if (gate) {
|
||||
arrived();
|
||||
await gate;
|
||||
}
|
||||
for (const record of records) {
|
||||
const existing = remote.get(record.id);
|
||||
if (!existing || compareRecords(record, existing) > 0)
|
||||
remote.set(record.id, record);
|
||||
}
|
||||
return Response.json({
|
||||
records: [...remote.values()],
|
||||
serverTime: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
const food = (name) => ({
|
||||
name,
|
||||
serving: "1 serving",
|
||||
nutrients: { ...emptyNutrients(), calories: 100 },
|
||||
});
|
||||
const read = async () =>
|
||||
await (await openDB("calio-journal", 1)).get("state", "journal");
|
||||
|
||||
test("offline journal and outbox are atomic, in-flight edits remain queued, reconnect merges without duplication", async () => {
|
||||
await client.initStore();
|
||||
await client.login("test", "test-only-password"); // offline mock sign-in seeds the local unlocked flag.
|
||||
await client.saveRecord("food", food("First"), "food-one");
|
||||
let state = await read();
|
||||
assert.equal(state.records.length, 1);
|
||||
assert.equal(state.outbox.length, 1);
|
||||
assert.deepEqual(state.records[0], state.outbox[0]);
|
||||
let release;
|
||||
let signalArrival;
|
||||
pause = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const sent = new Promise((resolve) => {
|
||||
signalArrival = resolve;
|
||||
});
|
||||
arrived = signalArrival;
|
||||
navigator.onLine = true;
|
||||
const syncing = client.sync();
|
||||
await sent;
|
||||
// This write happens after the request captured the old version.
|
||||
await client.saveRecord("food", food("Edited while syncing"), "food-one");
|
||||
state = await read();
|
||||
assert.equal(state.outbox[0].data.name, "Edited while syncing");
|
||||
release();
|
||||
await syncing;
|
||||
state = await read();
|
||||
assert.equal(state.outbox.length, 0);
|
||||
assert.equal(state.records.length, 1);
|
||||
assert.equal(remote.get("food-one").data.name, "Edited while syncing");
|
||||
await client.sync();
|
||||
assert.equal(remote.size, 1);
|
||||
});
|
||||
test("network errors and expired sessions preserve all pending changes", async () => {
|
||||
navigator.onLine = false;
|
||||
await client.saveRecord("food", food("Retained"), "food-two");
|
||||
navigator.onLine = true;
|
||||
fail = true;
|
||||
await client.sync();
|
||||
assert.equal((await read()).outbox.length, 1);
|
||||
await assert.rejects(client.logout(), /pending changes/);
|
||||
assert.equal((await read()).unlocked, true);
|
||||
fail = false;
|
||||
unauthorized = true;
|
||||
await client.sync();
|
||||
assert.equal((await read()).outbox.length, 1);
|
||||
unauthorized = false;
|
||||
await client.sync();
|
||||
assert.equal((await read()).outbox.length, 0);
|
||||
});
|
||||
test("a newer remote deletion beats a stale local write and explicit logout clears device data", async () => {
|
||||
const state = await read();
|
||||
const old = state.records.find((r) => r.id === "food-two");
|
||||
remote.set(old.id, {
|
||||
...old,
|
||||
updatedAt: new Date(Date.parse(old.updatedAt) + 1000).toISOString(),
|
||||
deleted: true,
|
||||
});
|
||||
navigator.onLine = false;
|
||||
await client.saveRecord("food", food("Stale offline edit"), old.id);
|
||||
navigator.onLine = true;
|
||||
await client.sync();
|
||||
assert.equal(
|
||||
(await read()).records.find((r) => r.id === old.id).deleted,
|
||||
true,
|
||||
);
|
||||
assert.equal((await read()).outbox.length, 0);
|
||||
await client.logout();
|
||||
assert.deepEqual(await read(), {
|
||||
records: [],
|
||||
outbox: [],
|
||||
unlocked: false,
|
||||
lastSync: null,
|
||||
});
|
||||
});
|
||||
148
tests/domain.test.js
Normal file
148
tests/domain.test.js
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
compareRecords,
|
||||
defaultSettings,
|
||||
emptyNutrients,
|
||||
recordSchema,
|
||||
totalNutrients,
|
||||
} from "../shared/domain.js";
|
||||
import { openDatabase } from "../server/db.js";
|
||||
const sample = (
|
||||
id = "entry-1",
|
||||
time = "2026-10-20T10:00:00.000Z",
|
||||
data = {},
|
||||
) => ({
|
||||
id,
|
||||
type: "entry",
|
||||
updatedAt: time,
|
||||
deleted: false,
|
||||
data: {
|
||||
date: "2026-10-20",
|
||||
meal: "Breakfast",
|
||||
name: "Oats",
|
||||
serving: "40 g",
|
||||
quantity: 1,
|
||||
nutrients: { ...emptyNutrients(), calories: 150, protein: 5 },
|
||||
...data,
|
||||
},
|
||||
});
|
||||
|
||||
test("nutrition totals honor fractional servings without changing source foods", () => {
|
||||
const entry = sample().data;
|
||||
const total = totalNutrients([
|
||||
{ ...entry, quantity: 1.5 },
|
||||
{ ...entry, quantity: 0.5 },
|
||||
]);
|
||||
assert.equal(total.calories, 300);
|
||||
assert.equal(total.protein, 10);
|
||||
assert.equal(entry.nutrients.calories, 150);
|
||||
});
|
||||
test("schemas reject impossible dates, negative nutrition, unknown fields, and reserved IDs", () => {
|
||||
assert.equal(recordSchema.safeParse(sample()).success, true);
|
||||
assert.equal(recordSchema.safeParse(sample("settings")).success, false);
|
||||
assert.equal(
|
||||
recordSchema.safeParse(sample("x", undefined, { date: "2026-02-30" }))
|
||||
.success,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
recordSchema.safeParse(
|
||||
sample("x", undefined, {
|
||||
nutrients: { ...emptyNutrients(), protein: -1 },
|
||||
}),
|
||||
).success,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
recordSchema.safeParse(sample("x", undefined, { admin: true })).success,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
recordSchema.safeParse({
|
||||
id: "settings",
|
||||
type: "settings",
|
||||
updatedAt: new Date().toISOString(),
|
||||
deleted: false,
|
||||
data: defaultSettings,
|
||||
}).success,
|
||||
true,
|
||||
);
|
||||
});
|
||||
test("same-millisecond conflicts resolve identically in either arrival order", () => {
|
||||
const a = sample();
|
||||
const b = sample("entry-1", a.updatedAt, { name: "Banana" });
|
||||
assert.equal(
|
||||
Math.sign(compareRecords(a, b)),
|
||||
-Math.sign(compareRecords(b, a)),
|
||||
);
|
||||
const left = openDatabase(":memory:");
|
||||
const right = openDatabase(":memory:");
|
||||
left.merge([a]);
|
||||
left.merge([b]);
|
||||
right.merge([b]);
|
||||
right.merge([a]);
|
||||
assert.deepEqual(left.all(), right.all());
|
||||
left.close();
|
||||
right.close();
|
||||
});
|
||||
test("independent offline additions survive, latest edits win, stale writes cannot resurrect deletions", () => {
|
||||
const store = openDatabase(":memory:");
|
||||
const first = sample();
|
||||
const newer = {
|
||||
...sample("entry-1", "2026-10-20T11:00:00.000Z"),
|
||||
deleted: true,
|
||||
};
|
||||
store.merge([first, sample("entry-2")]);
|
||||
store.merge([newer]);
|
||||
store.merge([first, first]);
|
||||
assert.equal(store.all().length, 2);
|
||||
assert.equal(store.all()[0].deleted, true);
|
||||
store.close();
|
||||
});
|
||||
test("batch is atomic on a type collision", () => {
|
||||
const store = openDatabase(":memory:");
|
||||
store.merge([sample()]);
|
||||
assert.throws(() =>
|
||||
store.merge([sample("entry-2"), { ...sample(), type: "food" }]),
|
||||
);
|
||||
assert.equal(store.all().length, 1);
|
||||
store.close();
|
||||
});
|
||||
test("opening the same database after an app update preserves records and sessions", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "calio-db-"));
|
||||
const filename = join(directory, "calio.sqlite");
|
||||
try {
|
||||
const store = openDatabase(filename);
|
||||
store.merge([sample()]);
|
||||
store.db
|
||||
.prepare("INSERT INTO sessions VALUES (?,?)")
|
||||
.run("session", Date.now() + 60000);
|
||||
store.close();
|
||||
const reopened = openDatabase(filename);
|
||||
assert.deepEqual(reopened.all(), [sample()]);
|
||||
assert.ok(reopened.db.prepare("SELECT * FROM sessions").get());
|
||||
assert.equal(
|
||||
reopened.db.prepare("PRAGMA user_version").get().user_version,
|
||||
1,
|
||||
);
|
||||
reopened.close();
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
test("a newer database refuses an unsafe application downgrade", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "calio-version-"));
|
||||
const filename = join(directory, "calio.sqlite");
|
||||
try {
|
||||
const store = openDatabase(filename);
|
||||
store.db.exec("PRAGMA user_version=2");
|
||||
store.close();
|
||||
assert.throws(() => openDatabase(filename), /newer Calio/);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
93
tests/export.test.js
Normal file
93
tests/export.test.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { downloadExport, offsetDay, weightValue } from "../src/utils.ts";
|
||||
import { defaultSettings, emptyNutrients } from "../shared/domain.js";
|
||||
const record = (id, type, data, deleted = false) => ({
|
||||
id,
|
||||
type,
|
||||
data,
|
||||
deleted,
|
||||
updatedAt: "2026-10-20T10:00:00.000Z",
|
||||
});
|
||||
const entry = {
|
||||
date: "2026-10-20",
|
||||
meal: "Lunch",
|
||||
name: "=danger|\nfood",
|
||||
serving: "1 bowl",
|
||||
quantity: 1.5,
|
||||
nutrients: { ...emptyNutrients(), calories: 200, protein: 20 },
|
||||
};
|
||||
const records = [
|
||||
record("e1", "entry", entry),
|
||||
record("e2", "entry", { ...entry, date: "2026-10-19" }),
|
||||
record("deleted", "entry", entry, true),
|
||||
record("w", "weight", {
|
||||
date: "2026-10-20",
|
||||
valueKg: 75,
|
||||
notes: "=untrusted",
|
||||
}),
|
||||
];
|
||||
async function capture(
|
||||
format,
|
||||
selected = ["calories", "protein"],
|
||||
includeWeight = true,
|
||||
) {
|
||||
let blob;
|
||||
const original = URL.createObjectURL;
|
||||
const timer = globalThis.setTimeout;
|
||||
globalThis.document = { createElement: () => ({ click() {} }) };
|
||||
URL.createObjectURL = (value) => {
|
||||
blob = value;
|
||||
return "blob:test";
|
||||
};
|
||||
globalThis.setTimeout = () => 0;
|
||||
try {
|
||||
downloadExport(
|
||||
records,
|
||||
defaultSettings,
|
||||
"2026-10-20",
|
||||
"2026-10-20",
|
||||
selected,
|
||||
includeWeight,
|
||||
format,
|
||||
2,
|
||||
);
|
||||
return await blob.text();
|
||||
} finally {
|
||||
URL.createObjectURL = original;
|
||||
globalThis.setTimeout = timer;
|
||||
}
|
||||
}
|
||||
test("JSON export includes fractional serving totals, chosen dates/metrics, kg weights and pending status", async () => {
|
||||
const data = JSON.parse(await capture("json"));
|
||||
assert.equal(data.schemaVersion, 1);
|
||||
assert.equal(data.pendingChanges, 2);
|
||||
assert.equal(data.entries.length, 1);
|
||||
assert.equal(data.entries[0].calories, 300);
|
||||
assert.equal(data.entries[0].protein, 30);
|
||||
assert.equal("fat" in data.entries[0], false);
|
||||
assert.equal(data.weights[0].valueKg, 75);
|
||||
assert.equal(data.dailyTotals[0].calories, 300);
|
||||
});
|
||||
test("CSV quotes text and guards spreadsheet formula fields; Markdown keeps clean rows", async () => {
|
||||
const csv = await capture("csv");
|
||||
assert.match(csv, /"'=danger\|\nfood"/);
|
||||
assert.match(csv, /"'=untrusted"/);
|
||||
assert.match(csv, /"daily_total"/);
|
||||
const markdown = await capture("markdown");
|
||||
assert.match(markdown, /\| 2026-10-20 \| 300 \| 30 \|/);
|
||||
assert.match(markdown, /=danger\/ food/);
|
||||
assert.doesNotMatch(markdown, /2026-10-19/);
|
||||
});
|
||||
test("weight-only exports omit food records; excluding weight omits all weigh-ins", async () => {
|
||||
const weights = JSON.parse(await capture("json", [], true));
|
||||
assert.equal(weights.entries.length, 0);
|
||||
assert.equal(weights.weights.length, 1);
|
||||
const foods = JSON.parse(await capture("json", ["calories"], false));
|
||||
assert.equal(foods.weights.length, 0);
|
||||
});
|
||||
test("local date arithmetic crosses month/year boundaries and weight unit conversion round trips", () => {
|
||||
assert.equal(offsetDay("2026-01-01", -1), "2025-12-31");
|
||||
assert.equal(offsetDay("2024-02-28", 1), "2024-02-29");
|
||||
assert.ok(Math.abs(weightValue(75, "lb") / 2.2046226218 - 75) < 1e-10);
|
||||
});
|
||||
125
tests/physics.test.js
Normal file
125
tests/physics.test.js
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
bubbleCount,
|
||||
createBubbleWorld,
|
||||
screenGravity,
|
||||
MAX_BUBBLES,
|
||||
BUBBLE_RADIUS,
|
||||
DRAW_BUBBLE_RADIUS,
|
||||
VESSEL_RADIUS,
|
||||
} from "../shared/bubble-physics.js";
|
||||
|
||||
test("bubble count tracks calories, remains visible at small amounts, and caps over goal", () => {
|
||||
assert.equal(bubbleCount(0, 2000, true), 0);
|
||||
assert.equal(bubbleCount(1, 2000, true), 1);
|
||||
assert.equal(bubbleCount(1000, 2000, true), Math.round(MAX_BUBBLES / 2));
|
||||
assert.equal(bubbleCount(2000, 2000, true), MAX_BUBBLES);
|
||||
assert.equal(bubbleCount(20000, 2000, true), MAX_BUBBLES);
|
||||
});
|
||||
test("new bubbles enter at the top, fall, collide and stay inside the calorie vessel", () => {
|
||||
const world = createBubbleWorld(0, () => 0.5);
|
||||
world.setTarget(8);
|
||||
world.step(50);
|
||||
assert.equal(world.balls.length, 1);
|
||||
assert.ok(world.balls[0].position.y < 50);
|
||||
for (let i = 0; i < 400; i++) world.step();
|
||||
assert.equal(world.balls.length, 8);
|
||||
assert.ok(world.balls.every((ball) => ball.position.y > 220));
|
||||
for (const ball of world.balls)
|
||||
assert.ok(
|
||||
Math.hypot(ball.position.x - 160, ball.position.y - 160) <=
|
||||
VESSEL_RADIUS - DRAW_BUBBLE_RADIUS + 1,
|
||||
);
|
||||
for (let i = 0; i < world.balls.length; i++)
|
||||
for (let j = i + 1; j < world.balls.length; j++)
|
||||
assert.ok(
|
||||
Math.hypot(
|
||||
world.balls[i].position.x - world.balls[j].position.x,
|
||||
world.balls[i].position.y - world.balls[j].position.y,
|
||||
) >
|
||||
BUBBLE_RADIUS * 1.8,
|
||||
);
|
||||
world.dispose();
|
||||
});
|
||||
test("full and over-goal vessels remain bounded through repeated gravity reversals", () => {
|
||||
const world = createBubbleWorld(MAX_BUBBLES);
|
||||
assert.equal(world.balls.length, MAX_BUBBLES);
|
||||
assert.ok(BUBBLE_RADIUS - DRAW_BUBBLE_RADIUS >= 1);
|
||||
assert.ok(Math.min(...world.balls.map((ball) => ball.position.y)) < 30);
|
||||
assert.ok(Math.max(...world.balls.map((ball) => ball.position.y)) > 290);
|
||||
assert.ok(
|
||||
world.balls.some(
|
||||
(ball) => Math.hypot(ball.position.x - 160, ball.position.y - 160) < 2,
|
||||
),
|
||||
);
|
||||
for (const [x, y] of [
|
||||
[0, 1],
|
||||
[1, 0],
|
||||
[0, -1],
|
||||
[-1, 0],
|
||||
[0.6, 0.8],
|
||||
]) {
|
||||
world.gravity(x, y);
|
||||
for (let i = 0; i < 180; i++) world.step();
|
||||
for (const ball of world.balls)
|
||||
assert.ok(
|
||||
Number.isFinite(ball.position.x) &&
|
||||
Math.hypot(ball.position.x - 160, ball.position.y - 160) <=
|
||||
VESSEL_RADIUS - DRAW_BUBBLE_RADIUS + 1,
|
||||
);
|
||||
}
|
||||
world.setTarget(10);
|
||||
assert.equal(world.balls.length, 10);
|
||||
world.setTarget(0);
|
||||
assert.equal(world.balls.length, 0);
|
||||
world.dispose();
|
||||
});
|
||||
test("bubbles follow changing gravity and wake when nudged", () => {
|
||||
const world = createBubbleWorld(12);
|
||||
world.gravity(1, 0);
|
||||
for (let i = 0; i < 400; i++) world.step();
|
||||
assert.ok(
|
||||
world.balls.reduce((sum, ball) => sum + ball.position.x, 0) / 12 > 240,
|
||||
);
|
||||
world.gravity(-1, 0);
|
||||
for (let i = 0; i < 400; i++) world.step();
|
||||
assert.ok(
|
||||
world.balls.reduce((sum, ball) => sum + ball.position.x, 0) / 12 < 80,
|
||||
);
|
||||
world.nudge();
|
||||
assert.ok(world.awake());
|
||||
assert.ok(world.balls.some((ball) => ball.speed > 1));
|
||||
world.dispose();
|
||||
});
|
||||
test("a settled 100% vessel fills to the upper rim and retains a visible gap between dots", () => {
|
||||
const world = createBubbleWorld(MAX_BUBBLES);
|
||||
for (let i = 0; i < 700; i++) world.step();
|
||||
assert.ok(
|
||||
Math.min(...world.balls.map((ball) => ball.position.y)) -
|
||||
DRAW_BUBBLE_RADIUS <
|
||||
35,
|
||||
);
|
||||
for (let i = 0; i < world.balls.length; i++)
|
||||
for (let j = i + 1; j < world.balls.length; j++) {
|
||||
const distance = Math.hypot(
|
||||
world.balls[i].position.x - world.balls[j].position.x,
|
||||
world.balls[i].position.y - world.balls[j].position.y,
|
||||
);
|
||||
assert.ok(distance - 2 * DRAW_BUBBLE_RADIUS > 0.75);
|
||||
}
|
||||
world.dispose();
|
||||
});
|
||||
test("orientation projects gravity for portrait, landscape, upside-down and flat phones", () => {
|
||||
const upright = screenGravity(90, 0, 0);
|
||||
assert.ok(Math.abs(upright.x) < 1e-10);
|
||||
assert.ok(upright.y > 0.99);
|
||||
const inverted = screenGravity(-90, 0, 0);
|
||||
assert.ok(inverted.y < -0.99);
|
||||
const right = screenGravity(0, 90, 0);
|
||||
assert.ok(right.x > 0.99);
|
||||
const landscape = screenGravity(0, 90, 90);
|
||||
assert.ok(Math.abs(landscape.x) < 1e-10);
|
||||
assert.ok(landscape.y < -0.99);
|
||||
assert.deepEqual(screenGravity(0, 0, 0), { x: 0, y: 0.18 });
|
||||
});
|
||||
50
tests/publishing.test.js
Normal file
50
tests/publishing.test.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { publicationPlan, publishImage } from "../scripts/publish-image.js";
|
||||
const base = {
|
||||
CI_EVENT: "push",
|
||||
REPOSITORY: "Elijah/Calio",
|
||||
COMMIT_SHA: "a".repeat(40),
|
||||
TARGET_REF: "refs/heads/main",
|
||||
MAIN_BRANCH: "main",
|
||||
};
|
||||
test("each push publishes a commit image; only main promotes latest", () => {
|
||||
const main = publicationPlan(base);
|
||||
assert.equal(main.image, "git.elijahkuntz.com/elijah/calio");
|
||||
assert.deepEqual(main.tags, [base.COMMIT_SHA]);
|
||||
assert.equal(main.latest, true);
|
||||
const branch = publicationPlan({
|
||||
...base,
|
||||
TARGET_REF: "refs/heads/codex/new-ui",
|
||||
});
|
||||
assert.equal(branch.latest, false);
|
||||
assert.deepEqual(branch.tags, [base.COMMIT_SHA]);
|
||||
});
|
||||
test("release tags add a version without overwriting main latest", () => {
|
||||
assert.deepEqual(
|
||||
publicationPlan({ ...base, TARGET_REF: "refs/tags/v0.1.0" }).tags,
|
||||
[base.COMMIT_SHA, "v0.1.0"],
|
||||
);
|
||||
assert.equal(
|
||||
publicationPlan({ ...base, TARGET_REF: "refs/tags/v0.1.0" }).latest,
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
publicationPlan({ ...base, TARGET_REF: "refs/tags/test/snapshot" }).tags,
|
||||
[base.COMMIT_SHA],
|
||||
);
|
||||
});
|
||||
test("PRs never publish or require registry secrets; missing publishing credentials fail clearly", () => {
|
||||
assert.equal(publicationPlan({ ...base, CI_EVENT: "pull_request" }), null);
|
||||
assert.throws(() => publishImage(base), /FORGEJO_PAT/);
|
||||
});
|
||||
test("invalid image names and commit identifiers cannot enter Docker command arguments", () => {
|
||||
assert.throws(
|
||||
() => publicationPlan({ ...base, REPOSITORY: "bad/name;command" }),
|
||||
/REPOSITORY/,
|
||||
);
|
||||
assert.throws(
|
||||
() => publicationPlan({ ...base, COMMIT_SHA: "--help" }),
|
||||
/commit ID/,
|
||||
);
|
||||
});
|
||||
56
tests/theme.test.js
Normal file
56
tests/theme.test.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
accentPalette,
|
||||
accentPresets,
|
||||
contrastText,
|
||||
DEFAULT_ACCENT,
|
||||
} from "../shared/theme.js";
|
||||
import { recordSchema, defaultSettings } from "../shared/domain.js";
|
||||
|
||||
test("custom accents have matching derived colors in light and dark modes", () => {
|
||||
const light = accentPalette("#d780a2", false);
|
||||
const dark = accentPalette("#d780a2", true);
|
||||
assert.equal(light["--accent"], "#d780a2");
|
||||
assert.equal(dark["--accent"], "#d780a2");
|
||||
assert.notEqual(light["--accent-soft"], dark["--accent-soft"]);
|
||||
for (const color of Object.values(dark))
|
||||
assert.match(color, /^#[a-f0-9]{6}$/i);
|
||||
assert.equal(accentPalette("invalid", true)["--accent"], DEFAULT_ACCENT);
|
||||
});
|
||||
test("button text stays readable on extreme and preset accent colors", () => {
|
||||
assert.equal(contrastText("#ffffff"), "#000000");
|
||||
assert.equal(contrastText("#000000"), "#ffffff");
|
||||
for (const color of [
|
||||
...accentPresets.map((v) => v.color),
|
||||
"#808080",
|
||||
"#ff0000",
|
||||
"#00ff00",
|
||||
"#0000ff",
|
||||
]) {
|
||||
const palette = accentPalette(color, true);
|
||||
assert.ok(["#000000", "#ffffff"].includes(palette["--on-accent"]));
|
||||
}
|
||||
});
|
||||
test("accent preferences validate and older settings without an accent still load", () => {
|
||||
const record = {
|
||||
id: "settings",
|
||||
type: "settings",
|
||||
deleted: false,
|
||||
updatedAt: new Date().toISOString(),
|
||||
data: { ...defaultSettings, accentColor: "#12abcd" },
|
||||
};
|
||||
assert.equal(recordSchema.safeParse(record).success, true);
|
||||
assert.equal(
|
||||
recordSchema.safeParse({
|
||||
...record,
|
||||
data: { ...record.data, accentColor: "red;display:none" },
|
||||
}).success,
|
||||
false,
|
||||
);
|
||||
const { accentColor, ...older } = defaultSettings;
|
||||
assert.equal(
|
||||
recordSchema.safeParse({ ...record, data: older }).success,
|
||||
true,
|
||||
);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue