The best way to control Claude Code, Codex and more from any computer or phone

main
ts 72 lines 2.73 KB
Raw
1 import * as Duration from "effect/Duration";
2
3 /**
4 * Re-hydrate a {@link Duration.Input} that may have been persisted to (and
5 * read back from) state as a structural `Duration` JSON.
6 *
7 * When a `Duration.Duration` round-trips through JSON state it is serialized
8 * to `{ _id: "Duration", _tag: "Millis" | "Nanos" | "Infinity", ... }`, which
9 * is NOT a valid {@link Duration.Input} on the way back in. This normalizes
10 * such a value back to a plain input (`number` millis, `bigint` nanos, or the
11 * `"Infinity"` literal). Any already-valid input (a number, a `"20 seconds"`
12 * string, or a live `Duration`) is returned unchanged.
13 */
14 export const normalizeDurationInput = (input: Duration.Input): Duration.Input => {
15 const json = input as {
16 _id?: unknown;
17 _tag?: "Millis" | "Nanos" | "Infinity" | "NegativeInfinity";
18 millis?: number;
19 nanos?: string;
20 };
21 return json._id === "Duration"
22 ? json._tag === "Millis"
23 ? json.millis!
24 : json._tag === "Nanos"
25 ? BigInt(json.nanos!)
26 : "Infinity"
27 : input;
28 };
29
30 const wire =
31 (to: (input: Duration.Input) => number) =>
32 (input: Duration.Input | undefined): number | undefined =>
33 input === undefined ? undefined : Math.round(to(normalizeDurationInput(input)));
34
35 /**
36 * Convert a {@link Duration.Input} to whole seconds for a wire/API field,
37 * normalizing any persisted-state `Duration` JSON first. Returns `undefined`
38 * when `input` is `undefined` so call sites can map optional fields directly.
39 */
40 export const toWireSeconds = wire(Duration.toSeconds);
41
42 /** Convert a {@link Duration.Input} to whole milliseconds for a wire/API field. */
43 export const toWireMillis = wire(Duration.toMillis);
44
45 /** Convert a {@link Duration.Input} to whole minutes for a wire/API field. */
46 export const toWireMinutes = wire(Duration.toMinutes);
47
48 /** Convert a {@link Duration.Input} to whole hours for a wire/API field. */
49 export const toWireHours = wire(Duration.toHours);
50
51 /** Convert a {@link Duration.Input} to whole days for a wire/API field. */
52 export const toWireDays = wire(Duration.toDays);
53
54 /**
55 * Convert a {@link Duration.Input} to whole, non-negative
56 * milliseconds. Returns `undefined` when `input` is `undefined`,
57 * so call sites can map through optional duration fields without
58 * a branch.
59 */
60 export const toMillis = (input: Duration.Input | undefined) =>
61 input === undefined
62 ? undefined
63 : Math.max(0, Math.ceil(Duration.toMillis(normalizeDurationInput(input))));
64
65 /**
66 * Convert a {@link Duration.Input} to whole, non-negative seconds.
67 * Returns `undefined` when `input` is `undefined`.
68 */
69 export const toSeconds = (input: Duration.Input | undefined) =>
70 input === undefined
71 ? undefined
72 : Math.max(0, Math.ceil(Duration.toSeconds(normalizeDurationInput(input))));