dsh-offwork 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,172 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtemp, readFile, writeFile, stat, readdir, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, resolve, dirname, basename } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { createOperations, DEFAULT_SETTINGS, validateSettings } from '../index.js';
8
+
9
+ const source = new URL('../index.js', import.meta.url);
10
+ const prefix = 'offwork-clock-host-';
11
+ async function fixture(t) {
12
+ const root = resolve(tmpdir());
13
+ const dir = await mkdtemp(join(root, prefix));
14
+ t.after(async () => {
15
+ // Never recursively remove anything except our unique direct temporary child.
16
+ assert.equal(dirname(resolve(dir)), root);
17
+ assert.ok(basename(dir).startsWith(prefix));
18
+ assert.notEqual(resolve(dir), root);
19
+ await rm(dir, { recursive: true, force: true });
20
+ });
21
+ const file = join(dir, 'data.json');
22
+ return { dir, file, operate: createOperations(file) };
23
+ }
24
+
25
+ function valid(patch) { return validateSettings({ ...DEFAULT_SETTINGS, ...patch }); }
26
+
27
+ test('defaults remain unsaved; real writes persist privately and can be reopened', async t => {
28
+ const { dir, file, operate } = await fixture(t);
29
+ const initial = await operate('get');
30
+ assert.deepEqual(initial, { ok: true, settings: DEFAULT_SETTINGS, configured: false });
31
+ initial.settings.weekdays.push(6);
32
+ assert.deepEqual((await operate('get')).settings.weekdays, [1, 2, 3, 4, 5]);
33
+ assert.deepEqual(await readdir(dir), []);
34
+ const saved = await operate('set', { payMode: 'daily', dailySalary: 500 });
35
+ assert.equal(saved.ok, true);
36
+ assert.equal(saved.configured, true);
37
+ assert.deepEqual(JSON.parse(await readFile(file, 'utf8')), saved.settings);
38
+ assert.equal((await stat(file)).mode & 0o777, 0o600);
39
+ assert.deepEqual(await createOperations(pathToFileURL(file))('get'), saved);
40
+ assert.deepEqual(await readdir(dir), ['data.json']);
41
+ });
42
+
43
+ test('legacy configuration gains only new defaults, without rewriting on get', async t => {
44
+ const { file, operate } = await fixture(t);
45
+ const { payMode, dailySalary, ...legacy } = DEFAULT_SETTINGS;
46
+ legacy.monthlySalary = 12345;
47
+ const bytes = JSON.stringify(legacy);
48
+ await writeFile(file, bytes);
49
+ const migrated = await operate('get');
50
+ assert.deepEqual(migrated, { ok: true, configured: true, settings: { ...DEFAULT_SETTINGS, monthlySalary: 12345 } });
51
+ assert.equal(await readFile(file, 'utf8'), bytes);
52
+ assert.equal((await operate('set', { dailySalary: 700 })).settings.monthlySalary, 12345);
53
+ assert.equal(JSON.parse(await readFile(file, 'utf8')).payMode, 'monthly');
54
+ });
55
+
56
+ test('malformed, unknown and incomplete saved data are never overwritten', async t => {
57
+ const { file, operate, dir } = await fixture(t);
58
+ for (const bytes of ['{broken', 'null', '[]', JSON.stringify({ ...DEFAULT_SETTINGS, surprise: true }), JSON.stringify({ start: '09:00' })]) {
59
+ await writeFile(file, bytes);
60
+ assert.equal((await operate('get')).ok, false);
61
+ assert.equal((await operate('set', { monthlySalary: 5 })).ok, false);
62
+ assert.equal(await readFile(file, 'utf8'), bytes);
63
+ assert.deepEqual(await readdir(dir), ['data.json']);
64
+ }
65
+ });
66
+
67
+ test('day and overnight shifts normalize breaks against shift start', () => {
68
+ for (const patch of [
69
+ { start: '22:00', end: '06:00', breakStart: '02:00', breakEnd: '03:00' },
70
+ { start: '22:00', end: '06:00', breakStart: '23:30', breakEnd: '00:30' },
71
+ { start: '22:00', end: '06:00', breakStart: '22:00', breakEnd: '23:00' },
72
+ { start: '22:00', end: '06:00', breakStart: '05:00', breakEnd: '06:00' },
73
+ { start: '22:00', end: '06:00', breakStart: '12:00', breakEnd: '12:00' },
74
+ { breakStart: '00:00', breakEnd: '00:00' },
75
+ ]) assert.doesNotThrow(() => valid(patch));
76
+ for (const patch of [
77
+ { start: '09:00', end: '09:00' },
78
+ { start: '22:00', end: '06:00' },
79
+ { start: '22:00', end: '06:00', breakStart: '02:00', breakEnd: '01:00' },
80
+ { start: '22:00', end: '06:00', breakStart: '22:00', breakEnd: '06:00' },
81
+ { breakStart: '18:00', breakEnd: '19:00' },
82
+ { breakStart: '12:00', breakEnd: '11:00' },
83
+ { payMode: 'hourly' }, { dailySalary: -1 }, { dailySalary: Infinity },
84
+ { monthlySalary: NaN }, { workdaysPerMonth: 0 }, { start: '9:00' },
85
+ { weekdays: [1, 1] }, { timezone: 'not/a-zone' }, { surprise: true },
86
+ ]) assert.throws(() => valid(patch), JSON.stringify(patch));
87
+ });
88
+
89
+ test('invalid patches and actions do not create files; queue recovers', async t => {
90
+ const { dir, operate } = await fixture(t);
91
+ for (const [action, patch] of [['wat'], ['get', {}], ['set'], ['set', []], ['set', { unknown: 1 }], ['set', { payMode: 'weekly' }]]) {
92
+ assert.equal((await operate(action, patch)).ok, false);
93
+ }
94
+ assert.deepEqual(await readdir(dir), []);
95
+ assert.equal((await operate('set', {})).configured, true);
96
+ });
97
+
98
+ test('concurrent partial sets serialize and preserve preceding updates', async t => {
99
+ const { file, operate, dir } = await fixture(t);
100
+ const patches = [{ monthlySalary: 22222 }, { dailySalary: 999 }, { payMode: 'daily' }, { timezone: 'UTC' }];
101
+ const pending = patches.map(patch => operate('set', patch));
102
+ pending.push(operate('set', { unknown: true }));
103
+ for (let i = 0; i < 30; i++) pending.push(operate('set', { dailySalary: 1000 + i }));
104
+ const results = await Promise.all(pending);
105
+ assert.equal(results[4].ok, false);
106
+ assert.ok(results.filter((_, i) => i !== 4).every(result => result.ok));
107
+ const expected = { ...DEFAULT_SETTINGS, ...Object.assign({}, ...patches), dailySalary: 1029 };
108
+ assert.deepEqual(JSON.parse(await readFile(file, 'utf8')), expected);
109
+ assert.deepEqual((await operate('get')).settings, expected);
110
+ assert.deepEqual(await readdir(dir), ['data.json']);
111
+ });
112
+
113
+ async function adapters(t) {
114
+ const fixtureData = await fixture(t);
115
+ // Import an isolated copy: apply() keeps its real default data URL beside the module,
116
+ // and neither adapter can accidentally reach the user's actual data.json.
117
+ const moduleFile = join(fixtureData.dir, 'host.mjs');
118
+ await writeFile(moduleFile, await readFile(source, 'utf8'));
119
+ const module = await import(pathToFileURL(moduleFile).href);
120
+ let command;
121
+ let tool;
122
+ module.apply({
123
+ effect: effect => effect(),
124
+ commands: { register(definition) { command = definition; return () => {}; } },
125
+ tools: { register(definition) { tool = definition; return () => {}; } },
126
+ });
127
+ const runCommand = async rawInput => {
128
+ const response = await command.handler({ rawInput });
129
+ const result = JSON.parse(response.text);
130
+ assert.equal(response.kind, result.ok ? 'success' : 'error');
131
+ return result;
132
+ };
133
+ return { ...fixtureData, tool, command, runCommand };
134
+ }
135
+
136
+ test('command and tool share results, validation, storage and a write queue', async t => {
137
+ const { tool, command, runCommand, file } = await adapters(t);
138
+ assert.equal(command.recordInput, false);
139
+ assert.deepEqual(await runCommand('get'), await tool.execute({ action: 'get' }));
140
+ const written = await runCommand('set {"payMode":"daily","dailySalary":600}');
141
+ assert.deepEqual(await tool.execute({ action: 'get' }), written);
142
+ const second = await tool.execute({ action: 'set', settings: { monthlySalary: 25000 } });
143
+ assert.deepEqual(await runCommand('get'), second);
144
+ assert.deepEqual(await runCommand('set {"unknown":1}'), await tool.execute({ action: 'set', settings: { unknown: 1 } }));
145
+ await Promise.all([
146
+ runCommand('set {"dailySalary":750}'),
147
+ tool.execute({ action: 'set', settings: { timezone: 'UTC' } }),
148
+ ]);
149
+ const stored = JSON.parse(await readFile(file, 'utf8'));
150
+ assert.equal(stored.dailySalary, 750);
151
+ assert.equal(stored.timezone, 'UTC');
152
+ for (const raw of ['get {}', 'set', 'set {bad', 'wat']) assert.equal((await runCommand(raw)).ok, false);
153
+ for (const args of [null, [], { action: 'get', unknown: true }]) assert.equal((await tool.execute(args)).ok, false);
154
+ });
155
+
156
+ test('tool schemas expose new fields, configured flag, and typed literal branches', async t => {
157
+ const { tool } = await adapters(t);
158
+ const input = tool.parameters.properties.settings;
159
+ assert.equal(input.additionalProperties, false);
160
+ assert.deepEqual(input.properties.payMode.enum, ['monthly', 'daily']);
161
+ assert.equal(input.properties.dailySalary.type, 'number');
162
+ const [success, failure] = tool.output.schema.oneOf;
163
+ assert.deepEqual(success.properties.ok, { type: 'boolean', const: true });
164
+ assert.deepEqual(failure.properties.ok, { type: 'boolean', const: false });
165
+ assert.ok(success.required.includes('configured'));
166
+ assert.equal(success.properties.configured.type, 'boolean');
167
+ assert.deepEqual(success.properties.settings.required, Object.keys(DEFAULT_SETTINGS));
168
+ assert.equal(success.additionalProperties, false);
169
+ assert.equal(failure.additionalProperties, false);
170
+ const result = await tool.execute({ action: 'get' });
171
+ assert.deepEqual(tool.output.render({}, result), [{ type: 'text', text: JSON.stringify(result) }]);
172
+ });
@@ -0,0 +1,75 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { formatDuration, clampPosition, normalizeView, clampOpacity, decodeCommand, changedSettings } from '../ui-utils.js';
5
+ test('duration rounds countdown upward and supports >24 hours', () => {
6
+ assert.equal(formatDuration(0), '00:00:00'); assert.equal(formatDuration(3661), '01:01:01');
7
+ assert.equal(formatDuration(.1), '00:00:01'); assert.equal(formatDuration(90000), '25:00:00');
8
+ assert.equal(formatDuration(NaN), '--:--:--'); assert.equal(formatDuration(-1), '--:--:--');
9
+ });
10
+ test('position stays visible when viewport shrinks', () => {
11
+ assert.deepEqual(clampPosition({ x: 9000, y: -20 }, { width: 800, height: 600 }, { width: 330, height: 400 }), { x: 458, y: 12 });
12
+ assert.deepEqual(clampPosition(null, { width: 200, height: 200 }, { width: 330, height: 400 }), { x: 12, y: 12 });
13
+ });
14
+ test('view defaults: compact, salary hidden, 82% glass', () => {
15
+ assert.deepEqual(normalizeView(null), { mini: true, masked: true, opacity: 0.82, position: null });
16
+ assert.deepEqual(normalizeView({ mini: false, masked: false, opacity: 0.5, position: { x: 1, y: 2 } }),
17
+ { mini: false, masked: false, opacity: 0.5, position: { x: 1, y: 2 } });
18
+ assert.equal(normalizeView({ mini: 'yes' }).mini, true);
19
+ assert.equal(normalizeView({ masked: 'false' }).masked, true);
20
+ });
21
+ test('malformed positions and opacity are repaired, not trusted', () => {
22
+ assert.deepEqual(normalizeView({ mini: 'yes', masked: true, position: { x: 'oops', y: 2 } }), { mini: true, masked: true, opacity: 0.82, position: null });
23
+ assert.equal(normalizeView({ opacity: 0 }).opacity, 0.3);
24
+ assert.equal(normalizeView({ opacity: 9 }).opacity, 1);
25
+ assert.equal(normalizeView({ opacity: 'x' }).opacity, 0.82);
26
+ assert.equal(clampOpacity(0.55), 0.55);
27
+ });
28
+ test('salary stays hidden until explicitly revealed, including on first paint', () => {
29
+ assert.equal(normalizeView(null).masked, true);
30
+ assert.equal(normalizeView({}).masked, true);
31
+ assert.equal(normalizeView({ masked: false }).masked, false);
32
+ });
33
+ test('RPC decodes every failure layer and real command envelopes', () => {
34
+ const response = (data, kind = 'success') => ({ ok: true, value: { result: { kind, text: JSON.stringify(data) } } });
35
+ assert.deepEqual(decodeCommand(response({ ok: true, settings: { monthlySalary: 1000 }, configured: true })).settings, { monthlySalary: 1000 });
36
+ assert.throws(() => decodeCommand({ ok: false, error: { message: 'permission denied' } }), /permission denied/);
37
+ assert.throws(() => decodeCommand({ ok: true }), /Command unavailable/);
38
+ assert.throws(() => decodeCommand(response({ ok: false, error: 'bad shift' }, 'error')), /bad shift/);
39
+ assert.throws(() => decodeCommand({ ok: true, value: { result: { kind: 'success', text: 'oops' } } }), /Invalid/);
40
+ });
41
+ test('partial saves preserve unrelated edits from another caller', () => {
42
+ assert.deepEqual(changedSettings({ salary: 1, days: [1, 2], start: '09:00' }, { salary: 2, days: [1, 2], start: '09:00' }), { salary: 2 });
43
+ });
44
+ test('Client uses the exact tested engine and a single surface', async () => {
45
+ const source = await readFile(new URL('../client.source.js', import.meta.url), 'utf8');
46
+ const built = await readFile(new URL('../client.js', import.meta.url), 'utf8');
47
+ const engine = (await readFile(new URL('../clock.js', import.meta.url), 'utf8')).replace(/^export /gm, '');
48
+ assert.ok(built.includes(engine));
49
+ assert.match(source, /prefers-reduced-motion:reduce/);
50
+ assert.match(source, /prefers-reduced-transparency:reduce/);
51
+ assert.match(source, /visibilitychange/); assert.match(source, /removeEventListener\('storage'/);
52
+ assert.match(source, /ro\?\.disconnect/); assert.match(source, /generation\.current/);
53
+ assert.doesNotMatch(source, /document\.body|window\.open|fetch\(/);
54
+ assert.match(source, /money\(safeState\.earned\)/);
55
+ assert.match(source, /owc-glass/);
56
+ assert.match(source, /--owc-alpha/);
57
+ assert.match(source, /type: 'range'/);
58
+ assert.match(source, /dragState/);
59
+ assert.ok(source.includes('onPointerMove: dragMove'));
60
+ });
61
+ test('compact strip stacks time above amount', async () => {
62
+ const source = await readFile(new URL('../client.source.js', import.meta.url), 'utf8');
63
+ const css = source.slice(source.indexOf('.owc-pill{'), source.indexOf('.owc-pill{') + 200);
64
+ assert.match(css, /flex-direction:column/);
65
+ assert.match(source, /className: 'owc-pill-top'/);
66
+ assert.match(source, /className: 'owc-pill-bottom'/);
67
+ assert.ok(source.indexOf("className: 'owc-pill-time'") < source.indexOf("className: 'owc-pill-money'"));
68
+ });
69
+ test('compact strip keeps both drag surface and expand action; panel keeps collapse', async () => {
70
+ const source = await readFile(new URL('../client.source.js', import.meta.url), 'utf8');
71
+ assert.match(source, /onPointerDown: dragDown/);
72
+ assert.match(source, /mini: false/);
73
+ assert.match(source, /mini: true/);
74
+ assert.match(source, /hasPointerCapture/);
75
+ });
@@ -0,0 +1,13 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ const root = new URL('../', import.meta.url);
3
+ const [entry, clock, utils] = await Promise.all(['client.source.js','clock.js','ui-utils.js'].map(name=>readFile(new URL(name,root),'utf8')));
4
+ if (entry.split('/* PURE_MODULES */').length !== 2) throw new Error('Expected exactly one pure-module marker');
5
+ const pure = [clock,utils].map(text=>text.replace(/^export /gm,'')).join('\n');
6
+ const result = '// Generated by tools/build.mjs; edit client.source.js, clock.js or ui-utils.js.\n'+entry.replace('/* PURE_MODULES */',pure);
7
+ if(process.argv.includes('--check')) {
8
+ if(await readFile(new URL('client.js',root),'utf8')!==result) throw new Error('Client artifact is stale');
9
+ console.log('Client artifact matches tested source');
10
+ } else {
11
+ await writeFile(new URL('client.js',root),result);
12
+ console.log('Built client.js from one calculation source');
13
+ }
package/ui-utils.js ADDED
@@ -0,0 +1,51 @@
1
+ // Small pure helpers shared by the browser artifact and its tests.
2
+ export function formatDuration(seconds) {
3
+ if (!Number.isFinite(seconds) || seconds < 0) return '--:--:--';
4
+ const n = Math.ceil(seconds);
5
+ return [Math.floor(n / 3600), Math.floor(n % 3600 / 60), n % 60]
6
+ .map(part => String(part).padStart(2, '0')).join(':');
7
+ }
8
+
9
+ export function clampPosition(position, viewport, size) {
10
+ const width = Math.max(0, viewport.width), height = Math.max(0, viewport.height);
11
+ const edge = Math.min(12, width / 2, height / 2);
12
+ const maxX = Math.max(edge, width - size.width - edge);
13
+ const maxY = Math.max(edge, height - size.height - edge);
14
+ return {
15
+ x: Math.max(edge, Math.min(Number.isFinite(position?.x) ? position.x : maxX, maxX)),
16
+ y: Math.max(edge, Math.min(Number.isFinite(position?.y) ? position.y : 88, maxY)),
17
+ };
18
+ }
19
+
20
+ export function clampOpacity(value, fallback = 0.82) {
21
+ const number = Number(value);
22
+ if (!Number.isFinite(number)) return fallback;
23
+ return Math.min(1, Math.max(0.3, number));
24
+ }
25
+
26
+ export function normalizeView(value) {
27
+ return {
28
+ mini: value?.mini !== false,
29
+ masked: value?.masked !== false,
30
+ opacity: clampOpacity(value?.opacity),
31
+ position: Number.isFinite(value?.position?.x) && Number.isFinite(value?.position?.y)
32
+ ? { x: value.position.x, y: value.position.y } : null,
33
+ };
34
+ }
35
+
36
+ export function decodeCommand(rpc) {
37
+ if (!rpc || rpc.ok !== true) throw new Error(rpc?.error?.message || 'RPC unavailable');
38
+ const result = rpc.value?.result;
39
+ if (!result || typeof result.text !== 'string') throw new Error('Command unavailable');
40
+ let data;
41
+ try { data = JSON.parse(result.text); }
42
+ catch { throw new Error('Invalid command response'); }
43
+ if (result.kind !== 'success' || data?.ok !== true) throw new Error(data?.error || 'Request failed');
44
+ if (!data.settings || typeof data.settings !== 'object') throw new Error('Missing settings');
45
+ return data;
46
+ }
47
+
48
+ export function changedSettings(original, draft) {
49
+ return Object.fromEntries(Object.entries(draft)
50
+ .filter(([key, value]) => JSON.stringify(value) !== JSON.stringify(original[key])));
51
+ }