Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/tag-on-merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ on:
paths-ignore:
- '**.md'
- 'docs/**'
- 'samples/**'
- '.github/**'

permissions:
Expand Down
30 changes: 25 additions & 5 deletions PLUGIN_AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A plugin is a folder with a `plugin.json` file and ordinary web files: HTML, Jav

The page runs in its own sandboxed browser. It talks to FourFold only through `window.fourfold`, a small API that gives it:

- read-only data from FourFold: the accounts, their XP and stats, and the timer (never logins);
- read-only data from FourFold: the accounts, their XP, stats, equipment, silver, gold and location, and the timer (never logins);
- web requests to the sites the plugin declares;
- a small private store;
- overlay cards, drawn by FourFold.
Expand All @@ -29,7 +29,7 @@ Users get plugins from the plugin hub: they open the plugin list (the wrench in

When you build on a copy of a sample, change its `id` and `author` in `plugin.json` first.

The other sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin).
`samples/silver-tracker` is a fuller example: it reads `fourfold.profile`, keeps its maths in a module, and has a check that runs with Node. The third sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin).

Every folder directly inside `dev-plugins` is one plugin.

Expand Down Expand Up @@ -70,7 +70,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load,
| `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. |
| `author` | yes | 1 to 40 characters. |
| `description` | no | At most 200 characters. |
| `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." |
| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1` and `2`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." |
| `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. |
| `icon` | no | Path to a `.png` file inside the plugin folder, at most 256 by 256 pixels and 64 KB. Forward slashes only. Without one, the strip shows a default icon. |
| `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. An international host name is fine: FourFold converts it to its `xn--` form, and that form is what it shows users. After the conversion the host can contain only letters, digits, dots and dashes, so a name with an underscore or any other punctuation is refused. |
Expand Down Expand Up @@ -151,7 +151,27 @@ const stats = await fourfold.stats.get(account.id);
if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack);
```

`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. An unknown account id is rejected with `invalid-argument`.
`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`.

### Profile

```js
const profile = await fourfold.profile.get(account.id);
if (!profile.isStale && profile.silver !== null) console.log(account.label, 'has', profile.silver, 'silver');
```

`fourfold.profile.get(accountId)` returns facts from the account's public profile page. It needs `"apiVersion": 2`.

| Field | Type | Meaning |
|---|---|---|
| `silver` | number or null | The account's silver. |
| `gold` | number or null | The account's gold. |
| `location` | string or null | Where the character is, as the profile page words it. At most 64 characters. |
| `playerId` | number or null | The account's public player id. Like `inGameName`, it is `null` unless the user has filled in that account's **Ranking username**. It is also `null` until the profile has been read under that name. |
| `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. |
| `isStale` | boolean | `true` when there is no data yet, when the last read failed, and for a closed account. |

The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read `silver`, `gold`, `location` and `updatedAt` keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`.

### Timer

Expand Down Expand Up @@ -387,7 +407,7 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve

- Read or control the game, or see its pages, cookies or sessions.
- See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either.
- Get real-time data. XP data arrives about once a minute, and the timer sends no tick events.
- Get real-time data. XP and profile data arrive about once a minute, and the timer sends no tick events.
- Use shortcut keys, sounds or desktop notifications.
- Draw custom cards. Cards are FourFold's data cards.
- Add a settings page behind the cog. Keep settings in your own panel.
Expand Down
72 changes: 72 additions & 0 deletions samples/silver-tracker/.check/rate.check.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Checks rate.mjs outside FourFold. Run: node samples/silver-tracker/.check/rate.check.mjs
import assert from 'node:assert/strict';
import { applyRead, createSession, parseGoal, rateAt, statusOf, toGoal } from '../rate.mjs';

const at = minutes => new Date(Date.UTC(2026, 9, 4, 12, 0) + minutes * 60000).toISOString();
const read = (silver, minutes, isStale = false) => ({ silver, updatedAt: at(minutes), isStale });
const feed = (...reads) => {
const session = createSession();
for (const next of reads) applyRead(session, next);
return session;
};
const rate = session => rateAt(session, session.lastAt);
const net = session => session.lastBalance - session.startBalance;

// One read alone gives no rate. Two reads a minute apart: 600 silver in 60 seconds is 36,000 an hour.
assert.equal(rate(feed(read(1000, 0))), null);
let session = feed(read(1000, 0), read(1600, 1));
assert.equal(session.earned, 600);
assert.equal(Math.round(rate(session)), 36000);

// Spending adds nothing to earned and never makes the rate negative. Net does go negative.
session = feed(read(5000, 0), read(2000, 1), read(2500, 2));
assert.equal(session.earned, 500);
assert.equal(net(session), -2500);
assert.equal(Math.round(rate(session)), 15000);

// A failed read, then a good one half an hour later with far more silver: no interval spans the gap, so the rate
// doesn't spike. Net is still the true change.
session = feed(read(1000, 0), read(1100, 1), read(1100, 1, true), read(9000, 30), read(9100, 31));
assert.equal(session.intervals.length, 2);
assert.equal(session.earned, 200);
assert.equal(net(session), 8100);
assert.equal(Math.round(rate(session)), 6000);

// The same read twice, or one stamped earlier than the last, changes nothing.
session = feed(read(1000, 0), read(1600, 1), read(1600, 1), read(99999, 0));
assert.equal(session.earned, 600);
assert.equal(session.intervals.length, 1);

// A read with no silver or no time counts as missed, like a stale one.
session = feed(read(1000, 0), { silver: null, updatedAt: null, isStale: false }, read(5000, 1), read(5100, 2));
assert.equal(session.earned, 100);

// The status never calls old numbers live. If the page stops giving silver while the read itself still succeeds,
// the account shows as stale until silver is back.
assert.equal(statusOf(createSession()), 'No data yet');
assert.equal(statusOf(feed(read(1000, 0))), 'Collecting baseline');
assert.equal(statusOf(feed(read(1000, 0), read(1600, 1))), 'Tracking');
session = feed(read(1000, 0), read(1600, 1), { silver: null, updatedAt: at(2), isStale: false });
assert.equal(statusOf(session), 'Stale; the last read failed');
applyRead(session, read(1700, 3));
assert.equal(statusOf(session), 'Tracking');
assert.equal(statusOf(feed(read(1000, 0), read(1000, 0, true))), 'Stale; the last read failed');

// Only the last hour counts. An interval that ended before it is dropped; one that straddles it counts in part.
session = feed(read(0, 0), read(60000, 1), read(60000, 90), read(60000, 91));
assert.equal(rate(session), 0);
assert.equal(session.earned, 60000);
assert.equal(Math.round(rate(feed(read(0, 0), read(1200, 120)))), 600);

// A goal is a whole number above zero, with commas or spaces as separators. Anything else is no goal.
assert.equal(parseGoal('1,000,000'), 1000000);
assert.equal(parseGoal(' 250 000 '), 250000);
for (const bad of ['', '0', '-5', '1.5', '1e9', 'abc', '9'.repeat(16)]) assert.equal(parseGoal(bad), null);

// Time to a goal needs a rate above zero. A reached goal has nothing left.
assert.deepEqual(toGoal(1000, 400, 300), { remaining: 600, progress: 0.4, hours: 2 });
assert.equal(toGoal(1000, 400, null).hours, null);
assert.equal(toGoal(1000, 400, 0).hours, null);
assert.deepEqual(toGoal(1000, 2500, 300), { remaining: 0, progress: 1, hours: null });

console.log('rate.mjs: all checks passed');
193 changes: 193 additions & 0 deletions samples/silver-tracker/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
// Silver tracker: silver earned per hour, session totals and a silver goal for each open account, in the panel and
// on a card. The maths is in rate.mjs.
import { applyRead, createSession, parseGoal, rateAt, statusOf, toGoal } from './rate.mjs';

const container = document.getElementById('accounts');
const empty = document.getElementById('empty');
const sessions = new Map(); // account id -> session; open accounts only
const blocks = new Map(); // account id -> that account's elements in the panel
let goals = {};

const whole = value => Math.round(value).toLocaleString('en-US');
const signed = value => (value > 0 ? '+' : '') + whole(value);
// A card's text can be at most 40 characters, and FourFold refuses a longer line, so clip it.
const fit = text => (text.length > 40 ? `${text.slice(0, 39)}…` : text);
const goalFor = id => (Number.isSafeInteger(goals[id]) && goals[id] > 0 ? goals[id] : null);

function duration(hours) {
if (hours >= 10000) return '9,999h+';
const minutes = Math.max(1, Math.round(hours * 60));
return minutes < 60 ? `${minutes}m` : `${whole(Math.floor(minutes / 60))}h ${minutes % 60}m`;
}

function goalText(left) {
if (left.remaining === 0) return 'Reached';
const toGo = `${whole(left.remaining)} to go`;
return left.hours === null ? toGo : `${toGo} · ${duration(left.hours)}`;
}

// Everything one account's block and card show.
function describe(account, session) {
const tracked = session.lastAt !== null;
const balance = tracked ? session.lastBalance : null;
const rate = tracked ? rateAt(session, session.lastAt) : null;
const goal = goalFor(account.id);
return {
id: account.id,
label: account.label,
balance,
rate,
earned: session.earned,
net: tracked ? balance - session.startBalance : null,
goal,
left: goal !== null && tracked ? toGoal(goal, balance, rate) : null,
status: statusOf(session)
};
}

async function setCard(view) {
if (view.balance === null) {
await fourfold.cards.clear('silver', view.id);
return;
}
const rows = [
{ label: 'Silver/hr', value: fit(view.rate === null ? 'No rate yet' : whole(view.rate)) },
{ label: 'Session', value: fit(`+${whole(view.earned)} (net ${signed(view.net)})`) }
];
if (view.left) rows.push({ label: 'Goal', value: fit(goalText(view.left)), progress: view.left.progress });
await fourfold.cards.set('silver', view.id, {
summary: fit(view.rate === null ? 'No rate yet' : `${whole(view.rate)}/hr`),
rows
});
}

function element(tag, className, parent) {
const created = document.createElement(tag);
if (className) created.className = className;
parent.append(created);
return created;
}

// One account's block, built once. Its handlers look the account up by id, so they never hold stale data.
function createBlock(id) {
const root = document.createElement('div');
root.className = 'account';
const parts = { root, title: element('h2', '', root), rate: element('p', 'rate', root) };
parts.session = element('p', '', root);
parts.balance = element('p', '', root);
const label = element('label', '', root);
label.textContent = 'Goal';
parts.input = element('input', '', label);
parts.input.type = 'text';
parts.input.inputMode = 'numeric';
parts.input.placeholder = 'Target silver';
parts.bar = element('div', 'bar', root);
parts.fill = element('div', '', parts.bar);
parts.goal = element('p', '', root);
parts.status = element('p', 'status', root);
const reset = element('button', '', root);
reset.type = 'button';
reset.textContent = 'Reset';

parts.input.addEventListener('change', async () => {
const goal = parseGoal(parts.input.value);
if (goal === null) delete goals[id];
else goals[id] = goal;
await saveGoals();
await render();
});
// Leaving the box redraws it at once, so a goal that wasn't accepted doesn't stay on show.
parts.input.addEventListener('blur', render);
// Ending the session is enough: the next refresh starts a new one from the latest read.
reset.addEventListener('click', () => {
sessions.delete(id);
render();
});
return parts;
}

function updateBlock(parts, view) {
parts.title.textContent = view.label;
parts.title.title = view.label;
parts.rate.textContent = view.rate === null ? 'No rate yet' : `${whole(view.rate)} silver/hr`;
const tracked = view.balance !== null;
parts.session.hidden = !tracked;
parts.balance.hidden = !tracked;
if (tracked) {
parts.session.textContent = `Session: +${whole(view.earned)} earned, ${signed(view.net)} net`;
parts.balance.textContent = `Balance: ${whole(view.balance)}`;
}
// Never rewrite the box under the user's cursor.
if (document.activeElement !== parts.input) parts.input.value = view.goal === null ? '' : whole(view.goal);
parts.bar.hidden = !view.left;
parts.goal.hidden = !view.left;
if (view.left) {
parts.fill.style.width = `${Math.round(view.left.progress * 100)}%`;
parts.goal.textContent = goalText(view.left);
}
parts.status.textContent = view.status;
}

function paint(views) {
for (const [id, parts] of blocks) {
if (views.every(view => view.id !== id)) {
parts.root.remove();
blocks.delete(id);
}
}
views.forEach((view, index) => {
let parts = blocks.get(view.id);
if (!parts) blocks.set(view.id, (parts = createBlock(view.id)));
// Moving a block drops its focus, so only move one that is out of place.
if (container.children[index] !== parts.root) container.insertBefore(parts.root, container.children[index] ?? null);
updateBlock(parts, view);
});
empty.hidden = views.length > 0;
}

async function refresh() {
const open = (await fourfold.accounts.list()).filter(account => account.isOpen);
// A closed account's session is over, and its card goes with it.
for (const id of [...sessions.keys()]) {
if (open.every(account => account.id !== id)) {
sessions.delete(id);
await fourfold.cards.clear('silver', id).catch(() => {});
}
}

const views = [];
for (const account of open) {
let session = sessions.get(account.id);
if (!session) sessions.set(account.id, (session = createSession()));
applyRead(session, await fourfold.profile.get(account.id));
const view = describe(account, session);
// A refused card must not stop the panel from updating.
await setCard(view).catch(error => console.warn(error.code ?? error.message));
views.push(view);
}
paint(views);
}

// Events arrive in bursts (xp.onUpdated fires once per account), so refreshes run one after another, never
// overlapping.
let queue = Promise.resolve();
const render = () => (queue = queue.then(refresh).catch(error => console.warn(error.code ?? error.message)));

async function saveGoals() {
// Goals for accounts that no longer exist go, so the store doesn't grow for ever.
const known = new Set((await fourfold.accounts.list()).map(account => account.id));
for (const id of Object.keys(goals)) {
if (!known.has(id)) delete goals[id];
}
await fourfold.storage.set('goals', goals);
}

async function start() {
const saved = await fourfold.storage.get('goals');
goals = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
fourfold.accounts.onChanged(render);
fourfold.xp.onUpdated(render);
await render();
}

start().catch(error => { container.textContent = `Silver tracker failed: ${error.message}`; });
15 changes: 15 additions & 0 deletions samples/silver-tracker/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Silver tracker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Silver tracker</h1>
<p class="muted">Silver earned per hour for each open account.</p>
<p id="empty" class="muted" hidden>Open an account to track its silver.</p>
<div id="accounts"></div>
<script type="module" src="app.js"></script>
</body>
</html>
11 changes: 11 additions & 0 deletions samples/silver-tracker/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"id": "fourfold.silver-tracker",
"name": "Silver tracker",
"shortLabel": "Silver",
"version": "1.0.0",
"author": "FourFold",
"description": "Silver per hour, session totals and a silver goal for each open account.",
"apiVersion": 2,
"panel": "index.html",
"cards": [{ "id": "silver", "name": "Silver", "scope": "account" }]
}
Loading
Loading