dsh-offwork 0.0.0-stage → 1.0.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/clock.js ADDED
@@ -0,0 +1,150 @@
1
+ // Pure calculation. Weekdays belong to the shift's START date, not the clock date.
2
+ // Keep helpers inside calculate: the client build embeds this exact function.
3
+ export function calculate(settings, timestamp = Date.now()) {
4
+ const now = Number(timestamp);
5
+ if (!Number.isFinite(now)) throw new RangeError('Invalid timestamp');
6
+ const DAY = 86400000;
7
+ const formatter = new Intl.DateTimeFormat('en-CA', {
8
+ timeZone: settings.timezone,
9
+ year: 'numeric',
10
+ month: '2-digit',
11
+ day: '2-digit',
12
+ hour: '2-digit',
13
+ minute: '2-digit',
14
+ second: '2-digit',
15
+ hourCycle: 'h23',
16
+ });
17
+ const civil = (time) => {
18
+ const p = Object.fromEntries(formatter.formatToParts(time).map((p) => [p.type, p.value]));
19
+ return Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
20
+ };
21
+ // Convert a timezone-local civil time to an absolute instant. At DST overlaps use
22
+ // the earlier occurrence; at gaps move forward by the gap (Temporal-compatible).
23
+ const instant = (local) => {
24
+ const offsets = [
25
+ ...new Set([-DAY, 0, DAY].map((delta) => civil(local + delta) - (local + delta))),
26
+ ];
27
+ const candidates = offsets.map((offset) => local - offset);
28
+ const exact = candidates.filter((time) => civil(time) === local);
29
+ if (exact.length) return Math.min(...exact);
30
+ const after = candidates.filter((time) => civil(time) >= local);
31
+ return Math.min(...(after.length ? after : candidates));
32
+ };
33
+ const minute = (text) => {
34
+ if (typeof text !== 'string' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(text)) {
35
+ throw new RangeError('Shift times must be HH:mm');
36
+ }
37
+ const [h, m] = text.split(':').map(Number);
38
+ return h * 60 + m;
39
+ };
40
+ const start = minute(settings.start),
41
+ end = minute(settings.end);
42
+ if (start === end) throw new RangeError('Shift must not be empty');
43
+ const overnight = end < start;
44
+ const duration = (end - start + 1440) % 1440;
45
+ let breakOffset = 0,
46
+ breakDuration = 0;
47
+ if (settings.breakStart != null || settings.breakEnd != null) {
48
+ const bs = minute(settings.breakStart),
49
+ be = minute(settings.breakEnd);
50
+ if (bs !== be) {
51
+ breakOffset = (bs - start + 1440) % 1440;
52
+ breakDuration = (be - bs + 1440) % 1440;
53
+ if (breakOffset + breakDuration > duration || breakDuration >= duration) {
54
+ throw new RangeError('Break must be inside the shift and leave paid work');
55
+ }
56
+ }
57
+ }
58
+ const localNow = civil(now);
59
+ const today = Math.floor(localNow / DAY) * DAY;
60
+ const minuteNow = (localNow - today) / 60000;
61
+ const workday = (day) => settings.weekdays.includes(new Date(day).getUTCDay());
62
+ let shiftDay = today;
63
+ if (overnight && minuteNow < start) {
64
+ // Retain yesterday's finished work shift until the next shift starts. If
65
+ // yesterday was off, a working today is 'before' (e.g. Monday daytime).
66
+ if (minuteNow < end || workday(today - DAY)) shiftDay -= DAY;
67
+ }
68
+ const isWorkday = workday(shiftDay);
69
+ const shiftStart = instant(shiftDay + start * 60000);
70
+ const shiftEnd = instant(shiftDay + (start + duration) * 60000);
71
+ const breakStart = breakDuration ? instant(shiftDay + (start + breakOffset) * 60000) : null;
72
+ const breakEnd = breakDuration
73
+ ? instant(shiftDay + (start + breakOffset + breakDuration) * 60000)
74
+ : null;
75
+ const breakMs = breakDuration ? breakEnd - breakStart : 0;
76
+ const totalMs = shiftEnd - shiftStart - breakMs;
77
+ if (totalMs <= 0 || breakMs < 0) throw new RangeError('Shift has no paid duration');
78
+ const clampedNow = Math.max(shiftStart, Math.min(now, shiftEnd));
79
+ const elapsedMs = isWorkday
80
+ ? Math.max(
81
+ 0,
82
+ Math.min(
83
+ totalMs,
84
+ clampedNow -
85
+ shiftStart -
86
+ (breakDuration ? Math.max(0, Math.min(clampedNow, breakEnd) - breakStart) : 0),
87
+ ),
88
+ )
89
+ : 0;
90
+ const status = !isWorkday
91
+ ? 'rest'
92
+ : now < shiftStart
93
+ ? 'before'
94
+ : now >= shiftEnd
95
+ ? 'done'
96
+ : breakDuration && now >= breakStart && now < breakEnd
97
+ ? 'lunch'
98
+ : 'working';
99
+ // Decimal inputs become exact rational numbers before truncation. Never use
100
+ // floor((salary / days * progress) * 100): binary rounding loses whole cents.
101
+ const rational = (number) => {
102
+ if (typeof number !== 'number' || !Number.isFinite(number) || number < 0)
103
+ throw new RangeError('Invalid salary');
104
+ const [mantissa, exponent = '0'] = String(number).toLowerCase().split('e');
105
+ const [integer, fraction = ''] = mantissa.split('.');
106
+ const scale = fraction.length - Number(exponent);
107
+ return scale >= 0
108
+ ? [BigInt(integer + fraction), 10n ** BigInt(scale)]
109
+ : [BigInt(integer + fraction) * 10n ** BigInt(-scale), 1n];
110
+ };
111
+ const payMode = settings.payMode === 'daily' ? 'daily' : 'monthly';
112
+ let [numerator, denominator] = rational(
113
+ payMode === 'daily' ? settings.dailySalary : settings.monthlySalary,
114
+ );
115
+ if (payMode === 'monthly') {
116
+ const [daysN, daysD] = rational(settings.workdaysPerMonth);
117
+ if (daysN === 0n) throw new RangeError('Workdays per month must be positive');
118
+ numerator *= daysD;
119
+ denominator *= daysN;
120
+ }
121
+ const dailyCents = Number((numerator * 100n) / denominator);
122
+ const earnedCents = Math.min(
123
+ dailyCents,
124
+ Number((numerator * 100n * BigInt(Math.floor(elapsedMs))) / (denominator * BigInt(totalMs))),
125
+ );
126
+ const hourlyCents = Number((numerator * 100n * 3600000n) / (denominator * BigInt(totalMs)));
127
+ const dateString = (day) => new Date(day).toISOString().slice(0, 10);
128
+ return {
129
+ status,
130
+ remaining: isWorkday ? Math.max(0, Math.ceil((shiftEnd - now) / 1000)) : 0,
131
+ startRemaining: status === 'before' ? Math.max(0, Math.ceil((shiftStart - now) / 1000)) : 0,
132
+ progress: elapsedMs / totalMs,
133
+ earned: earnedCents / 100,
134
+ daily: dailyCents / 100,
135
+ hourly: hourlyCents / 100,
136
+ date: dateString(today),
137
+ shiftDate: dateString(shiftDay),
138
+ earnedCents,
139
+ dailyCents,
140
+ payMode,
141
+ isWorkday,
142
+ overnight,
143
+ shiftStart,
144
+ shiftEnd,
145
+ breakStart,
146
+ breakEnd,
147
+ elapsed: elapsedMs / 1000,
148
+ total: totalMs / 1000,
149
+ };
150
+ }
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: offwork-clock
3
+ name: 'dsh-offwork'
4
+ config: {}
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#167a69"/><circle cx="29" cy="28" r="18" fill="none" stroke="#fff" stroke-width="4"/><path d="M29 17v12l8 5" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round"/><circle cx="46" cy="46" r="13" fill="#f6d376"/><path d="m40 40 6 7 6-7m-6 7v8m-6-7h12m-12 4h12" fill="none" stroke="#31534a" stroke-width="2.5"/></svg>
package/index.js ADDED
@@ -0,0 +1,274 @@
1
+ import { readFile, writeFile, rename, unlink, chmod } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const inject = ['commands', 'tools'];
7
+
8
+ export const DEFAULT_SETTINGS = Object.freeze({
9
+ payMode: 'monthly',
10
+ monthlySalary: 10000,
11
+ dailySalary: 400,
12
+ workdaysPerMonth: 21.75,
13
+ start: '09:00',
14
+ end: '18:00',
15
+ breakStart: '12:00',
16
+ breakEnd: '13:00',
17
+ weekdays: Object.freeze([1, 2, 3, 4, 5]),
18
+ timezone: 'Asia/Shanghai',
19
+ });
20
+
21
+ const dataFile = new URL('./data.json', import.meta.url);
22
+ const keys = Object.keys(DEFAULT_SETTINGS);
23
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
24
+ const fail = (error) => ({
25
+ ok: false,
26
+ error: error instanceof Error ? error.message : String(error),
27
+ });
28
+
29
+ function validatePatch(value) {
30
+ if (!isObject(value)) throw new Error('settings 必须是 JSON 对象。');
31
+ for (const key of Object.keys(value)) {
32
+ if (!keys.includes(key)) throw new Error(`未知配置字段:${key}`);
33
+ }
34
+ }
35
+
36
+ export function validateSettings(value) {
37
+ validatePatch(value);
38
+ for (const key of keys) {
39
+ if (!Object.hasOwn(value, key)) throw new Error(`缺少配置字段:${key}`);
40
+ }
41
+ if (value.payMode !== 'monthly' && value.payMode !== 'daily') {
42
+ throw new Error('payMode 必须是 monthly 或 daily。');
43
+ }
44
+ if (
45
+ typeof value.dailySalary !== 'number' ||
46
+ !Number.isFinite(value.dailySalary) ||
47
+ value.dailySalary < 0
48
+ ) {
49
+ throw new Error('dailySalary 必须是大于等于 0 的有限数字。');
50
+ }
51
+ if (
52
+ typeof value.monthlySalary !== 'number' ||
53
+ !Number.isFinite(value.monthlySalary) ||
54
+ value.monthlySalary < 0
55
+ ) {
56
+ throw new Error('monthlySalary 必须是大于等于 0 的有限数字。');
57
+ }
58
+ if (
59
+ typeof value.workdaysPerMonth !== 'number' ||
60
+ !Number.isFinite(value.workdaysPerMonth) ||
61
+ value.workdaysPerMonth <= 0
62
+ ) {
63
+ throw new Error('workdaysPerMonth 必须是大于 0 的有限数字。');
64
+ }
65
+ const minutes = (key) => {
66
+ if (typeof value[key] !== 'string' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value[key])) {
67
+ throw new Error(`${key} 必须是 24 小时制 HH:mm。`);
68
+ }
69
+ const [hour, minute] = value[key].split(':').map(Number);
70
+ return hour * 60 + minute;
71
+ };
72
+ const start = minutes('start');
73
+ const end = minutes('end');
74
+ const breakStart = minutes('breakStart');
75
+ const breakEnd = minutes('breakEnd');
76
+ if (end === start) throw new Error('start 和 end 不能相同。');
77
+ const relative = (minute) => (minute - start + 1440) % 1440;
78
+ const duration = relative(end);
79
+ if (breakStart !== breakEnd) {
80
+ const from = relative(breakStart);
81
+ const to = relative(breakEnd);
82
+ if (from >= to || to > duration) {
83
+ throw new Error('午休必须按班次起点顺序落在班次内。');
84
+ }
85
+ if (to - from >= duration) throw new Error('午休不能占满整个班次。');
86
+ }
87
+ if (
88
+ !Array.isArray(value.weekdays) ||
89
+ value.weekdays.length === 0 ||
90
+ value.weekdays.some((day) => !Number.isInteger(day) || day < 0 || day > 6) ||
91
+ new Set(value.weekdays).size !== value.weekdays.length
92
+ ) {
93
+ throw new Error('weekdays 必须是非空、不重复的 0–6 整数数组(0 为周日)。');
94
+ }
95
+ if (
96
+ typeof value.timezone !== 'string' ||
97
+ value.timezone.length === 0 ||
98
+ value.timezone.trim() !== value.timezone
99
+ ) {
100
+ throw new Error('timezone 必须是有效时区名称。');
101
+ }
102
+ try {
103
+ new Intl.DateTimeFormat('en', { timeZone: value.timezone });
104
+ } catch {
105
+ throw new Error('timezone 必须是有效时区名称。');
106
+ }
107
+ return { ...value, weekdays: [...value.weekdays] };
108
+ }
109
+
110
+ // One local persistence owner, shared by the command and tool adapters.
111
+ // Reads never persist defaults. Writes are serialized and atomically replace a 0600 file.
112
+ export function createOperations(dataFileArg = dataFile) {
113
+ const target = dataFileArg instanceof URL ? fileURLToPath(dataFileArg) : resolve(dataFileArg);
114
+ let queue = Promise.resolve();
115
+ async function read() {
116
+ let text;
117
+ try {
118
+ text = await readFile(target, 'utf8');
119
+ } catch (error) {
120
+ if (error.code === 'ENOENT')
121
+ return { settings: validateSettings(DEFAULT_SETTINGS), configured: false };
122
+ throw new Error('无法读取本机配置。');
123
+ }
124
+ try {
125
+ const stored = JSON.parse(text);
126
+ validatePatch(stored);
127
+ // Only the newly introduced fields are optional in legacy files.
128
+ const settings = validateSettings({
129
+ payMode: DEFAULT_SETTINGS.payMode,
130
+ dailySalary: DEFAULT_SETTINGS.dailySalary,
131
+ ...stored,
132
+ });
133
+ return { settings, configured: true };
134
+ } catch {
135
+ throw new Error('本机配置损坏或无效;请检查插件目录 data.json。');
136
+ }
137
+ }
138
+ async function write(settings) {
139
+ const temp = join(dirname(target), `.data-${randomUUID()}.tmp`);
140
+ try {
141
+ await writeFile(temp, `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
142
+ await chmod(temp, 0o600);
143
+ await rename(temp, target);
144
+ } catch {
145
+ throw new Error('无法保存本机配置。');
146
+ } finally {
147
+ await unlink(temp).catch(() => {});
148
+ }
149
+ }
150
+ return function operate(action, patch) {
151
+ const operation = queue.then(async () => {
152
+ try {
153
+ if (action !== 'get' && action !== 'set') throw new Error('action 必须是 get 或 set。');
154
+ if (action === 'get' && patch !== undefined) throw new Error('get 不接受 settings。');
155
+ if (action === 'set') validatePatch(patch);
156
+ const current = await read();
157
+ if (action === 'get') return { ok: true, ...current };
158
+ const settings = validateSettings({ ...current.settings, ...patch });
159
+ await write(settings);
160
+ return { ok: true, settings, configured: true };
161
+ } catch (error) {
162
+ return fail(error);
163
+ }
164
+ });
165
+ queue = operation.then(
166
+ () => {},
167
+ () => {},
168
+ );
169
+ return operation;
170
+ };
171
+ }
172
+
173
+ const settingsSchema = {
174
+ type: 'object',
175
+ additionalProperties: false,
176
+ description: '要合并保存的配置字段。时间使用 HH:mm。',
177
+ properties: {
178
+ payMode: {
179
+ type: 'string',
180
+ enum: ['monthly', 'daily'],
181
+ description: '计薪方式,默认 monthly(月薪);daily 为日薪。',
182
+ },
183
+ dailySalary: { type: 'number', description: '日薪,有限数字且 >= 0,默认 400。' },
184
+ monthlySalary: { type: 'number', description: '月薪,有限数字且 >= 0。' },
185
+ workdaysPerMonth: { type: 'number', description: '每月工作日数,有限数字且 > 0。' },
186
+ start: { type: 'string', description: '上班时间 HH:mm。' },
187
+ end: { type: 'string', description: '下班时间 HH:mm;早于上班表示次日,不能与上班相同。' },
188
+ breakStart: { type: 'string', description: '休息开始 HH:mm。' },
189
+ breakEnd: {
190
+ type: 'string',
191
+ description: '休息结束 HH:mm;与开始相同即关闭,否则按班次顺序在班次内,且不能占满班次。',
192
+ },
193
+ weekdays: {
194
+ type: 'array',
195
+ items: { type: 'integer', enum: [0, 1, 2, 3, 4, 5, 6] },
196
+ description: '非空、不重复;0 为周日,1 为周一。',
197
+ },
198
+ timezone: { type: 'string', description: '有效时区,例如 Asia/Shanghai。' },
199
+ },
200
+ };
201
+
202
+ export function apply(ctx) {
203
+ const operate = createOperations();
204
+ ctx.effect(() =>
205
+ ctx.commands.register({
206
+ name: 'offwork-clock',
207
+ description: '读取或保存本机下班时钟配置:get 或 set JSON。',
208
+ input: { hint: 'get | set {"monthlySalary":10000}' },
209
+ recordInput: false,
210
+ async handler({ rawInput }) {
211
+ let result;
212
+ try {
213
+ const match = /^(get|set)(?:\s+([\s\S]*))?$/.exec(rawInput.trim());
214
+ if (!match) throw new Error('用法:/offwork-clock get 或 /offwork-clock set JSON');
215
+ const [, action, json] = match;
216
+ if (action === 'get' && json !== undefined) throw new Error('get 不接受参数。');
217
+ if (action === 'set' && !json?.trim()) throw new Error('set 需要 JSON 配置对象。');
218
+ result = await operate(action, action === 'set' ? JSON.parse(json) : undefined);
219
+ } catch (error) {
220
+ result = fail(error);
221
+ }
222
+ return { kind: result.ok ? 'success' : 'error', text: JSON.stringify(result) };
223
+ },
224
+ }),
225
+ );
226
+ ctx.effect(() =>
227
+ ctx.tools.register({
228
+ name: 'offwork_clock',
229
+ description:
230
+ '读取或更新下班时钟的工资与班次配置。get 返回配置及 configured(是否已有保存文件);set 合并保存。配置保存在运行 Harness 的机器上,调用及结果会进入会话记录。',
231
+ parameters: {
232
+ type: 'object',
233
+ additionalProperties: false,
234
+ required: ['action'],
235
+ properties: {
236
+ action: { type: 'string', enum: ['get', 'set'], description: 'get 读取;set 更新。' },
237
+ settings: settingsSchema,
238
+ },
239
+ },
240
+ output: {
241
+ schema: {
242
+ oneOf: [
243
+ {
244
+ type: 'object',
245
+ additionalProperties: false,
246
+ required: ['ok', 'settings', 'configured'],
247
+ properties: {
248
+ ok: { type: 'boolean', const: true },
249
+ settings: { ...settingsSchema, required: keys },
250
+ configured: { type: 'boolean' },
251
+ },
252
+ },
253
+ {
254
+ type: 'object',
255
+ additionalProperties: false,
256
+ required: ['ok', 'error'],
257
+ properties: { ok: { type: 'boolean', const: false }, error: { type: 'string' } },
258
+ },
259
+ ],
260
+ },
261
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
262
+ },
263
+ async execute(args) {
264
+ if (
265
+ !isObject(args) ||
266
+ Object.keys(args).some((key) => key !== 'action' && key !== 'settings')
267
+ ) {
268
+ return fail('参数必须是仅含 action 和可选 settings 的对象。');
269
+ }
270
+ return operate(args.action, args.settings);
271
+ },
272
+ }),
273
+ );
274
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Offwork Clock",
4
+ "description": "A draggable countdown to clock-out with live estimated earnings and salary settings."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "下班计时器",
4
+ "description": "可拖动的下班倒计时与工资悬浮窗,支持月薪/日薪、夜班、工作日、可选休息扣除、金额隐藏与位置记忆。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "dsh-offwork",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "下班倒计时与实时工资悬浮窗:可拖动、可调透明度、工资可隐藏。A draggable countdown and salary overlay for DeepSeek Harness.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "now",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/SnowBeatRain/dsh-offwork.git"
11
+ },
12
+ "homepage": "https://github.com/SnowBeatRain/dsh-offwork#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/SnowBeatRain/dsh-offwork/issues"
15
+ },
16
+ "keywords": [
17
+ "deepseek-harness",
18
+ "dsh-plugin",
19
+ "dsh-widget",
20
+ "countdown",
21
+ "salary",
22
+ "offwork",
23
+ "overlay"
24
+ ],
25
+ "engines": {
26
+ "dsh": ">=0.2.1-rc.5 <0.3.0-0"
27
+ },
28
+ "exports": {
29
+ ".": "./index.js",
30
+ "./client": "./client.js",
31
+ "./locale/*.json": "./locale/*.json",
32
+ "./icon": "./icon.svg",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "index.js",
37
+ "client.js",
38
+ "client.source.js",
39
+ "clock.js",
40
+ "ui-utils.js",
41
+ "cordis.patch.yml",
42
+ "locale/*.json",
43
+ "icon.svg",
44
+ "LICENSE",
45
+ "README.md",
46
+ "CHANGELOG.md",
47
+ "tests/*.mjs",
48
+ "tools/*.mjs"
49
+ ],
50
+ "scripts": {
51
+ "build": "node tools/build.mjs",
52
+ "format": "prettier --write . && npm run build",
53
+ "format:check": "prettier --check .",
54
+ "test": "node tools/build.mjs --check && node --test tests/*.mjs",
55
+ "check:package": "node tools/check-package.mjs",
56
+ "check": "npm run format:check && npm test && npm run check:package",
57
+ "prepublishOnly": "npm run build && npm run check"
58
+ },
59
+ "dsh": {
60
+ "bundle": {
61
+ "patch": "./cordis.patch.yml"
62
+ },
63
+ "client": {
64
+ "platform": "web",
65
+ "immediately": true,
66
+ "inject": [
67
+ "@deepseek-ai/dsh-client-ui-conversation",
68
+ "@deepseek-ai/dsh-api-remotes"
69
+ ]
70
+ }
71
+ },
72
+ "devDependencies": {
73
+ "prettier": "3.9.10"
74
+ }
75
+ }