@vite-hub/schedule 0.1.0 → 0.3.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.
Files changed (54) hide show
  1. package/README.md +114 -96
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +6 -2
  4. package/dist/definition.js +47 -1
  5. package/dist/due-BVMRQ93v.js +144 -0
  6. package/dist/durability.d.ts +14 -0
  7. package/dist/durability.js +23 -0
  8. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  9. package/dist/error-diagnostics-Mpeks7J0.js +166 -0
  10. package/dist/index.d.ts +59 -5
  11. package/dist/index.js +27 -2
  12. package/dist/invariant-DolT9EEx.js +22 -0
  13. package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-C0KZZB6v.d.ts} +2 -2
  14. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  15. package/dist/object-Da1zyPCR.js +11 -0
  16. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  17. package/dist/{operations-gk2qzhYV.js → operations-DwZWFIUX.js} +75 -22
  18. package/dist/operations.d.ts +27 -4
  19. package/dist/operations.js +127 -730
  20. package/dist/os.d.ts +167 -0
  21. package/dist/os.js +1659 -0
  22. package/dist/runtime/console.d.ts +12 -0
  23. package/dist/runtime/console.js +85 -0
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.d.ts +32 -5
  27. package/dist/runtime/process.js +401 -413
  28. package/dist/runtime/state.d.ts +2 -9
  29. package/dist/runtime/state.js +2 -2
  30. package/dist/runtime/static.d.ts +28 -2
  31. package/dist/runtime/static.js +2 -2
  32. package/dist/runtime.d.ts +34 -32
  33. package/dist/runtime.js +6 -5
  34. package/dist/started-BuGmnus4.js +201 -0
  35. package/dist/started-Bx7MDbrl.js +146 -0
  36. package/dist/{execute-BJrgNgQ0.js → started-errors-p7cu_rI7.js} +69 -20
  37. package/dist/{state-DSxmHPn3.js → state-B-Fuyfb4.js} +42 -22
  38. package/dist/state-Do2wV4Tx.d.ts +49 -0
  39. package/dist/{static-6g82xguw.js → static-DQwzzvPg.js} +63 -42
  40. package/dist/store-Df0-fzCl.d.ts +53 -0
  41. package/dist/time-zone-SBldrUgt.js +59 -0
  42. package/dist/{types-CHdV9FQU.d.ts → types-Cw5LjPuc.d.ts} +62 -8
  43. package/dist/vite.d.ts +255 -2
  44. package/dist/vite.js +5876 -2
  45. package/dist/{wait-until-BmIqRo4x.js → wait-until-Dy4Bn3ZN.js} +26 -1
  46. package/package.json +19 -24
  47. package/dist/definition-CMiOg1lg.js +0 -111
  48. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  49. package/dist/error-diagnostics-in7mif5s.js +0 -45
  50. package/dist/nuxt.d.ts +0 -17
  51. package/dist/nuxt.js +0 -27
  52. package/dist/store-QAOd8bxm.d.ts +0 -11
  53. package/dist/vite-BAVyZ8hZ.d.ts +0 -474
  54. package/dist/vite-BJwZkMrn.js +0 -5193
package/dist/os.js ADDED
@@ -0,0 +1,1659 @@
1
+ import { t as isIanaTimeZone } from "./time-zone-SBldrUgt.js";
2
+ import { t as isRecord } from "./object-Da1zyPCR.js";
3
+ import { n as invariantError } from "./invariant-DolT9EEx.js";
4
+ import { r as timeZoneOffsetMinutes } from "./due-BVMRQ93v.js";
5
+ import { defineErrors } from "@vite-hub/runtime";
6
+ import { parseCronExpression } from "cron-schedule";
7
+ import { homedir, userInfo } from "node:os";
8
+ import { basename, dirname, join, posix, win32 } from "node:path";
9
+ import { mkdir, readFile, realpath, rm, rmdir, writeFile } from "node:fs/promises";
10
+ import { execFile } from "node:child_process";
11
+ import { createHash } from "node:crypto";
12
+ //#region src/os/host.ts
13
+ const generatedHeader = "Generated by ViteHub (@vite-hub/schedule/os). installOsSchedule() replaces this file.";
14
+ /** Path helpers of the target OS, so a fake Windows host gives Windows paths on Linux. */
15
+ function pathsFor(platform) {
16
+ return platform === "win32" ? win32 : posix;
17
+ }
18
+ /** Trims command output for an error, keeping the end. */
19
+ function commandOutput(result) {
20
+ const output = `${result.stderr.trim()}\n${result.stdout.trim()}`.trim();
21
+ return output.length > 2e3 ? `…${output.slice(-2e3)}` : output;
22
+ }
23
+ function exec(file, args, env) {
24
+ return new Promise((resolve) => {
25
+ execFile(file, args, {
26
+ encoding: "utf8",
27
+ env: env ? {
28
+ ...process.env,
29
+ ...env
30
+ } : process.env,
31
+ maxBuffer: 16777216,
32
+ windowsHide: true
33
+ }, (error, stdout, stderr) => {
34
+ if (!error) return resolve({
35
+ code: 0,
36
+ stdout,
37
+ stderr
38
+ });
39
+ resolve({
40
+ code: typeof error.code === "number" ? error.code : 127,
41
+ stdout,
42
+ stderr: stderr || error.message
43
+ });
44
+ });
45
+ });
46
+ }
47
+ function isMissing(error) {
48
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
49
+ }
50
+ async function resolvePath(path) {
51
+ try {
52
+ return await realpath(path);
53
+ } catch (error) {
54
+ if (!isMissing(error)) throw error;
55
+ if (dirname(path) === path) return path;
56
+ return join(await resolvePath(dirname(path)), basename(path));
57
+ }
58
+ }
59
+ function createNodeHost() {
60
+ const user = userInfo().username;
61
+ return {
62
+ platform: process.platform,
63
+ uid: process.getuid?.(),
64
+ user: process.platform === "win32" && process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${user}` : user,
65
+ get homedir() {
66
+ return homedir();
67
+ },
68
+ env: process.env,
69
+ get machineTimeZone() {
70
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
71
+ },
72
+ now: () => /* @__PURE__ */ new Date(),
73
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
74
+ exec,
75
+ fs: {
76
+ async readFile(path) {
77
+ try {
78
+ return await readFile(path, "utf8");
79
+ } catch (error) {
80
+ if (isMissing(error)) return void 0;
81
+ throw error;
82
+ }
83
+ },
84
+ async writeFile(path, content) {
85
+ await mkdir(dirname(path), { recursive: true });
86
+ await writeFile(path, content, {
87
+ encoding: "utf8",
88
+ mode: 420
89
+ });
90
+ },
91
+ async mkdir(path) {
92
+ await mkdir(path, { recursive: true });
93
+ },
94
+ async rm(path) {
95
+ try {
96
+ await rm(path);
97
+ return true;
98
+ } catch (error) {
99
+ if (isMissing(error)) return false;
100
+ throw error;
101
+ }
102
+ },
103
+ async rmdirIfEmpty(path) {
104
+ try {
105
+ await rmdir(path);
106
+ } catch (error) {
107
+ if (isMissing(error) || error instanceof Error && "code" in error && (error.code === "ENOTEMPTY" || error.code === "EEXIST")) return;
108
+ throw error;
109
+ }
110
+ },
111
+ realpath: resolvePath
112
+ }
113
+ };
114
+ }
115
+ //#endregion
116
+ //#region src/os/cron.ts
117
+ const allMonths = range(1, 12);
118
+ const allWeekdays = range(0, 6);
119
+ function range(first, last) {
120
+ return Array.from({ length: last - first + 1 }, (_, index) => first + index);
121
+ }
122
+ /** Reads a five-field cron. Returns `undefined` for anything else. */
123
+ function parseCronFields(cron) {
124
+ if (cron.trim() !== cron || cron.split(/\s+/).length !== 5) return void 0;
125
+ try {
126
+ const parsed = parseCronExpression(cron);
127
+ const sorted = (values) => [...new Set(values)].sort((left, right) => left - right);
128
+ return {
129
+ minutes: sorted(parsed.minutes),
130
+ hours: sorted(parsed.hours),
131
+ days: sorted(parsed.days),
132
+ months: sorted(parsed.months.map((month) => month + 1)),
133
+ weekdays: sorted(parsed.weekdays.map((weekday) => weekday % 7))
134
+ };
135
+ } catch {
136
+ return;
137
+ }
138
+ }
139
+ function isDayRestricted(fields) {
140
+ return fields.days.length !== 31;
141
+ }
142
+ function isWeekdayRestricted(fields) {
143
+ return fields.weekdays.length !== allWeekdays.length;
144
+ }
145
+ function isMonthRestricted(fields) {
146
+ return fields.months.length !== allMonths.length;
147
+ }
148
+ /** True when every day field holds every value, so the cron runs on every day. */
149
+ function runsEveryDay(fields) {
150
+ return !isDayRestricted(fields) && !isWeekdayRestricted(fields) && !isMonthRestricted(fields);
151
+ }
152
+ /** Minutes of the day when the cron runs, sorted. */
153
+ function timesOfDay(fields) {
154
+ return fields.hours.flatMap((hour) => fields.minutes.map((minute) => hour * 60 + minute));
155
+ }
156
+ /** The step of a sorted list of two or more values with equal gaps, else `undefined`. One value has step 0. */
157
+ function arithmeticStep(values) {
158
+ if (values.length < 2) return 0;
159
+ const step = values[1] - values[0];
160
+ return values.every((value, index) => index === 0 || value - values[index - 1] === step) ? step : void 0;
161
+ }
162
+ //#endregion
163
+ //#region src/os/errors.ts
164
+ const platformNames = {
165
+ darwin: "launchd",
166
+ linux: "systemd",
167
+ win32: "Task Scheduler"
168
+ };
169
+ const osScheduleErrors = /*#__PURE__*/ defineErrors({
170
+ docs: "https://vitehub.dev/docs/schedule/diagnostics",
171
+ codes: {
172
+ SCHEDULE_OS_COMMAND_FAILED: {
173
+ why: ({ command, exitCode, output }) => `\`${command}\` failed with exit code ${exitCode}: ${output || "no output"}`,
174
+ fix: "Read the output. On Linux, \"Failed to connect to bus\" means that the user has no systemd user manager: run `loginctl enable-linger <user>`, or run inside a login session with `XDG_RUNTIME_DIR` set. On macOS over SSH, the `gui` domain is missing: log in at the screen once, or install with `scope: \"system\"`.",
175
+ data: (data) => data
176
+ },
177
+ SCHEDULE_OS_CRON_UNSUPPORTED: {
178
+ why: ({ platform, cron, reason }) => `${platformNames[platform]} cannot run the cron "${cron}" exactly: ${reason}`,
179
+ fix: "Rewrite the cron with fewer values, such as one weekday list without a month list, or a step that divides the hour or day evenly. systemd on Linux runs every five-field cron.",
180
+ data: (data) => data
181
+ },
182
+ SCHEDULE_OS_INVALID_OPTIONS: {
183
+ why: ({ problem }) => `The OS timer options are invalid: ${problem}`,
184
+ fix: "Pass a name of letters, digits, \".\", \"_\" and \"-\", a Schedule with a five-field `cron`, and `{ command }` with an absolute program path.",
185
+ data: (data) => data
186
+ },
187
+ SCHEDULE_OS_NAME_TAKEN: {
188
+ why: ({ platform, name, scope, resource }) => `${platformNames[platform]} already has ${resource}, and ViteHub did not install it as the ${scope} timer "${name}". ViteHub replaces and removes only the timers that it installed.`,
189
+ fix: "Pick another name, or remove the existing unit, plist, or task that `error.data.resource` names yourself, then install again.",
190
+ data: (data) => data
191
+ },
192
+ SCHEDULE_OS_OPTION_UNSUPPORTED: {
193
+ why: ({ platform, option, reason }) => `${platformNames[platform]} does not support \`${option}\`: ${reason}`,
194
+ fix: "Remove the option on this operating system, or give it a value that the error names.",
195
+ data: (data) => data
196
+ },
197
+ SCHEDULE_OS_PERMISSION_REQUIRED: {
198
+ why: ({ scope }) => `Installing an OS timer with \`scope: "${scope}"\` needs root or Administrator.`,
199
+ fix: "Run as root (`sudo`) or from an Administrator shell, or install with `scope: \"user\"`.",
200
+ data: (data) => data
201
+ },
202
+ SCHEDULE_OS_PLATFORM_UNSUPPORTED: {
203
+ why: ({ platform }) => `OS timers are not supported on "${platform}".`,
204
+ fix: "Install OS timers on Linux with systemd, macOS, or Windows. On other hosts, run the Schedule with a ViteHub Schedule runtime.",
205
+ data: (data) => data
206
+ },
207
+ SCHEDULE_OS_TIME_ZONE_UNSUPPORTED: {
208
+ why: ({ platform, timeZone, machineTimeZone }) => `${platformNames[platform]} runs timers in the machine time zone "${machineTimeZone}", and the cron gives other runs there than in "${timeZone}".`,
209
+ fix: "Pass `timeZone: \"local\"` to run the cron in the machine time zone, or set `timeZone` to the zone that the cron is for. A Schedule without `timeZone` runs in UTC. A cron that gives the same runs in both zones also works, such as an hourly cron when the zones differ by whole hours. systemd on Linux runs a cron in any time zone.",
210
+ data: (data) => data
211
+ }
212
+ }
213
+ });
214
+ //#endregion
215
+ //#region src/os/time-zone.ts
216
+ const minuteMs = 6e4;
217
+ const dayMs$1 = 1440 * minuteMs;
218
+ const dayMinutes = 1440;
219
+ const sampledDays = 732;
220
+ function modulo(value, size) {
221
+ return (value % size + size) % size;
222
+ }
223
+ /** The minutes, from `from` to `to`, where the offset of `timeZone` changes. It assumes at most one change a day. */
224
+ function offsetChanges(timeZone, from, to) {
225
+ const offset = (time) => timeZoneOffsetMinutes(new Date(time), timeZone);
226
+ const changes = [];
227
+ let previous = from;
228
+ let previousOffset = offset(from);
229
+ while (previous < to) {
230
+ const time = Math.min(previous + dayMs$1, to);
231
+ const current = offset(time);
232
+ if (current !== previousOffset) {
233
+ let low = previous;
234
+ let high = time;
235
+ while (high - low > minuteMs) {
236
+ const middle = low + Math.floor((high - low) / minuteMs / 2) * minuteMs;
237
+ if (offset(middle) === previousOffset) low = middle;
238
+ else high = middle;
239
+ }
240
+ changes.push(high);
241
+ }
242
+ previous = time;
243
+ previousOffset = current;
244
+ }
245
+ return changes;
246
+ }
247
+ /** The clock changes of `timeZone` in the two years from `from`, as windows of local days. */
248
+ function clockChanges(timeZone, from) {
249
+ const start = Math.floor(from.getTime() / minuteMs) * minuteMs;
250
+ const changes = [];
251
+ for (const instant of offsetChanges(timeZone, start, start + sampledDays * dayMs$1)) {
252
+ const before = timeZoneOffsetMinutes(/* @__PURE__ */ new Date(instant - minuteMs), timeZone);
253
+ const after = timeZoneOffsetMinutes(new Date(instant), timeZone);
254
+ const low = instant + Math.min(before, after) * minuteMs;
255
+ const high = instant + Math.max(before, after) * minuteMs;
256
+ for (let day = Math.floor(low / dayMs$1) * dayMs$1; day < high; day += dayMs$1) {
257
+ const date = new Date(day);
258
+ changes.push({
259
+ year: date.getUTCFullYear(),
260
+ month: date.getUTCMonth() + 1,
261
+ day: date.getUTCDate(),
262
+ weekday: date.getUTCDay(),
263
+ start: (Math.max(low, day) - day) / minuteMs,
264
+ end: (Math.min(high, day + dayMs$1) - day) / minuteMs,
265
+ delta: after - before
266
+ });
267
+ }
268
+ }
269
+ return changes;
270
+ }
271
+ /** Every value of `offset(timeZone) - offset(machineTimeZone)`, in minutes, in the two years from `from`. */
272
+ function offsetDifferences(timeZone, machineTimeZone, from) {
273
+ const start = Math.floor(from.getTime() / minuteMs) * minuteMs;
274
+ const end = start + sampledDays * dayMs$1;
275
+ const instants = [
276
+ start,
277
+ ...offsetChanges(timeZone, start, end),
278
+ ...offsetChanges(machineTimeZone, start, end)
279
+ ];
280
+ return [...new Set(instants.map((time) => timeZoneOffsetMinutes(new Date(time), timeZone) - timeZoneOffsetMinutes(new Date(time), machineTimeZone)))].sort((left, right) => left - right);
281
+ }
282
+ /** Hours and minutes whose product is exactly `times` (minutes of the day), else `undefined`. */
283
+ function asProduct(times) {
284
+ const unique = new Set(times);
285
+ const hours = [...new Set([...unique].map((time) => Math.floor(time / 60)))].sort((left, right) => left - right);
286
+ const minutes = [...new Set([...unique].map((time) => time % 60))].sort((left, right) => left - right);
287
+ return hours.length * minutes.length === unique.size ? {
288
+ hours,
289
+ minutes
290
+ } : void 0;
291
+ }
292
+ /** The cron moved by a constant `difference`: the machine time is the Schedule time minus `difference` minutes. */
293
+ function shiftFields(fields, difference) {
294
+ const shifted = timesOfDay(fields).map((time) => time - difference);
295
+ const product = asProduct(shifted.map((time) => modulo(time, dayMinutes)));
296
+ if (!product) return void 0;
297
+ const dayShift = Math.floor(shifted[0] / dayMinutes);
298
+ if (shifted.every((time) => Math.floor(time / dayMinutes) === dayShift)) {
299
+ if (dayShift === 0) return {
300
+ ...fields,
301
+ ...product
302
+ };
303
+ if (isDayRestricted(fields) || isMonthRestricted(fields)) return void 0;
304
+ const weekdays = [...new Set(fields.weekdays.map((weekday) => modulo(weekday + dayShift, 7)))].sort((left, right) => left - right);
305
+ return {
306
+ ...fields,
307
+ ...product,
308
+ weekdays
309
+ };
310
+ }
311
+ return runsEveryDay(fields) ? {
312
+ ...fields,
313
+ ...product
314
+ } : void 0;
315
+ }
316
+ /**
317
+ * The cron in the machine time zone, for launchd and Task Scheduler, which run timers in the machine's local time.
318
+ * Returns `undefined` when no cron in the machine zone gives the same runs as `fields` in `timeZone`.
319
+ */
320
+ function machineCronFields(fields, timeZone, machineTimeZone, from) {
321
+ if (timeZone === machineTimeZone) return fields;
322
+ const differences = offsetDifferences(timeZone, machineTimeZone, from);
323
+ if (differences.length === 1) return differences[0] === 0 ? fields : shiftFields(fields, differences[0]);
324
+ if (!runsEveryDay(fields)) return void 0;
325
+ const key = (difference) => [...new Set(timesOfDay(fields).map((time) => modulo(time - difference, dayMinutes)))].sort((left, right) => left - right).join(",");
326
+ const first = key(differences[0]);
327
+ if (differences.some((difference) => key(difference) !== first)) return void 0;
328
+ return shiftFields(fields, differences[0]);
329
+ }
330
+ /** The cron in the machine time zone of `host`, or the error that says why the OS cannot run it there. */
331
+ function machineFieldsOrError(platform, spec, host) {
332
+ if (spec.timeZone === "local") return [void 0, spec.fields];
333
+ const fields = machineCronFields(spec.fields, spec.timeZone, host.machineTimeZone, host.now());
334
+ return fields ? [void 0, fields] : [osScheduleErrors.SCHEDULE_OS_TIME_ZONE_UNSUPPORTED({
335
+ platform,
336
+ timeZone: spec.timeZone,
337
+ machineTimeZone: host.machineTimeZone
338
+ }), void 0];
339
+ }
340
+ //#endregion
341
+ //#region src/os/launchd.ts
342
+ const intervalKeys = /* @__PURE__ */ new Set([
343
+ "Minute",
344
+ "Hour",
345
+ "Day",
346
+ "Weekday",
347
+ "Month"
348
+ ]);
349
+ const maxIntervals = 1e3;
350
+ const { join: join$3 } = pathsFor("darwin");
351
+ /**
352
+ * `StartCalendarInterval` dicts for the cron: one per combination of the restricted fields. launchd ANDs the keys of a
353
+ * dict, so a cron that restricts both day fields gets the day dicts and the weekday dicts.
354
+ */
355
+ function launchdIntervals(fields) {
356
+ const values = (restricted, list) => restricted ? list : [void 0];
357
+ const minutes = values(fields.minutes.length !== 60, fields.minutes);
358
+ const hours = values(fields.hours.length !== 24, fields.hours);
359
+ const months = values(isMonthRestricted(fields), fields.months);
360
+ const days = [...isDayRestricted(fields) ? fields.days.map((Day) => ({ Day })) : [], ...isWeekdayRestricted(fields) ? fields.weekdays.map((Weekday) => ({ Weekday })) : []];
361
+ if (!days.length) days.push({});
362
+ const count = minutes.length * hours.length * months.length * days.length;
363
+ if (count > maxIntervals) return `it needs ${count} StartCalendarInterval entries, and the limit is ${maxIntervals}.`;
364
+ return months.flatMap((Month) => days.flatMap((day) => hours.flatMap((Hour) => minutes.map((Minute) => {
365
+ const interval = {};
366
+ if (Minute !== void 0) interval.Minute = Minute;
367
+ if (Hour !== void 0) interval.Hour = Hour;
368
+ Object.assign(interval, day);
369
+ if (Month !== void 0) interval.Month = Month;
370
+ return interval;
371
+ }))));
372
+ }
373
+ function xml$1(value) {
374
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
375
+ }
376
+ function unxml(value) {
377
+ return value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&apos;", "'").replaceAll("&amp;", "&");
378
+ }
379
+ function launchdLogFile(spec, scope, homedir) {
380
+ return join$3(spec.logDir ?? defaultLogDir(spec.name, scope, homedir), `${spec.name}.log`);
381
+ }
382
+ function defaultLogDir(name, scope, homedir) {
383
+ return scope === "user" ? join$3(homedir, "Library/Logs", name) : join$3("/Library/Logs", name);
384
+ }
385
+ function renderLaunchdPlist(spec, intervals, logFile) {
386
+ const string = (value) => `<string>${xml$1(value)}</string>`;
387
+ const env = Object.entries(spec.env);
388
+ return [
389
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
390
+ "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">",
391
+ `<!-- ${generatedHeader} -->`,
392
+ "<plist version=\"1.0\">",
393
+ "<dict>",
394
+ " <key>Label</key>",
395
+ `\t${string(spec.name)}`,
396
+ " <key>ProgramArguments</key>",
397
+ " <array>",
398
+ ...spec.command.map((argument) => `\t\t${string(argument)}`),
399
+ " </array>",
400
+ ...env.length ? [
401
+ " <key>EnvironmentVariables</key>",
402
+ " <dict>",
403
+ ...env.flatMap(([name, value]) => [`\t\t<key>${xml$1(name)}</key>`, `\t\t${string(value)}`]),
404
+ " </dict>"
405
+ ] : [],
406
+ ...spec.cwd === void 0 ? [] : [" <key>WorkingDirectory</key>", `\t${string(spec.cwd)}`],
407
+ " <key>StartCalendarInterval</key>",
408
+ " <array>",
409
+ ...intervals.flatMap((interval) => {
410
+ const entries = Object.entries(interval);
411
+ return entries.length ? [
412
+ " <dict>",
413
+ ...entries.flatMap(([key, value]) => [`\t\t\t<key>${key}</key>`, `\t\t\t<integer>${value}</integer>`]),
414
+ " </dict>"
415
+ ] : [" <dict/>"];
416
+ }),
417
+ " </array>",
418
+ " <key>StandardOutPath</key>",
419
+ `\t${string(logFile)}`,
420
+ " <key>StandardErrorPath</key>",
421
+ `\t${string(logFile)}`,
422
+ " <key>RunAtLoad</key>",
423
+ " <false/>",
424
+ " <key>ProcessType</key>",
425
+ " <string>Background</string>",
426
+ "</dict>",
427
+ "</plist>",
428
+ ""
429
+ ].join("\n");
430
+ }
431
+ /** Reads back the `StartCalendarInterval` dicts and the log path of a plist that `renderLaunchdPlist()` wrote. */
432
+ function parseLaunchdPlist(plist) {
433
+ const intervals = [...(plist.match(/<key>StartCalendarInterval<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] ?? "").matchAll(/<dict\/>|<dict>([\s\S]*?)<\/dict>/g)].map((match) => {
434
+ const interval = {};
435
+ for (const [, key, value] of (match[1] ?? "").matchAll(/<key>(\w+)<\/key>\s*<integer>(\d+)<\/integer>/g)) if (intervalKeys.has(key)) interval[key] = Number(value);
436
+ return interval;
437
+ });
438
+ const logFile = plist.match(/<key>StandardOutPath<\/key>\s*<string>([^<]*)<\/string>/)?.[1];
439
+ return {
440
+ intervals,
441
+ ...logFile === void 0 ? {} : { logFile: unxml(logFile) }
442
+ };
443
+ }
444
+ /** Reads `launchctl print` output: the `state` and `last exit code` lines of the service, one tab deep. */
445
+ function parseLaunchctlPrint(output) {
446
+ const state = output.match(/^\tstate = (.+)$/m)?.[1]?.trim();
447
+ const lastExit = output.match(/^\tlast exit code = (-?\d+)/m)?.[1];
448
+ return {
449
+ running: state === "running",
450
+ ...lastExit === void 0 ? {} : { lastExitCode: Number(lastExit) }
451
+ };
452
+ }
453
+ const dayMs = 864e5;
454
+ /** UTC instant of a wall-clock time in `timeZone`. A time in a daylight saving gap moves forward by the gap. */
455
+ function zonedInstant(year, month, day, minuteOfDay, timeZone) {
456
+ const local = Date.UTC(year, month - 1, day, 0, minuteOfDay);
457
+ const guess = local - timeZoneOffsetMinutes(new Date(local), timeZone) * 6e4;
458
+ return /* @__PURE__ */ new Date(local - timeZoneOffsetMinutes(new Date(guess), timeZone) * 6e4);
459
+ }
460
+ function matchesInterval(interval, month, day, weekday) {
461
+ return (interval.Month === void 0 || interval.Month === month) && (interval.Day === void 0 || interval.Day === day) && (interval.Weekday === void 0 || interval.Weekday % 7 === weekday);
462
+ }
463
+ /** The next time after `now` that one of `intervals` matches in `timeZone`, the machine zone that launchd uses. */
464
+ function nextLaunchdRun(intervals, timeZone, now) {
465
+ const today = new Date(now.getTime() + timeZoneOffsetMinutes(now, timeZone) * 6e4);
466
+ for (let offset = 0; offset <= 1464; offset++) {
467
+ const date = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()) + offset * dayMs);
468
+ const [year, month, day, weekday] = [
469
+ date.getUTCFullYear(),
470
+ date.getUTCMonth() + 1,
471
+ date.getUTCDate(),
472
+ date.getUTCDay()
473
+ ];
474
+ const times = /* @__PURE__ */ new Set();
475
+ for (const interval of intervals) {
476
+ if (!matchesInterval(interval, month, day, weekday)) continue;
477
+ for (const hour of interval.Hour === void 0 ? range(0, 23) : [interval.Hour]) for (const minute of interval.Minute === void 0 ? range(0, 59) : [interval.Minute]) times.add(hour * 60 + minute);
478
+ }
479
+ for (const time of [...times].sort((left, right) => left - right)) {
480
+ const instant = zonedInstant(year, month, day, time, timeZone);
481
+ if (instant > now) return instant;
482
+ }
483
+ }
484
+ }
485
+ const notFound = /could not find|no such process|not found/i;
486
+ const marker$1 = `<!-- ${generatedHeader} -->`;
487
+ /** launchd jobs: a LaunchAgent in the user's `gui` domain, or a LaunchDaemon in the `system` domain. */
488
+ function createLaunchdDriver(host, scope) {
489
+ const plistPath = (name) => scope === "user" ? join$3(host.homedir, "Library/LaunchAgents", `${name}.plist`) : join$3("/Library/LaunchDaemons", `${name}.plist`);
490
+ const domains = scope === "user" ? [`gui/${host.uid}`, `user/${host.uid}`] : ["system"];
491
+ function failed(args, result) {
492
+ return [osScheduleErrors.SCHEDULE_OS_COMMAND_FAILED({
493
+ command: ["launchctl", ...args].join(" "),
494
+ exitCode: result.code,
495
+ output: commandOutput(result)
496
+ }), void 0];
497
+ }
498
+ /** The domain that has the job loaded, and its `launchctl print` output. */
499
+ async function loaded(name) {
500
+ for (const domain of domains) {
501
+ const result = await host.exec("launchctl", ["print", `${domain}/${name}`]);
502
+ if (result.code === 0) return {
503
+ domain,
504
+ output: result.stdout
505
+ };
506
+ }
507
+ }
508
+ /**
509
+ * The plist and the loaded job of `name`, and the resource that holds the name when ViteHub did not install it: a
510
+ * plist at our path without our header, or a job with this label that launchd loaded from another plist.
511
+ */
512
+ async function owner(name) {
513
+ const path = plistPath(name);
514
+ const plist = await host.fs.readFile(path);
515
+ const job = await loaded(name);
516
+ const loadedFrom = job?.output.match(/^\tpath = (.+)$/m)?.[1]?.trim();
517
+ let foreign;
518
+ if (plist !== void 0 && !plist.includes(marker$1)) foreign = path;
519
+ else if (job && (loadedFrom === void 0 || loadedFrom !== path && await host.fs.realpath(loadedFrom) !== await host.fs.realpath(path))) foreign = loadedFrom ?? `${job.domain}/${name}`;
520
+ return {
521
+ ...plist === void 0 ? {} : { plist },
522
+ ...job ? { job } : {},
523
+ ...foreign ? { foreign } : {}
524
+ };
525
+ }
526
+ async function bootout(name, job) {
527
+ if (!job) return [void 0, false];
528
+ const args = ["bootout", `${job.domain}/${name}`];
529
+ const result = await host.exec("launchctl", args);
530
+ return result.code === 0 || notFound.test(commandOutput(result)) ? [void 0, true] : failed(args, result);
531
+ }
532
+ async function bootstrapIn(domain, plist) {
533
+ for (let attempt = 1;; attempt++) {
534
+ const result = await host.exec("launchctl", [
535
+ "bootstrap",
536
+ domain,
537
+ plist
538
+ ]);
539
+ if (result.code === 0 || attempt === 10 || !/\b5: Input\/output error/.test(commandOutput(result))) return result;
540
+ await host.sleep(200);
541
+ }
542
+ }
543
+ async function bootstrap(plist) {
544
+ for (let index = 0;; index++) {
545
+ const domain = domains[index];
546
+ const result = await bootstrapIn(domain, plist);
547
+ if (result.code === 0) return [void 0, domain];
548
+ if (!(result.code === 125 || /domain does not support/i.test(commandOutput(result))) || index === domains.length - 1) return failed([
549
+ "bootstrap",
550
+ domain,
551
+ plist
552
+ ], result);
553
+ }
554
+ }
555
+ return {
556
+ async install(spec) {
557
+ if (!spec.catchUp) return [osScheduleErrors.SCHEDULE_OS_OPTION_UNSUPPORTED({
558
+ platform: "darwin",
559
+ option: "catchUp",
560
+ reason: "launchd always runs a time that the Mac missed while it slept, once it wakes. Remove `catchUp: false`."
561
+ }), void 0];
562
+ if (spec.randomDelaySeconds) return [osScheduleErrors.SCHEDULE_OS_OPTION_UNSUPPORTED({
563
+ platform: "darwin",
564
+ option: "randomDelaySeconds",
565
+ reason: "launchd has no random delay. Remove the option, or set it to 0."
566
+ }), void 0];
567
+ const [zoneError, fields] = machineFieldsOrError("darwin", spec, host);
568
+ if (zoneError) return [zoneError, void 0];
569
+ const intervals = launchdIntervals(fields);
570
+ if (typeof intervals === "string") return [osScheduleErrors.SCHEDULE_OS_CRON_UNSUPPORTED({
571
+ platform: "darwin",
572
+ cron: spec.cron,
573
+ reason: intervals
574
+ }), void 0];
575
+ const file = plistPath(spec.name);
576
+ const logFile = launchdLogFile(spec, scope, host.homedir);
577
+ const plist = renderLaunchdPlist(spec, intervals, logFile);
578
+ const files = [file, logFile];
579
+ const current = await owner(spec.name);
580
+ if (current.foreign) return [osScheduleErrors.SCHEDULE_OS_NAME_TAKEN({
581
+ platform: "darwin",
582
+ name: spec.name,
583
+ scope,
584
+ resource: current.foreign
585
+ }), void 0];
586
+ if (current.plist === plist && current.job) return [void 0, {
587
+ files,
588
+ changed: false
589
+ }];
590
+ const [bootoutError] = await bootout(spec.name, current.job);
591
+ if (bootoutError) return [bootoutError, void 0];
592
+ await host.fs.mkdir(spec.logDir ?? defaultLogDir(spec.name, scope, host.homedir));
593
+ await host.fs.writeFile(file, plist);
594
+ const [bootstrapError, domain] = await bootstrap(file);
595
+ if (bootstrapError) return [bootstrapError, void 0];
596
+ const enableArgs = ["enable", `${domain}/${spec.name}`];
597
+ const enabled = await host.exec("launchctl", enableArgs);
598
+ if (enabled.code !== 0) return failed(enableArgs, enabled);
599
+ return [void 0, {
600
+ files,
601
+ changed: true
602
+ }];
603
+ },
604
+ async status(name) {
605
+ const { plist, job, foreign } = await owner(name);
606
+ if (foreign) return [void 0, {
607
+ name,
608
+ platform: "darwin",
609
+ scope,
610
+ installed: false,
611
+ running: false
612
+ }];
613
+ const parsed = plist === void 0 ? void 0 : parseLaunchdPlist(plist);
614
+ const state = job ? parseLaunchctlPrint(job.output) : { running: false };
615
+ const nextRunAt = job && parsed?.intervals.length ? nextLaunchdRun(parsed.intervals, host.machineTimeZone, host.now()) : void 0;
616
+ return [void 0, {
617
+ name,
618
+ platform: "darwin",
619
+ scope,
620
+ installed: job !== void 0,
621
+ ...state,
622
+ ...nextRunAt ? { nextRunAt } : {},
623
+ ...parsed?.logFile ? { logFile: parsed.logFile } : {}
624
+ }];
625
+ },
626
+ async uninstall(name) {
627
+ const file = plistPath(name);
628
+ const { plist, job, foreign } = await owner(name);
629
+ if (foreign) return [void 0, {
630
+ name,
631
+ platform: "darwin",
632
+ scope,
633
+ removed: [],
634
+ existed: false
635
+ }];
636
+ const [bootoutError, wasLoaded] = await bootout(name, job);
637
+ if (bootoutError) return [bootoutError, void 0];
638
+ const logFile = plist === void 0 ? void 0 : parseLaunchdPlist(plist).logFile;
639
+ const removed = [];
640
+ for (const path of [file, ...logFile ? [logFile] : []]) if (await host.fs.rm(path)) removed.push(path);
641
+ await host.fs.rmdirIfEmpty(defaultLogDir(name, scope, host.homedir));
642
+ return [void 0, {
643
+ name,
644
+ platform: "darwin",
645
+ scope,
646
+ removed,
647
+ existed: wasLoaded || plist !== void 0
648
+ }];
649
+ }
650
+ };
651
+ }
652
+ //#endregion
653
+ //#region ../internal/src/systemd.ts
654
+ /** systemd expands `%` specifiers in every value, and a line break ends the setting. */
655
+ function systemdValue(value, lineBreak) {
656
+ if (/[\n\r]/.test(value)) lineBreak();
657
+ return value.replaceAll("%", "%%");
658
+ }
659
+ /** Quotes an `ExecStart=` argument, where systemd also expands `$` variables. */
660
+ function systemdExecArgument(value, lineBreak) {
661
+ const escaped = systemdValue(value, lineBreak).replaceAll("$", "$$$$");
662
+ return /^[\w./@+:,=-]+$/.test(escaped) ? escaped : `"${escaped.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
663
+ }
664
+ /** Quotes the `NAME=value` of an `Environment=` line. */
665
+ function systemdAssignment(name, value, lineBreak) {
666
+ return `"${systemdValue(`${name}=${value}`, lineBreak).replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
667
+ }
668
+ //#endregion
669
+ //#region src/os/systemd.ts
670
+ const weekdayNames$1 = [
671
+ "Sun",
672
+ "Mon",
673
+ "Tue",
674
+ "Wed",
675
+ "Thu",
676
+ "Fri",
677
+ "Sat"
678
+ ];
679
+ const { join: join$2 } = pathsFor("linux");
680
+ function lineBreak() {
681
+ throw invariantError("a systemd value has a line break after validation");
682
+ }
683
+ function pad$1(value) {
684
+ return String(value).padStart(2, "0");
685
+ }
686
+ /** `1..5`, `0,15,30,45`, or `*` when the list holds every value. Runs of three or more become ranges. */
687
+ function calendarList(values, size, format = pad$1) {
688
+ if (values.length === size) return "*";
689
+ const parts = [];
690
+ for (let start = 0; start < values.length;) {
691
+ let end = start;
692
+ while (end + 1 < values.length && values[end + 1] === values[end] + 1) end++;
693
+ if (end - start >= 2) parts.push(`${format(values[start])}..${format(values[end])}`);
694
+ else for (let index = start; index <= end; index++) parts.push(format(values[index]));
695
+ start = end + 1;
696
+ }
697
+ return parts.join(",");
698
+ }
699
+ /**
700
+ * `OnCalendar=` values of the cron in `timeZone`. systemd ANDs a weekday with the date, and cron ORs a restricted day
701
+ * of the month with a restricted weekday, so that case takes two lines.
702
+ */
703
+ function systemdCalendars(fields, timeZone) {
704
+ const time = `${calendarList(fields.hours, 24)}:${calendarList(fields.minutes, 60)}:00${timeZone === "local" ? "" : ` ${timeZone}`}`;
705
+ const months = calendarList(fields.months, 12);
706
+ const byWeekday = `${calendarList(fields.weekdays.map((weekday) => weekday || 7).sort((left, right) => left - right), 7, (weekday) => weekdayNames$1[weekday % 7])} *-${months}-* ${time}`;
707
+ const byDay = `*-${months}-${calendarList(fields.days, 31)} ${time}`;
708
+ if (isWeekdayRestricted(fields)) return isDayRestricted(fields) ? [byWeekday, byDay] : [byWeekday];
709
+ return [byDay];
710
+ }
711
+ function systemdLogFile(spec) {
712
+ return spec.logDir === void 0 ? void 0 : join$2(spec.logDir, `${spec.name}.log`);
713
+ }
714
+ function renderSystemdService(spec) {
715
+ const logFile = systemdLogFile(spec);
716
+ return [
717
+ `# ${generatedHeader}`,
718
+ "[Unit]",
719
+ `Description=${systemdValue(spec.description, lineBreak)}`,
720
+ "",
721
+ "[Service]",
722
+ "Type=oneshot",
723
+ `ExecStart=${spec.command.map((argument) => systemdExecArgument(argument, lineBreak)).join(" ")}`,
724
+ ...spec.cwd === void 0 ? [] : [`WorkingDirectory=${systemdValue(spec.cwd, lineBreak)}`],
725
+ ...Object.entries(spec.env).map(([name, value]) => `Environment=${systemdAssignment(name, value, lineBreak)}`),
726
+ ...logFile === void 0 ? [] : [`StandardOutput=append:${systemdValue(logFile, lineBreak)}`, `StandardError=append:${systemdValue(logFile, lineBreak)}`],
727
+ `SyslogIdentifier=${spec.name}`,
728
+ ""
729
+ ].join("\n");
730
+ }
731
+ function renderSystemdTimer(spec) {
732
+ return [
733
+ `# ${generatedHeader}`,
734
+ "[Unit]",
735
+ `Description=${systemdValue(spec.description, lineBreak)}`,
736
+ "",
737
+ "[Timer]",
738
+ ...systemdCalendars(spec.fields, spec.timeZone).map((calendar) => `OnCalendar=${calendar}`),
739
+ `Persistent=${spec.catchUp}`,
740
+ "AccuracySec=1s",
741
+ ...spec.randomDelaySeconds ? [`RandomizedDelaySec=${spec.randomDelaySeconds}`] : [],
742
+ `Unit=${spec.name}.service`,
743
+ "",
744
+ "[Install]",
745
+ "WantedBy=timers.target",
746
+ ""
747
+ ].join("\n");
748
+ }
749
+ /** Reads `systemctl show` output: blocks of `Key=value` lines, one block per unit, keyed by `Id`. */
750
+ function parseSystemctlShow(output) {
751
+ const units = /* @__PURE__ */ new Map();
752
+ for (const block of output.split(/\n\s*\n/)) {
753
+ const properties = /* @__PURE__ */ new Map();
754
+ for (const line of block.split("\n")) {
755
+ const index = line.indexOf("=");
756
+ if (index > 0) properties.set(line.slice(0, index), line.slice(index + 1));
757
+ }
758
+ const id = properties.get("Id");
759
+ if (id) units.set(id, properties);
760
+ }
761
+ return units;
762
+ }
763
+ /** `@1794841368` (`--timestamp=unix`) as a Date. Empty or `0` means never. */
764
+ function unixTimestamp(value) {
765
+ const seconds = Number(value?.replace(/^@/, ""));
766
+ return value && Number.isFinite(seconds) && seconds > 0 ? /* @__PURE__ */ new Date(seconds * 1e3) : void 0;
767
+ }
768
+ const statusProperties = [
769
+ "Id",
770
+ "LoadState",
771
+ "FragmentPath",
772
+ "ActiveState",
773
+ "SubState",
774
+ "NextElapseUSecRealtime",
775
+ "LastTriggerUSec",
776
+ "ExecMainStartTimestamp",
777
+ "ExecMainExitTimestamp",
778
+ "ExecMainCode",
779
+ "ExecMainStatus",
780
+ "Result"
781
+ ];
782
+ const exitedCode = "1";
783
+ const marker = `# ${generatedHeader}`;
784
+ /**
785
+ * The unit or file that holds `name` when ViteHub did not install it: a file at our path without our header, or a
786
+ * loaded unit that systemd reads from another file, such as /usr/lib/systemd/user/<name>.service or a transient unit.
787
+ */
788
+ async function foreignResource(host, paths, texts, units, name) {
789
+ for (const kind of ["service", "timer"]) {
790
+ const text = texts[kind];
791
+ if (text !== void 0 && !text.startsWith(marker)) return paths[kind];
792
+ const unit = units.get(`${name}.${kind}`);
793
+ const state = unit?.get("LoadState");
794
+ if (!state || state === "not-found") continue;
795
+ const fragment = unit?.get("FragmentPath");
796
+ if (!fragment) return `${name}.${kind}`;
797
+ if (fragment !== paths[kind] && await host.fs.realpath(fragment) !== await host.fs.realpath(paths[kind])) return fragment;
798
+ }
799
+ }
800
+ /**
801
+ * The folder of user units that the systemd user manager reads: `<config home>/systemd/user`, next to the
802
+ * `user.control` folder that comes first in its unit path. The manager has its own environment, so the
803
+ * XDG_CONFIG_HOME or HOME of this process can point elsewhere.
804
+ */
805
+ function userUnitDirectory(unitPath) {
806
+ const paths = unitPath.trim().split(/\s+/);
807
+ const directory = paths.find((path) => path.endsWith("/systemd/user.control"))?.slice(0, -8);
808
+ return directory?.startsWith("/") && paths.includes(directory) ? directory : void 0;
809
+ }
810
+ /** systemd timers, as `systemctl --user` units or system units in /etc/systemd/system. */
811
+ function createSystemdDriver(host, scope) {
812
+ const user = scope === "user";
813
+ const execEnv = user && !host.env.XDG_RUNTIME_DIR && host.uid !== void 0 ? { XDG_RUNTIME_DIR: `/run/user/${host.uid}` } : void 0;
814
+ let directory;
815
+ async function unitDirectory() {
816
+ if (!user) return "/etc/systemd/system";
817
+ const result = await systemctl("show", "-p", "UnitPath", "--value");
818
+ return (result.code === 0 ? userUnitDirectory(result.stdout) : void 0) ?? join$2(host.env.XDG_CONFIG_HOME || join$2(host.homedir, ".config"), "systemd/user");
819
+ }
820
+ async function paths(name) {
821
+ directory ??= unitDirectory();
822
+ const folder = await directory;
823
+ return {
824
+ service: join$2(folder, `${name}.service`),
825
+ timer: join$2(folder, `${name}.timer`)
826
+ };
827
+ }
828
+ function systemctl(...args) {
829
+ return host.exec("systemctl", user ? ["--user", ...args] : args, execEnv);
830
+ }
831
+ function failed(args, result) {
832
+ const command = [
833
+ "systemctl",
834
+ ...user ? ["--user"] : [],
835
+ ...args
836
+ ].join(" ");
837
+ return [osScheduleErrors.SCHEDULE_OS_COMMAND_FAILED({
838
+ command,
839
+ exitCode: result.code,
840
+ output: commandOutput(result)
841
+ }), void 0];
842
+ }
843
+ async function run(...args) {
844
+ const result = await systemctl(...args);
845
+ return result.code === 0 ? [void 0, result] : failed(args, result);
846
+ }
847
+ async function linger() {
848
+ if (!user) return void 0;
849
+ const result = await host.exec("loginctl", [
850
+ "show-user",
851
+ host.user,
852
+ "-p",
853
+ "Linger",
854
+ "--value"
855
+ ]);
856
+ return result.code === 0 && result.stdout.trim() === "yes";
857
+ }
858
+ function logFileOf(service) {
859
+ return (service?.match(/^StandardOutput=append:(.*)$/m)?.[1])?.replaceAll("%%", "%");
860
+ }
861
+ async function readUnits(files) {
862
+ const [service, timer] = [await host.fs.readFile(files.service), await host.fs.readFile(files.timer)];
863
+ return {
864
+ ...service === void 0 ? {} : { service },
865
+ ...timer === void 0 ? {} : { timer }
866
+ };
867
+ }
868
+ /** The resource that holds `name` when ViteHub did not install it in this scope. */
869
+ async function foreign(name, files, texts) {
870
+ const fileOwner = await foreignResource(host, files, texts, /* @__PURE__ */ new Map(), name);
871
+ if (fileOwner) return [void 0, fileOwner];
872
+ const [error, result] = await run("show", `${name}.service`, `${name}.timer`, "-p", "Id,LoadState,FragmentPath");
873
+ if (error) return [error, void 0];
874
+ return [void 0, await foreignResource(host, files, texts, parseSystemctlShow(result.stdout), name)];
875
+ }
876
+ return {
877
+ async install(spec) {
878
+ const files = await paths(spec.name);
879
+ const service = renderSystemdService(spec);
880
+ const timer = renderSystemdTimer(spec);
881
+ const current = await readUnits(files);
882
+ const [foreignError, resource] = await foreign(spec.name, files, current);
883
+ if (foreignError) return [foreignError, void 0];
884
+ if (resource) return [osScheduleErrors.SCHEDULE_OS_NAME_TAKEN({
885
+ platform: "linux",
886
+ name: spec.name,
887
+ scope,
888
+ resource
889
+ }), void 0];
890
+ const changed = current.service !== service || current.timer !== timer;
891
+ const logFile = systemdLogFile(spec);
892
+ if (spec.logDir !== void 0) await host.fs.mkdir(spec.logDir);
893
+ const unit = `${spec.name}.timer`;
894
+ if (changed) {
895
+ await host.fs.writeFile(files.service, service);
896
+ await host.fs.writeFile(files.timer, timer);
897
+ const [reloadError] = await run("daemon-reload");
898
+ if (reloadError) return [reloadError, void 0];
899
+ const [enableError] = await run("enable", unit);
900
+ if (enableError) return [enableError, void 0];
901
+ const [restartError] = await run("restart", unit);
902
+ if (restartError) return [restartError, void 0];
903
+ }
904
+ const enabled = (await systemctl("is-enabled", unit)).stdout.trim() === "enabled";
905
+ const active = (await systemctl("is-active", unit)).stdout.trim() === "active";
906
+ let started = false;
907
+ if (!enabled || !active) {
908
+ const [startError] = await run("enable", "--now", unit);
909
+ if (startError) return [startError, void 0];
910
+ started = true;
911
+ }
912
+ return [void 0, {
913
+ files: [
914
+ files.service,
915
+ files.timer,
916
+ ...logFile === void 0 ? [] : [logFile]
917
+ ],
918
+ changed: changed || started,
919
+ ...user ? { linger: await linger() } : {}
920
+ }];
921
+ },
922
+ async status(name) {
923
+ const [error, result] = await run(...[
924
+ "show",
925
+ `${name}.timer`,
926
+ `${name}.service`,
927
+ "--timestamp=unix",
928
+ "-p",
929
+ statusProperties.join(",")
930
+ ]);
931
+ if (error) return [error, void 0];
932
+ const units = parseSystemctlShow(result.stdout);
933
+ const files = await paths(name);
934
+ const texts = await readUnits(files);
935
+ const lingering = await linger();
936
+ if (await foreignResource(host, files, texts, units, name)) return [void 0, {
937
+ name,
938
+ platform: "linux",
939
+ scope,
940
+ installed: false,
941
+ running: false,
942
+ ...lingering === void 0 ? {} : { linger: lingering }
943
+ }];
944
+ const timer = units.get(`${name}.timer`);
945
+ const service = units.get(`${name}.service`);
946
+ const installed = timer?.get("LoadState") === "loaded";
947
+ const running = [
948
+ "activating",
949
+ "active",
950
+ "deactivating",
951
+ "reloading"
952
+ ].includes(service?.get("ActiveState") ?? "");
953
+ const exited = unixTimestamp(service?.get("ExecMainExitTimestamp")) !== void 0;
954
+ const exitStatus = Number(service?.get("ExecMainStatus"));
955
+ const lastRunAt = unixTimestamp(service?.get("ExecMainStartTimestamp"));
956
+ const nextRunAt = unixTimestamp(timer?.get("NextElapseUSecRealtime"));
957
+ const logFile = logFileOf(texts.service);
958
+ return [void 0, {
959
+ name,
960
+ platform: "linux",
961
+ scope,
962
+ installed,
963
+ running,
964
+ ...lastRunAt ? { lastRunAt } : {},
965
+ ...exited && !running && Number.isInteger(exitStatus) ? { lastExitCode: service?.get("ExecMainCode") === exitedCode ? exitStatus : 128 + exitStatus } : {},
966
+ ...nextRunAt ? { nextRunAt } : {},
967
+ ...lingering === void 0 ? {} : { linger: lingering },
968
+ ...logFile ? { logFile } : {}
969
+ }];
970
+ },
971
+ async uninstall(name) {
972
+ const files = await paths(name);
973
+ const texts = await readUnits(files);
974
+ const logFile = logFileOf(texts.service);
975
+ const nothing = {
976
+ name,
977
+ platform: "linux",
978
+ scope,
979
+ removed: [],
980
+ existed: false
981
+ };
982
+ if (texts.service === void 0 && texts.timer === void 0) return [void 0, nothing];
983
+ const [foreignError, resource] = await foreign(name, files, texts);
984
+ if (foreignError) return [foreignError, void 0];
985
+ if (resource) return [void 0, nothing];
986
+ const notLoaded = /not loaded|does not exist|not found/i;
987
+ for (const args of [[
988
+ "disable",
989
+ "--now",
990
+ `${name}.timer`
991
+ ], ["stop", `${name}.service`]]) {
992
+ const result = await systemctl(...args);
993
+ if (result.code !== 0 && !notLoaded.test(commandOutput(result))) return failed(args, result);
994
+ }
995
+ await systemctl("clean", "--what=state", `${name}.timer`);
996
+ const removed = [];
997
+ for (const file of [
998
+ files.timer,
999
+ files.service,
1000
+ ...logFile ? [logFile] : []
1001
+ ]) if (await host.fs.rm(file)) removed.push(file);
1002
+ const [reloadError] = await run("daemon-reload");
1003
+ if (reloadError) return [reloadError, void 0];
1004
+ await systemctl("reset-failed", `${name}.service`, `${name}.timer`);
1005
+ return [void 0, {
1006
+ name,
1007
+ platform: "linux",
1008
+ scope,
1009
+ removed,
1010
+ existed: true
1011
+ }];
1012
+ }
1013
+ };
1014
+ }
1015
+ //#endregion
1016
+ //#region src/os/task-scheduler.ts
1017
+ const maxTriggers = 48;
1018
+ const weekdayNames = [
1019
+ "Sunday",
1020
+ "Monday",
1021
+ "Tuesday",
1022
+ "Wednesday",
1023
+ "Thursday",
1024
+ "Friday",
1025
+ "Saturday"
1026
+ ];
1027
+ const monthNames = [
1028
+ "January",
1029
+ "February",
1030
+ "March",
1031
+ "April",
1032
+ "May",
1033
+ "June",
1034
+ "July",
1035
+ "August",
1036
+ "September",
1037
+ "October",
1038
+ "November",
1039
+ "December"
1040
+ ];
1041
+ const taskNeverRan = 267011;
1042
+ const taskRunning = 267009;
1043
+ const { join: join$1 } = pathsFor("win32");
1044
+ /** An XML duration, such as `PT23H52M30S`. */
1045
+ function taskDuration(seconds) {
1046
+ const hours = Math.floor(seconds / 3600);
1047
+ const minutes = Math.floor(seconds % 3600 / 60);
1048
+ const rest = seconds % 60;
1049
+ return `PT${hours ? `${hours}H` : ""}${minutes ? `${minutes}M` : ""}${rest || !seconds ? `${rest}S` : ""}`;
1050
+ }
1051
+ /** One trigger for the runs. The duration ends half a step after the last run. */
1052
+ function trigger({ start, step, count }) {
1053
+ if (count < 2) return { start };
1054
+ return {
1055
+ start,
1056
+ repetition: {
1057
+ interval: taskDuration(step * 60),
1058
+ duration: taskDuration((count - 1) * step * 60 + step * 30)
1059
+ }
1060
+ };
1061
+ }
1062
+ /**
1063
+ * Task Scheduler repeats a trigger in elapsed time. When the clocks change between the first and the last run, the
1064
+ * later runs move by the change, and the duration ends at another time of day. Such runs need one trigger per time.
1065
+ */
1066
+ function crossesChange(runs, changes) {
1067
+ const last = runs.start + (runs.count - 1) * runs.step;
1068
+ return runs.count > 1 && changes.some((change) => runs.start < change.end && last >= change.start);
1069
+ }
1070
+ /** The fewest triggers that start at every time of the day of the cron, and keep their times across `changes`. */
1071
+ function timeTriggers(fields, changes) {
1072
+ const times = timesOfDay(fields);
1073
+ const single = (start) => ({
1074
+ start,
1075
+ step: 0,
1076
+ count: 1
1077
+ });
1078
+ const candidates = [times.map(single)];
1079
+ const step = arithmeticStep(times);
1080
+ if (step !== void 0) candidates.push([{
1081
+ start: times[0],
1082
+ step,
1083
+ count: times.length
1084
+ }]);
1085
+ const minuteStep = arithmeticStep(fields.minutes);
1086
+ if (minuteStep !== void 0) candidates.push(fields.hours.map((hour) => ({
1087
+ start: hour * 60 + fields.minutes[0],
1088
+ step: minuteStep,
1089
+ count: fields.minutes.length
1090
+ })));
1091
+ const hourStep = arithmeticStep(fields.hours);
1092
+ if (hourStep !== void 0) candidates.push(fields.minutes.map((minute) => ({
1093
+ start: fields.hours[0] * 60 + minute,
1094
+ step: hourStep * 60,
1095
+ count: fields.hours.length
1096
+ })));
1097
+ return candidates.map((candidate) => candidate.flatMap((runs) => crossesChange(runs, changes) ? range(0, runs.count - 1).map((index) => single(runs.start + index * runs.step)) : [runs])).reduce((best, candidate) => candidate.length < best.length ? candidate : best).map(trigger);
1098
+ }
1099
+ function onDay(schedule, change) {
1100
+ switch (schedule.kind) {
1101
+ case "always":
1102
+ case "day": return true;
1103
+ case "week": return schedule.weekdays.includes(change.weekday);
1104
+ case "month": return schedule.days.includes(change.day) && schedule.months.includes(change.month);
1105
+ }
1106
+ }
1107
+ function wallClock(minute) {
1108
+ return `${pad(Math.floor(minute / 60) % 24)}:${pad(minute % 60)}`;
1109
+ }
1110
+ /**
1111
+ * Triggers for the cron, or why Task Scheduler cannot run it exactly. `clock` has the clock changes of the machine
1112
+ * time zone, which Task Scheduler uses.
1113
+ */
1114
+ function taskTriggers(fields, clock = {
1115
+ timeZone: "UTC",
1116
+ changes: []
1117
+ }) {
1118
+ const dayRestricted = isDayRestricted(fields);
1119
+ const weekdayRestricted = isWeekdayRestricted(fields);
1120
+ const monthRestricted = isMonthRestricted(fields);
1121
+ if (weekdayRestricted && monthRestricted) return "a weekly trigger runs in every month, so it cannot keep a weekday list to some months.";
1122
+ const days = [];
1123
+ if (weekdayRestricted) days.push({
1124
+ kind: "week",
1125
+ weekdays: fields.weekdays
1126
+ });
1127
+ if (dayRestricted || monthRestricted) days.push({
1128
+ kind: "month",
1129
+ days: fields.days,
1130
+ months: fields.months
1131
+ });
1132
+ if (!days.length) days.push({ kind: "day" });
1133
+ const changes = clock.changes.filter((change) => days.some((schedule) => onDay(schedule, change)));
1134
+ const times = timesOfDay(fields);
1135
+ const step = arithmeticStep(times);
1136
+ if (changes.length && runsEveryDay(fields) && step && times.length * step === 1440 && changes.every((change) => change.delta % step === 0)) return {
1137
+ times: [{
1138
+ start: times[0],
1139
+ repetition: { interval: taskDuration(step * 60) }
1140
+ }],
1141
+ days: [{ kind: "always" }]
1142
+ };
1143
+ const triggers = timeTriggers(fields, changes);
1144
+ const count = triggers.length * days.length;
1145
+ if (count <= maxTriggers) return {
1146
+ times: triggers,
1147
+ days
1148
+ };
1149
+ const change = changes[0];
1150
+ if (change && timeTriggers(fields, []).length * days.length <= maxTriggers) {
1151
+ const [from, to] = change.delta > 0 ? [change.start, change.end] : [change.end, change.start];
1152
+ return `the clocks in ${clock.timeZone} change from ${wallClock(from)} to ${wallClock(to)} on ${change.year}-${pad(change.month)}-${pad(change.day)}, and Task Scheduler repeats a trigger in elapsed time, so the cron needs ${count} triggers to keep its times. The limit is ${maxTriggers}. Use fewer times of day, or times away from the clock change.`;
1153
+ }
1154
+ return `it needs ${count} triggers, and the limit is ${maxTriggers}. Use times of day with equal gaps, such as "*/20 9-17 * * *".`;
1155
+ }
1156
+ function xml(value) {
1157
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
1158
+ }
1159
+ /** A PowerShell single-quoted string. PowerShell also reads the typographic single quotes as quotes. */
1160
+ function powerShellString(value) {
1161
+ return `'${value.replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`;
1162
+ }
1163
+ function pad(value) {
1164
+ return String(value).padStart(2, "0");
1165
+ }
1166
+ function renderDaySchedule(schedule) {
1167
+ switch (schedule.kind) {
1168
+ case "always": return [];
1169
+ case "day": return [
1170
+ " <ScheduleByDay>",
1171
+ " <DaysInterval>1</DaysInterval>",
1172
+ " </ScheduleByDay>"
1173
+ ];
1174
+ case "week": return [
1175
+ " <ScheduleByWeek>",
1176
+ " <DaysOfWeek>",
1177
+ ...schedule.weekdays.map((weekday) => ` <${weekdayNames[weekday]} />`),
1178
+ " </DaysOfWeek>",
1179
+ " <WeeksInterval>1</WeeksInterval>",
1180
+ " </ScheduleByWeek>"
1181
+ ];
1182
+ case "month": return [
1183
+ " <ScheduleByMonth>",
1184
+ " <DaysOfMonth>",
1185
+ ...schedule.days.map((day) => ` <Day>${day}</Day>`),
1186
+ " </DaysOfMonth>",
1187
+ " <Months>",
1188
+ ...schedule.months.map((month) => ` <${monthNames[month - 1]} />`),
1189
+ " </Months>",
1190
+ " </ScheduleByMonth>"
1191
+ ];
1192
+ }
1193
+ }
1194
+ /** The `.ps1` file that the task runs: it sets the environment, runs the command, and appends its output to the log. */
1195
+ function renderTaskWrapper(spec, logFile) {
1196
+ return `\uFEFF${[
1197
+ `# ${generatedHeader}`,
1198
+ `$log = ${powerShellString(logFile)}`,
1199
+ ...Object.entries(spec.env).map(([name, value]) => `$env:${name} = ${powerShellString(value)}`),
1200
+ ...spec.cwd === void 0 ? [] : [`Set-Location -LiteralPath ${powerShellString(spec.cwd)}`],
1201
+ "$global:LASTEXITCODE = 1",
1202
+ `& ${spec.command.map(powerShellString).join(" ")} 2>&1 | ForEach-Object { "$_" } | Out-File -LiteralPath $log -Append -Encoding utf8`,
1203
+ "exit $global:LASTEXITCODE",
1204
+ ""
1205
+ ].join("\n")}`;
1206
+ }
1207
+ /** The log path that `renderTaskWrapper()` wrote. */
1208
+ function parseTaskWrapperLog(wrapper) {
1209
+ return wrapper.match(/^\$log = '((?:[^']|'')*)'\r?$/m)?.[1]?.replaceAll("''", "'");
1210
+ }
1211
+ /** The task XML. The description ends with a hash of the XML and the wrapper, which a later install compares. */
1212
+ function renderTaskXml(spec, triggers, options) {
1213
+ const render = (description) => [
1214
+ "<?xml version=\"1.0\" encoding=\"UTF-16\"?>",
1215
+ "<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">",
1216
+ " <RegistrationInfo>",
1217
+ ` <Description>${xml(description)}</Description>`,
1218
+ ` <URI>\\${xml(spec.name)}</URI>`,
1219
+ " </RegistrationInfo>",
1220
+ " <Triggers>",
1221
+ ...triggers.days.flatMap((days) => triggers.times.flatMap((time) => [
1222
+ days.kind === "always" ? " <TimeTrigger>" : " <CalendarTrigger>",
1223
+ ...time.repetition ? [
1224
+ " <Repetition>",
1225
+ ` <Interval>${time.repetition.interval}</Interval>`,
1226
+ ...time.repetition.duration ? [` <Duration>${time.repetition.duration}</Duration>`] : [],
1227
+ " <StopAtDurationEnd>false</StopAtDurationEnd>",
1228
+ " </Repetition>"
1229
+ ] : [],
1230
+ ` <StartBoundary>2026-01-01T${pad(Math.floor(time.start / 60))}:${pad(time.start % 60)}:00</StartBoundary>`,
1231
+ " <Enabled>true</Enabled>",
1232
+ ...spec.randomDelaySeconds ? [` <RandomDelay>${taskDuration(spec.randomDelaySeconds)}</RandomDelay>`] : [],
1233
+ ...renderDaySchedule(days),
1234
+ days.kind === "always" ? " </TimeTrigger>" : " </CalendarTrigger>"
1235
+ ])),
1236
+ " </Triggers>",
1237
+ " <Principals>",
1238
+ " <Principal id=\"Author\">",
1239
+ ...options.scope === "system" ? [" <UserId>S-1-5-18</UserId>", " <RunLevel>HighestAvailable</RunLevel>"] : [
1240
+ ` <UserId>${xml(options.userId)}</UserId>`,
1241
+ " <LogonType>InteractiveToken</LogonType>",
1242
+ " <RunLevel>LeastPrivilege</RunLevel>"
1243
+ ],
1244
+ " </Principal>",
1245
+ " </Principals>",
1246
+ " <Settings>",
1247
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
1248
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
1249
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
1250
+ ` <StartWhenAvailable>${spec.catchUp}</StartWhenAvailable>`,
1251
+ " <Enabled>true</Enabled>",
1252
+ " <Hidden>false</Hidden>",
1253
+ " <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>",
1254
+ " </Settings>",
1255
+ " <Actions Context=\"Author\">",
1256
+ " <Exec>",
1257
+ " <Command>powershell.exe</Command>",
1258
+ ` <Arguments>${xml(`-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "${options.wrapper}"`)}</Arguments>`,
1259
+ " </Exec>",
1260
+ " </Actions>",
1261
+ "</Task>",
1262
+ ""
1263
+ ].join("\n");
1264
+ const managed = `${spec.description}. Managed by ViteHub (${options.scope} scope).`;
1265
+ return render(`${managed} sha256:${createHash("sha256").update(render(managed)).update("\n").update(options.wrapperText).digest("hex")}`);
1266
+ }
1267
+ /** The scope in the marker that `renderTaskXml()` put at the end of a task description, else `undefined`. */
1268
+ function taskOwnerScope(description) {
1269
+ const scope = description?.match(/Managed by ViteHub \((user|system) scope\)\. sha256:[0-9a-f]{64}$/)?.[1];
1270
+ return scope === "user" || scope === "system" ? scope : void 0;
1271
+ }
1272
+ /** The hash that `renderTaskXml()` put in a task description. */
1273
+ function taskDescriptionHash(description) {
1274
+ return description?.match(/sha256:([0-9a-f]{64})/)?.[1];
1275
+ }
1276
+ /**
1277
+ * Windows PowerShell 5.1 joins native arguments without escaping them, so a quote, an empty argument, or a trailing
1278
+ * backslash in an argument with spaces reaches the program changed.
1279
+ */
1280
+ function unsafeWindowsArgument(argument) {
1281
+ if (argument === "") return "an empty argument";
1282
+ if (argument.includes("\"")) return "an argument with a double quote";
1283
+ if (/\s/.test(argument) && argument.endsWith("\\")) return "an argument with spaces that ends with a backslash";
1284
+ }
1285
+ /** Reads the JSON of the status script. */
1286
+ function parseTaskInfo(output) {
1287
+ const value = JSON.parse(output.trim() || "{}");
1288
+ if (typeof value !== "object" || value === null || !("installed" in value)) return { installed: false };
1289
+ return value;
1290
+ }
1291
+ function date(value) {
1292
+ if (!value) return void 0;
1293
+ const parsed = new Date(value);
1294
+ return Number.isNaN(parsed.getTime()) ? void 0 : parsed;
1295
+ }
1296
+ function taskInfoScript(name) {
1297
+ return [
1298
+ `$task = Get-ScheduledTask -TaskName ${powerShellString(name)} -TaskPath '\\' -ErrorAction SilentlyContinue`,
1299
+ "if (-not $task) { ConvertTo-Json -Compress @{ installed = $false }; exit 0 }",
1300
+ `$info = Get-ScheduledTaskInfo -TaskName ${powerShellString(name)} -TaskPath '\\'`,
1301
+ "function Iso($date) { if ($date -and $date.Year -ge 2000) { $date.ToUniversalTime().ToString('o') } else { $null } }",
1302
+ "ConvertTo-Json -Compress @{ installed = $true; state = [string]$task.State; description = $task.Description; lastRunTime = (Iso $info.LastRunTime); lastTaskResult = $info.LastTaskResult; nextRunTime = (Iso $info.NextRunTime) }"
1303
+ ].join("\n");
1304
+ }
1305
+ /** Task Scheduler tasks in the root folder, run as the current user or as SYSTEM. */
1306
+ function createTaskSchedulerDriver(host, scope) {
1307
+ /** A task of this name that ViteHub did not install in this scope. */
1308
+ const foreign = (task) => task.installed && taskOwnerScope(task.description) !== scope;
1309
+ const taskResource = (name, task) => {
1310
+ const owner = taskOwnerScope(task.description);
1311
+ return owner ? `the ${owner}-scope task \\${name}` : `the task \\${name}`;
1312
+ };
1313
+ const root = scope === "user" ? host.env.LOCALAPPDATA || join$1(host.homedir, "AppData", "Local") : host.env.ProgramData || host.env.PROGRAMDATA || "C:\\ProgramData";
1314
+ const wrapperPath = (name) => join$1(root, "ViteHub", "schedules", `${name}.ps1`);
1315
+ const defaultLogDir = (name) => join$1(root, name, "Logs");
1316
+ async function powershell(script) {
1317
+ const full = `$ErrorActionPreference = 'Stop'\n$ProgressPreference = 'SilentlyContinue'\n[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n${script}`;
1318
+ return host.exec("powershell.exe", [
1319
+ "-NoProfile",
1320
+ "-NonInteractive",
1321
+ "-ExecutionPolicy",
1322
+ "Bypass",
1323
+ "-EncodedCommand",
1324
+ Buffer.from(full, "utf16le").toString("base64")
1325
+ ]);
1326
+ }
1327
+ async function run(command, script) {
1328
+ const result = await powershell(script);
1329
+ if (result.code === 0) return [void 0, result];
1330
+ const output = commandOutput(result);
1331
+ if (/access is denied|0x80070005/i.test(output)) return [osScheduleErrors.SCHEDULE_OS_PERMISSION_REQUIRED({ scope }), void 0];
1332
+ return [osScheduleErrors.SCHEDULE_OS_COMMAND_FAILED({
1333
+ command,
1334
+ exitCode: result.code,
1335
+ output
1336
+ }), void 0];
1337
+ }
1338
+ async function info(name) {
1339
+ const [error, result] = await run(`Get-ScheduledTask -TaskName ${name}`, taskInfoScript(name));
1340
+ if (error) return [error, void 0];
1341
+ try {
1342
+ return [void 0, parseTaskInfo(result.stdout)];
1343
+ } catch {
1344
+ return [osScheduleErrors.SCHEDULE_OS_COMMAND_FAILED({
1345
+ command: `Get-ScheduledTask -TaskName ${name}`,
1346
+ exitCode: 0,
1347
+ output: `Unexpected output: ${commandOutput(result)}`
1348
+ }), void 0];
1349
+ }
1350
+ }
1351
+ return {
1352
+ async install(spec) {
1353
+ for (const argument of spec.command) {
1354
+ const problem = unsafeWindowsArgument(argument);
1355
+ if (problem) return [osScheduleErrors.SCHEDULE_OS_OPTION_UNSUPPORTED({
1356
+ platform: "win32",
1357
+ option: "command",
1358
+ reason: `Windows PowerShell 5.1 passes ${problem} to the program changed. Remove it from ${JSON.stringify(argument)}.`
1359
+ }), void 0];
1360
+ }
1361
+ const [zoneError, fields] = machineFieldsOrError("win32", spec, host);
1362
+ if (zoneError) return [zoneError, void 0];
1363
+ const triggers = taskTriggers(fields, {
1364
+ timeZone: host.machineTimeZone,
1365
+ changes: clockChanges(host.machineTimeZone, host.now())
1366
+ });
1367
+ if (typeof triggers === "string") return [osScheduleErrors.SCHEDULE_OS_CRON_UNSUPPORTED({
1368
+ platform: "win32",
1369
+ cron: spec.cron,
1370
+ reason: triggers
1371
+ }), void 0];
1372
+ const wrapper = wrapperPath(spec.name);
1373
+ const logDir = spec.logDir ?? defaultLogDir(spec.name);
1374
+ const logFile = join$1(logDir, `${spec.name}.log`);
1375
+ const wrapperText = renderTaskWrapper(spec, logFile);
1376
+ const taskXml = renderTaskXml(spec, triggers, {
1377
+ scope,
1378
+ userId: host.user,
1379
+ wrapper,
1380
+ wrapperText
1381
+ });
1382
+ const files = [wrapper, logFile];
1383
+ const [infoError, current] = await info(spec.name);
1384
+ if (infoError) return [infoError, void 0];
1385
+ if (foreign(current)) return [osScheduleErrors.SCHEDULE_OS_NAME_TAKEN({
1386
+ platform: "win32",
1387
+ name: spec.name,
1388
+ scope,
1389
+ resource: taskResource(spec.name, current)
1390
+ }), void 0];
1391
+ if (current.installed && current.state !== "Disabled" && taskDescriptionHash(current.description ?? void 0) === taskDescriptionHash(taskXml) && await host.fs.readFile(wrapper) === wrapperText) return [void 0, {
1392
+ files,
1393
+ changed: false
1394
+ }];
1395
+ await host.fs.mkdir(logDir);
1396
+ await host.fs.writeFile(wrapper, wrapperText);
1397
+ const xmlFile = join$1(root, "ViteHub", "schedules", `${spec.name}.xml`);
1398
+ await host.fs.writeFile(xmlFile, taskXml);
1399
+ const [registerError] = await run(`Register-ScheduledTask -TaskName ${spec.name}`, [`$xml = Get-Content -LiteralPath ${powerShellString(xmlFile)} -Raw -Encoding UTF8`, `Register-ScheduledTask -TaskName ${powerShellString(spec.name)} -TaskPath '\\' -Xml $xml -Force | Out-Null`].join("\n"));
1400
+ await host.fs.rm(xmlFile);
1401
+ if (registerError) {
1402
+ if (!current.installed) await host.fs.rm(wrapper);
1403
+ return [registerError, void 0];
1404
+ }
1405
+ return [void 0, {
1406
+ files,
1407
+ changed: true
1408
+ }];
1409
+ },
1410
+ async status(name) {
1411
+ const [error, task] = await info(name);
1412
+ if (error) return [error, void 0];
1413
+ if (foreign(task)) return [void 0, {
1414
+ name,
1415
+ platform: "win32",
1416
+ scope,
1417
+ installed: false,
1418
+ running: false
1419
+ }];
1420
+ const running = task.state === "Running";
1421
+ const lastRunAt = date(task.lastRunTime);
1422
+ const nextRunAt = date(task.nextRunTime);
1423
+ const result = task.lastTaskResult;
1424
+ const exited = typeof result === "number" && result !== taskNeverRan && result !== taskRunning && !running;
1425
+ const wrapper = await host.fs.readFile(wrapperPath(name));
1426
+ const logFile = wrapper === void 0 ? void 0 : parseTaskWrapperLog(wrapper);
1427
+ return [void 0, {
1428
+ name,
1429
+ platform: "win32",
1430
+ scope,
1431
+ installed: task.installed,
1432
+ running,
1433
+ ...lastRunAt ? { lastRunAt } : {},
1434
+ ...exited ? { lastExitCode: result } : {},
1435
+ ...nextRunAt ? { nextRunAt } : {},
1436
+ ...logFile ? { logFile } : {}
1437
+ }];
1438
+ },
1439
+ async uninstall(name) {
1440
+ const [infoError, task] = await info(name);
1441
+ if (infoError) return [infoError, void 0];
1442
+ if (foreign(task)) return [void 0, {
1443
+ name,
1444
+ platform: "win32",
1445
+ scope,
1446
+ removed: [],
1447
+ existed: false
1448
+ }];
1449
+ const wrapper = wrapperPath(name);
1450
+ const wrapperText = await host.fs.readFile(wrapper);
1451
+ if (task.installed) {
1452
+ const [error] = await run(`Unregister-ScheduledTask -TaskName ${name}`, `Unregister-ScheduledTask -TaskName ${powerShellString(name)} -TaskPath '\\' -Confirm:$false`);
1453
+ if (error) return [error, void 0];
1454
+ }
1455
+ const logFile = wrapperText === void 0 ? void 0 : parseTaskWrapperLog(wrapperText);
1456
+ const removed = [];
1457
+ for (const path of [wrapper, ...logFile ? [logFile] : []]) if (await host.fs.rm(path)) removed.push(path);
1458
+ for (const directory of [
1459
+ defaultLogDir(name),
1460
+ join$1(root, name),
1461
+ join$1(root, "ViteHub", "schedules"),
1462
+ join$1(root, "ViteHub")
1463
+ ]) await host.fs.rmdirIfEmpty(directory);
1464
+ return [void 0, {
1465
+ name,
1466
+ platform: "win32",
1467
+ scope,
1468
+ removed,
1469
+ existed: task.installed || wrapperText !== void 0
1470
+ }];
1471
+ }
1472
+ };
1473
+ }
1474
+ //#endregion
1475
+ //#region src/os/schedules.ts
1476
+ const optionKeys = /* @__PURE__ */ new Set([
1477
+ "catchUp",
1478
+ "command",
1479
+ "cwd",
1480
+ "description",
1481
+ "env",
1482
+ "logDir",
1483
+ "randomDelaySeconds",
1484
+ "scope"
1485
+ ]);
1486
+ const namePattern = /^[A-Za-z0-9][\w.-]{0,99}$/;
1487
+ const variableName = /^[A-Z_a-z]\w*$/;
1488
+ const platforms = /* @__PURE__ */ new Set([
1489
+ "darwin",
1490
+ "linux",
1491
+ "win32"
1492
+ ]);
1493
+ function invalid(problem) {
1494
+ return [osScheduleErrors.SCHEDULE_OS_INVALID_OPTIONS({ problem }), void 0];
1495
+ }
1496
+ function isString(value) {
1497
+ return typeof value === "string";
1498
+ }
1499
+ function isPlatform(platform) {
1500
+ return platforms.has(platform);
1501
+ }
1502
+ function isAbsolute$1(platform, path) {
1503
+ return platform === "win32" ? /^(?:[A-Za-z]:[\\/]|\\\\)/.test(path) : path.startsWith("/");
1504
+ }
1505
+ function checkName(name) {
1506
+ if (!isString(name) || !namePattern.test(name)) return invalid(`the name ${JSON.stringify(name)} must start with a letter or digit and use only letters, digits, ".", "_" and "-", up to 100 characters.`);
1507
+ return [void 0, name];
1508
+ }
1509
+ function checkScope(scope) {
1510
+ if (scope === void 0) return [void 0, "user"];
1511
+ if (scope === "user" || scope === "system") return [void 0, scope];
1512
+ return invalid("`scope` must be \"user\" or \"system\".");
1513
+ }
1514
+ function readSpec(platform, name, schedule, options) {
1515
+ if (!isRecord(schedule) || schedule.cron === void 0) return invalid("pass a Schedule with `cron`, such as `defineSchedule({ cron: \"0 * * * *\", handler })`.");
1516
+ const { cron, timeZone = "UTC" } = schedule;
1517
+ const fields = isString(cron) ? parseCronFields(cron) : void 0;
1518
+ if (!isString(cron) || !fields) return invalid("`cron` must be a five-field cron expression, such as \"0 9 * * 1-5\".");
1519
+ if (timeZone !== "local" && !isIanaTimeZone(timeZone)) return invalid("`timeZone` must be an IANA time zone, such as \"Europe/Madrid\", or \"local\" for the time zone of the machine.");
1520
+ if (!isRecord(options)) return invalid("pass options with `command`.");
1521
+ const unknownKey = Object.keys(options).find((key) => !optionKeys.has(key));
1522
+ if (unknownKey) return invalid(`\`${unknownKey}\` is not an option.`);
1523
+ const { catchUp = true, command, cwd, description = `${name} (ViteHub schedule)`, env = {}, logDir, randomDelaySeconds } = options;
1524
+ if (!Array.isArray(command) || !command.length || !command.every(isString)) return invalid("`command` must be a list of strings: the program and its arguments.");
1525
+ if (!isAbsolute$1(platform, command[0])) return invalid(`\`command[0]\` must be an absolute path, such as process.execPath. ${JSON.stringify(command[0])} is not.`);
1526
+ const [scopeError, scope] = checkScope(options.scope);
1527
+ if (scopeError) return [scopeError, void 0];
1528
+ if (typeof catchUp !== "boolean") return invalid("`catchUp` must be a boolean.");
1529
+ if (!isRecord(env)) return invalid("`env` must be an object of strings.");
1530
+ const variables = {};
1531
+ for (const [key, value] of Object.entries(env)) {
1532
+ if (!variableName.test(key)) return invalid(`\`env\` has an invalid variable name ${JSON.stringify(key)}.`);
1533
+ if (!isString(value)) return invalid(`\`env.${key}\` must be a string.`);
1534
+ variables[key] = value;
1535
+ }
1536
+ for (const [option, path] of [["cwd", cwd], ["logDir", logDir]]) if (path !== void 0 && (!isString(path) || !isAbsolute$1(platform, path))) return invalid(`\`${option}\` must be an absolute path.`);
1537
+ if (randomDelaySeconds !== void 0 && !(Number.isInteger(randomDelaySeconds) && Number(randomDelaySeconds) >= 0)) return invalid("`randomDelaySeconds` must be a whole number of seconds, 0 or more.");
1538
+ if (!isString(description)) return invalid("`description` must be a string.");
1539
+ const spec = {
1540
+ name,
1541
+ description,
1542
+ cron,
1543
+ fields,
1544
+ timeZone,
1545
+ command,
1546
+ env: variables,
1547
+ catchUp,
1548
+ scope,
1549
+ ...isString(cwd) ? { cwd } : {},
1550
+ ...isString(logDir) ? { logDir } : {},
1551
+ ...typeof randomDelaySeconds === "number" ? { randomDelaySeconds } : {}
1552
+ };
1553
+ if (platform === "linux") {
1554
+ if ([
1555
+ ...command,
1556
+ ...Object.values(variables),
1557
+ cwd,
1558
+ logDir,
1559
+ description
1560
+ ].filter(isString).some((value) => /[\n\r]/.test(value))) return invalid("systemd values must be one line. Remove the line break from `command`, `env`, `cwd`, `logDir` or `description`.");
1561
+ }
1562
+ return [void 0, spec];
1563
+ }
1564
+ /** The public functions on `host`. Tests pass a fake host. */
1565
+ function createOsSchedules(host) {
1566
+ function driver(scope) {
1567
+ const platform = host.platform;
1568
+ if (!isPlatform(platform)) return [osScheduleErrors.SCHEDULE_OS_PLATFORM_UNSUPPORTED({ platform }), void 0];
1569
+ return [void 0, {
1570
+ platform,
1571
+ driver: (platform === "linux" ? createSystemdDriver : platform === "darwin" ? createLaunchdDriver : createTaskSchedulerDriver)(host, scope)
1572
+ }];
1573
+ }
1574
+ function target(name, options) {
1575
+ const [nameError, checked] = checkName(name);
1576
+ if (nameError) return [nameError, void 0];
1577
+ if (options !== void 0 && !isRecord(options)) return invalid("pass `{ scope }` or nothing.");
1578
+ const unknownKey = Object.keys(options ?? {}).find((key) => key !== "scope");
1579
+ if (unknownKey) return invalid(`\`${unknownKey}\` is not an option.`);
1580
+ const [scopeError, scope] = checkScope(options?.scope);
1581
+ if (scopeError) return [scopeError, void 0];
1582
+ const [driverError, found] = driver(scope);
1583
+ if (driverError) return [driverError, void 0];
1584
+ return [void 0, {
1585
+ name: checked,
1586
+ scope,
1587
+ ...found
1588
+ }];
1589
+ }
1590
+ async function osScheduleStatus(name, options) {
1591
+ const [error, found] = target(name, options);
1592
+ if (error) return [error, void 0];
1593
+ return found.driver.status(found.name);
1594
+ }
1595
+ async function uninstallOsSchedule(name, options) {
1596
+ const [error, found] = target(name, options);
1597
+ if (error) return [error, void 0];
1598
+ return found.driver.uninstall(found.name);
1599
+ }
1600
+ async function installOsSchedule(name, schedule, options) {
1601
+ const [nameError, checked] = checkName(name);
1602
+ if (nameError) return [nameError, void 0];
1603
+ if (!isPlatform(host.platform)) return [osScheduleErrors.SCHEDULE_OS_PLATFORM_UNSUPPORTED({ platform: host.platform }), void 0];
1604
+ const [specError, spec] = readSpec(host.platform, checked, schedule, options);
1605
+ if (specError) return [specError, void 0];
1606
+ const { scope } = spec;
1607
+ if (scope === "system" && host.uid !== void 0 && host.uid !== 0) return [osScheduleErrors.SCHEDULE_OS_PERMISSION_REQUIRED({ scope }), void 0];
1608
+ const [driverError, found] = driver(scope);
1609
+ if (driverError) return [driverError, void 0];
1610
+ const withCwd = spec.cwd === void 0 && scope === "user" ? {
1611
+ ...spec,
1612
+ cwd: host.homedir
1613
+ } : spec;
1614
+ const [installError, installation] = await found.driver.install(withCwd);
1615
+ if (installError) return [installError, void 0];
1616
+ return [void 0, {
1617
+ name: checked,
1618
+ platform: found.platform,
1619
+ scope,
1620
+ ...installation,
1621
+ status: () => osScheduleStatus(checked, { scope }),
1622
+ uninstall: () => uninstallOsSchedule(checked, { scope })
1623
+ }];
1624
+ }
1625
+ return {
1626
+ installOsSchedule,
1627
+ osScheduleStatus,
1628
+ uninstallOsSchedule
1629
+ };
1630
+ }
1631
+ //#endregion
1632
+ //#region src/os.ts
1633
+ let schedules;
1634
+ function nodeSchedules() {
1635
+ schedules ??= createOsSchedules(createNodeHost());
1636
+ return schedules;
1637
+ }
1638
+ /**
1639
+ * Installs `schedule` as an OS timer named `name` that runs `options.command`: a systemd timer on Linux, a launchd job
1640
+ * on macOS, or a Task Scheduler task on Windows. It runs on the Schedule's `cron` in its `timeZone`, or fails with a
1641
+ * code when the OS cannot run that cron exactly. Installing the same timer again changes nothing. It fails with
1642
+ * `SCHEDULE_OS_NAME_TAKEN` when the OS already has a timer of that name that ViteHub did not install in this scope.
1643
+ */
1644
+ function installOsSchedule(name, schedule, options) {
1645
+ return nodeSchedules().installOsSchedule(name, schedule, options);
1646
+ }
1647
+ /** Reads the state of the OS timer `name`: whether it is installed and running, its last run and exit code, and its next run. */
1648
+ function osScheduleStatus(name, target) {
1649
+ return nodeSchedules().osScheduleStatus(name, target);
1650
+ }
1651
+ /**
1652
+ * Stops and removes the OS timer `name` and the files that it owns. Removing a timer that does not exist succeeds.
1653
+ * A timer of the same name that ViteHub did not install in this scope stays as it is, and `existed` is `false`.
1654
+ */
1655
+ function uninstallOsSchedule(name, target) {
1656
+ return nodeSchedules().uninstallOsSchedule(name, target);
1657
+ }
1658
+ //#endregion
1659
+ export { installOsSchedule, osScheduleErrors, osScheduleStatus, uninstallOsSchedule };