kalvium-worklog 1.4.5 → 1.7.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.
package/dist/scheduler.js CHANGED
@@ -2,13 +2,20 @@ import { homedir, platform } from "os";
2
2
  import { join } from "path";
3
3
  import { writeFileSync, existsSync, mkdirSync } from "fs";
4
4
  import { execSync } from "child_process";
5
- import { INSTALL_DIR, LOG_FILE, ensureInstallDir } from "./config.js";
5
+ import { INSTALL_DIR, LOG_FILE, ensureInstallDir, saveSchedule } from "./config.js";
6
6
  import { dirname } from "path";
7
7
  import { fileURLToPath } from "url";
8
8
  const __dirname = dirname(fileURLToPath(import.meta.url));
9
9
  const IS_MAC = platform() === "darwin";
10
10
  const IS_WINDOWS = platform() === "win32";
11
11
  const IS_LINUX = platform() === "linux";
12
+ const LAUNCHD_DOMAIN = `gui/${process.getuid?.() ?? 0}`;
13
+ function nodeExecutable() {
14
+ const stablePaths = IS_MAC
15
+ ? ["/opt/homebrew/bin/node", "/usr/local/bin/node"]
16
+ : [];
17
+ return stablePaths.find((path) => existsSync(path)) ?? process.execPath;
18
+ }
12
19
  /**
13
20
  * Set up daily auto-submit scheduler.
14
21
  * macOS: launchd
@@ -17,6 +24,7 @@ const IS_LINUX = platform() === "linux";
17
24
  */
18
25
  export async function setupScheduler(options) {
19
26
  const { hour, minute } = options;
27
+ saveSchedule({ hour, minute });
20
28
  if (IS_MAC) {
21
29
  return setupLaunchd(hour, minute);
22
30
  }
@@ -43,6 +51,8 @@ function formatTime(hour, minute) {
43
51
  function copyDailyScript() {
44
52
  ensureInstallDir();
45
53
  const distDir = __dirname;
54
+ // Generated wrappers are ESM but live outside the npm package.
55
+ writeFileSync(join(INSTALL_DIR, "package.json"), '{"type":"module"}\n');
46
56
  // Daily submit wrapper
47
57
  const dailyDst = join(INSTALL_DIR, "daily_submit.js");
48
58
  const dailyWrapper = `#!/usr/bin/env node
@@ -68,8 +78,21 @@ function setupLaunchd(hour, minute) {
68
78
  }
69
79
  const dailyScript = copyDailyScript();
70
80
  const catchupScript = join(INSTALL_DIR, "catchup_submit.js");
81
+ const nodePath = nodeExecutable();
71
82
  // ─── 1. Scheduled daily plist (fires at chosen time) ────────────────────
72
83
  const plistPath = join(launchAgentsDir, "com.kalvium.worklog.plist");
84
+ // launchd uses 1 for Sunday, so Monday through Friday are 2 through 6.
85
+ const weekdayIntervals = [2, 3, 4, 5, 6]
86
+ .map((weekday) => `
87
+ <dict>
88
+ <key>Hour</key>
89
+ <integer>${hour}</integer>
90
+ <key>Minute</key>
91
+ <integer>${minute}</integer>
92
+ <key>Weekday</key>
93
+ <integer>${weekday}</integer>
94
+ </dict>`)
95
+ .join("");
73
96
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
74
97
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
75
98
  <plist version="1.0">
@@ -78,24 +101,12 @@ function setupLaunchd(hour, minute) {
78
101
  <string>com.kalvium.worklog</string>
79
102
  <key>ProgramArguments</key>
80
103
  <array>
81
- <string>${process.execPath}</string>
104
+ <string>${nodePath}</string>
82
105
  <string>${dailyScript}</string>
83
106
  </array>
84
107
  <key>StartCalendarInterval</key>
85
- <dict>
86
- <key>Hour</key>
87
- <integer>${hour}</integer>
88
- <key>Minute</key>
89
- <integer>${minute}</integer>
90
- <key>Weekday</key>
91
- <array>
92
- <integer>1</integer>
93
- <integer>2</integer>
94
- <integer>3</integer>
95
- <integer>4</integer>
96
- <integer>5</integer>
97
- </array>
98
- </dict>
108
+ <array>${weekdayIntervals}
109
+ </array>
99
110
  <key>StandardOutPath</key>
100
111
  <string>${LOG_FILE}</string>
101
112
  <key>StandardErrorPath</key>
@@ -110,8 +121,16 @@ function setupLaunchd(hour, minute) {
110
121
  </dict>
111
122
  </plist>`;
112
123
  writeFileSync(plistPath, plist);
113
- execSync(`launchctl unload "${plistPath}"`, { stdio: "ignore" });
114
- execSync(`launchctl load "${plistPath}"`, { stdio: "ignore" });
124
+ unloadLaunchAgent(plistPath);
125
+ try {
126
+ execSync(`launchctl bootstrap ${LAUNCHD_DOMAIN} "${plistPath}"`, {
127
+ stdio: "ignore",
128
+ });
129
+ }
130
+ catch (error) {
131
+ console.log(`Failed to load daily scheduler: ${String(error)}`);
132
+ return false;
133
+ }
115
134
  // ─── 2. Catch-up plist (fires on login/wake — RunAtLoad) ────────────────
116
135
  // This checks if today's worklog was already submitted. If not, submits it.
117
136
  // Handles the case where the scheduled time was missed (laptop asleep/offline).
@@ -124,7 +143,7 @@ function setupLaunchd(hour, minute) {
124
143
  <string>com.kalvium.worklog.catchup</string>
125
144
  <key>ProgramArguments</key>
126
145
  <array>
127
- <string>${process.execPath}</string>
146
+ <string>${nodePath}</string>
128
147
  <string>${catchupScript}</string>
129
148
  </array>
130
149
  <key>RunAtLoad</key>
@@ -145,17 +164,45 @@ function setupLaunchd(hour, minute) {
145
164
  </dict>
146
165
  </plist>`;
147
166
  writeFileSync(catchupPlistPath, catchupPlist);
148
- execSync(`launchctl unload "${catchupPlistPath}"`, { stdio: "ignore" });
149
- execSync(`launchctl load "${catchupPlistPath}"`, { stdio: "ignore" });
150
- console.log(`Daily auto-submit installed (${formatTime(hour, minute)} every weekday)`);
167
+ unloadLaunchAgent(catchupPlistPath);
168
+ try {
169
+ execSync(`launchctl bootstrap ${LAUNCHD_DOMAIN} "${catchupPlistPath}"`, {
170
+ stdio: "ignore",
171
+ });
172
+ }
173
+ catch (error) {
174
+ console.log(`Failed to load catch-up scheduler: ${String(error)}`);
175
+ return false;
176
+ }
177
+ // Start one check immediately. RunAtLoad is not reliable when an agent is
178
+ // registered after the user session has already started.
179
+ try {
180
+ execSync(`launchctl kickstart -k ${LAUNCHD_DOMAIN}/com.kalvium.worklog.catchup`, { stdio: "ignore" });
181
+ }
182
+ catch (error) {
183
+ console.log(`Failed to start catch-up check: ${String(error)}`);
184
+ return false;
185
+ }
186
+ console.log(`Daily auto-submit installed (${formatTime(hour, minute)} Monday-Friday)`);
151
187
  console.log(" + Catch-up check on login/wake (every 30 min)");
152
188
  return true;
153
189
  }
190
+ function unloadLaunchAgent(plistPath) {
191
+ try {
192
+ execSync(`launchctl bootout ${LAUNCHD_DOMAIN} "${plistPath}"`, {
193
+ stdio: "ignore",
194
+ });
195
+ }
196
+ catch {
197
+ // The task might not have been loaded yet.
198
+ }
199
+ }
154
200
  function setupTaskScheduler(hour, minute) {
155
201
  const dailyScript = copyDailyScript();
202
+ const nodePath = nodeExecutable();
156
203
  const batPath = join(INSTALL_DIR, "daily_submit.bat");
157
204
  // Create batch wrapper
158
- writeFileSync(batPath, `@echo off\r\n"${process.execPath}" "${dailyScript}"\r\n`);
205
+ writeFileSync(batPath, `@echo off\r\n"${nodePath}" "${dailyScript}"\r\n`);
159
206
  // Remove existing task
160
207
  try {
161
208
  execSync('schtasks /Delete /TN "KalviumWorklog" /F', { stdio: "ignore" });
@@ -178,7 +225,7 @@ function setupTaskScheduler(hour, minute) {
178
225
  }
179
226
  function setupCron(hour, minute) {
180
227
  const dailyScript = copyDailyScript();
181
- const cronLine = `${minute} ${hour} * * 1-5 ${process.execPath} ${dailyScript} >> ${LOG_FILE} 2>&1`;
228
+ const cronLine = `${minute} ${hour} * * 1-5 ${nodeExecutable()} ${dailyScript} >> ${LOG_FILE} 2>&1`;
182
229
  // Read existing crontab
183
230
  let crontab = "";
184
231
  try {
@@ -207,7 +254,7 @@ export async function removeScheduler() {
207
254
  // Remove daily plist
208
255
  const plistPath = join(homedir(), "Library/LaunchAgents/com.kalvium.worklog.plist");
209
256
  try {
210
- execSync(`launchctl unload "${plistPath}"`, { stdio: "ignore" });
257
+ execSync(`launchctl bootout ${LAUNCHD_DOMAIN} "${plistPath}"`, { stdio: "ignore" });
211
258
  }
212
259
  catch {
213
260
  // ignore
@@ -218,7 +265,7 @@ export async function removeScheduler() {
218
265
  // Remove catch-up plist
219
266
  const catchupPlistPath = join(homedir(), "Library/LaunchAgents/com.kalvium.worklog.catchup.plist");
220
267
  try {
221
- execSync(`launchctl unload "${catchupPlistPath}"`, { stdio: "ignore" });
268
+ execSync(`launchctl bootout ${LAUNCHD_DOMAIN} "${catchupPlistPath}"`, { stdio: "ignore" });
222
269
  }
223
270
  catch {
224
271
  // ignore
package/dist/submit.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export interface SubmitOptions {
2
2
  text?: string;
3
3
  dryRun?: boolean;
4
+ allowInteractiveLogin?: boolean;
4
5
  }
5
6
  export interface SubmitResult {
6
7
  success: boolean;
@@ -22,7 +23,9 @@ export declare function checkStatus(): Promise<void>;
22
23
  * Skips weekends. Logs to file.
23
24
  * Retries on network failure (up to 5 times with 60s delay).
24
25
  */
25
- export declare function dailySubmit(): Promise<boolean>;
26
+ export declare function dailySubmit(options?: {
27
+ allowInteractiveLogin?: boolean;
28
+ }): Promise<boolean>;
26
29
  /**
27
30
  * Catch-up check: if it's a weekday and today's worklog hasn't been
28
31
  * submitted yet, submit it. Used on login/wake to handle missed runs.
package/dist/submit.js CHANGED
@@ -1,4 +1,4 @@
1
- import { getWorklogApi, log } from "./config.js";
1
+ import { getCatchupDate, getLocalDate, getWorklogApi, loadSchedule, log, setCatchupDate, } from "./config.js";
2
2
  import { refreshToken } from "./refresh.js";
3
3
  import { captureToken } from "./capture-token.js";
4
4
  const STATUS_KEY = "on_site";
@@ -11,6 +11,7 @@ const STATUS_LABEL = "Working on-site (Company location)";
11
11
  export async function submitWorklog(options = {}) {
12
12
  const text = options.text ?? "Working on assigned task";
13
13
  const dryRun = options.dryRun ?? false;
14
+ const allowInteractiveLogin = options.allowInteractiveLogin ?? true;
14
15
  const worklogApi = getWorklogApi();
15
16
  if (!worklogApi) {
16
17
  return {
@@ -25,7 +26,7 @@ export async function submitWorklog(options = {}) {
25
26
  timeSpent: 0,
26
27
  priorityLevel: "medium",
27
28
  blockers: "",
28
- worklogs: JSON.stringify({ content: `<p>${text}</p>` }),
29
+ worklogs: JSON.stringify({ content: `<p>${escapeHtml(text)}</p>` }),
29
30
  });
30
31
  if (dryRun) {
31
32
  console.log(`[DRY RUN] Would submit to ${worklogApi}`);
@@ -41,17 +42,20 @@ export async function submitWorklog(options = {}) {
41
42
  // Step 1: Refresh token
42
43
  const refreshResult = await refreshToken();
43
44
  if (!refreshResult.success || !refreshResult.accessToken) {
44
- if (attempt === 0) {
45
+ if (refreshResult.networkError) {
46
+ return {
47
+ success: false,
48
+ message: `Network error while refreshing token: ${refreshResult.error ?? "connection failed"}`,
49
+ };
50
+ }
51
+ if (attempt === 0 && allowInteractiveLogin) {
45
52
  console.log("Token expired. Auto re-logging in via browser...");
46
53
  const reloginOk = await captureToken();
47
54
  if (reloginOk)
48
55
  continue;
49
56
  return { success: false, message: "Re-login failed" };
50
57
  }
51
- return {
52
- success: false,
53
- message: refreshResult.error ?? "Token refresh failed",
54
- };
58
+ return { success: false, message: authenticationMessage(refreshResult.error) };
55
59
  }
56
60
  // Step 2: Submit worklog
57
61
  console.log(`Submitting worklog: '${text}'...`);
@@ -78,7 +82,7 @@ export async function submitWorklog(options = {}) {
78
82
  };
79
83
  }
80
84
  // 401/403 = token invalid — try re-login
81
- if ((res.status === 401 || res.status === 403) && attempt === 0) {
85
+ if ((res.status === 401 || res.status === 403) && attempt === 0 && allowInteractiveLogin) {
82
86
  console.log(`Got HTTP ${res.status}. Token may be invalid. Trying re-login...`);
83
87
  const reloginOk = await captureToken();
84
88
  if (reloginOk)
@@ -116,6 +120,10 @@ export async function checkStatus() {
116
120
  for (let attempt = 0; attempt < 2; attempt++) {
117
121
  const refreshResult = await refreshToken();
118
122
  if (!refreshResult.success || !refreshResult.accessToken) {
123
+ if (refreshResult.networkError) {
124
+ console.log(`ERROR: Network error while refreshing token: ${refreshResult.error}`);
125
+ return;
126
+ }
119
127
  if (attempt === 0) {
120
128
  console.log("Token expired. Auto re-logging in via browser...");
121
129
  const reloginOk = await captureToken();
@@ -146,7 +154,7 @@ export async function checkStatus() {
146
154
  console.log("ERROR: Invalid response");
147
155
  return;
148
156
  }
149
- const today = new Date().toISOString().slice(0, 10);
157
+ const today = getLocalDate();
150
158
  for (const w of worklogs.slice(0, 5)) {
151
159
  const date = (w.worklogDate ?? "").slice(0, 10);
152
160
  const status = w.status ?? "?";
@@ -172,7 +180,7 @@ export async function checkStatus() {
172
180
  * Skips weekends. Logs to file.
173
181
  * Retries on network failure (up to 5 times with 60s delay).
174
182
  */
175
- export async function dailySubmit() {
183
+ export async function dailySubmit(options = {}) {
176
184
  const day = new Date().getDay();
177
185
  if (day === 0 || day === 6) {
178
186
  log("[INFO] Weekend - skipping");
@@ -189,19 +197,25 @@ export async function dailySubmit() {
189
197
  }
190
198
  const result = await submitWorklog({
191
199
  text: "Working on assigned task",
200
+ // A persistent Google session can restore an expired Kalvium token
201
+ // without user input. If Google needs a password or 2FA, the browser
202
+ // remains available for the user to complete that security check.
203
+ allowInteractiveLogin: options.allowInteractiveLogin ?? true,
192
204
  });
193
205
  if (result.success) {
194
206
  log(`[INFO] SUCCESS: ${result.message}`);
195
207
  return true;
196
208
  }
197
209
  // Check if it's a network error (retry) vs a real error (give up)
198
- const isNetworkError = result.message.includes("fetch") ||
199
- result.message.includes("ECONNREFUSED") ||
200
- result.message.includes("ENOTFOUND") ||
201
- result.message.includes("ETIMEDOUT") ||
202
- result.message.includes("network") ||
203
- result.message.includes("Failed to fetch") ||
204
- result.message.includes("refresh failed");
210
+ const isAuthenticationError = result.message.startsWith("Authentication expired");
211
+ const isNetworkError = !isAuthenticationError &&
212
+ (result.message.includes("fetch") ||
213
+ result.message.includes("ECONNREFUSED") ||
214
+ result.message.includes("ENOTFOUND") ||
215
+ result.message.includes("ETIMEDOUT") ||
216
+ result.message.includes("network") ||
217
+ result.message.includes("Failed to fetch") ||
218
+ result.message.includes("refresh failed"));
205
219
  // "Already submitted" is a success, not an error
206
220
  if (result.message.includes("Already submitted")) {
207
221
  log(`[INFO] ${result.message}`);
@@ -218,6 +232,16 @@ export async function dailySubmit() {
218
232
  }
219
233
  return false;
220
234
  }
235
+ function authenticationMessage(reason) {
236
+ const detail = reason ? ` (${reason})` : "";
237
+ return `Authentication expired${detail}. Run \`kalvium-worklog login\` while you are at your computer, then retry.`;
238
+ }
239
+ function escapeHtml(value) {
240
+ const entities = {
241
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
242
+ };
243
+ return value.replace(/[&<>\"']/g, (character) => entities[character]);
244
+ }
221
245
  function sleep(ms) {
222
246
  return new Promise((resolve) => setTimeout(resolve, ms));
223
247
  }
@@ -230,6 +254,17 @@ export async function catchUpSubmit() {
230
254
  if (day === 0 || day === 6) {
231
255
  return true; // weekend, nothing to do
232
256
  }
257
+ const today = getLocalDate();
258
+ if (getCatchupDate() === today)
259
+ return true;
260
+ const schedule = loadSchedule();
261
+ if (schedule) {
262
+ const now = new Date();
263
+ if (now.getHours() * 60 + now.getMinutes() <
264
+ schedule.hour * 60 + schedule.minute) {
265
+ return true;
266
+ }
267
+ }
233
268
  log("[INFO] Catch-up check: verifying today's worklog...");
234
269
  // Check if today's worklog was already submitted
235
270
  const worklogApi = getWorklogApi();
@@ -251,11 +286,11 @@ export async function catchUpSubmit() {
251
286
  if (res.ok) {
252
287
  const worklogs = await res.json();
253
288
  if (Array.isArray(worklogs)) {
254
- const today = new Date().toISOString().slice(0, 10);
255
289
  const todayEntry = worklogs.find((w) => (w.worklogDate ?? "").slice(0, 10) === today &&
256
290
  w.status === "complete");
257
291
  if (todayEntry) {
258
292
  log("[INFO] Today's worklog already submitted. No catch-up needed.");
293
+ setCatchupDate(today);
259
294
  return true;
260
295
  }
261
296
  }
@@ -268,5 +303,8 @@ export async function catchUpSubmit() {
268
303
  }
269
304
  // Today's worklog is missing — submit it
270
305
  log("[INFO] Today's worklog is missing. Running catch-up submit...");
271
- return dailySubmit();
306
+ const submitted = await dailySubmit();
307
+ if (submitted)
308
+ setCatchupDate(today);
309
+ return submitted;
272
310
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kalvium-worklog",
3
- "version": "1.4.5",
3
+ "version": "1.7.0",
4
4
  "description": "Auto-submit your daily Kalvium worklog without opening the website",
5
5
  "keywords": [
6
6
  "kalvium",
@@ -37,10 +37,8 @@
37
37
  "postinstall": "node dist/postinstall.js"
38
38
  },
39
39
  "dependencies": {
40
- "commander": "^12.1.0"
41
- },
42
- "optionalDependencies": {
43
- "playwright": "^1.48.0"
40
+ "commander": "^12.1.0",
41
+ "playwright": "^1.64.1"
44
42
  },
45
43
  "devDependencies": {
46
44
  "@types/node": "^22.0.0",