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

main
ts 201 lines 7.57 KB
Raw
1 import * as Duration from "effect/Duration";
2 import * as Redacted from "effect/Redacted";
3 import { isResource } from "../Resource.ts";
4 import { base64ToBytes, bytesToBase64 } from "../Util/base64.ts";
5
6 /**
7 * JSON marker used to tag a `Redacted<T>` value when writing state.
8 * The reviver recognises objects with exactly this key and rebuilds
9 * the `Redacted` wrapper on read.
10 */
11 export const REDACTED_MARKER = "__redacted__";
12
13 /**
14 * JSON marker used to tag a `Duration` value when writing state.
15 * The reviver recognises objects with exactly this key and rebuilds
16 * a real `Duration` instance on read so that downstream code can call
17 * `Duration.toSeconds`, `Duration.toMillis`, etc. without first
18 * decoding `Duration.toJSON`'s `{_id,_tag,...}` shape.
19 */
20 export const DURATION_MARKER = "__duration__";
21
22 /**
23 * JSON marker used to tag a `Date` value when writing state. The reviver
24 * recognises objects with exactly this key and rebuilds a real `Date`
25 * instance on read, so a Date-typed prop read back out of persisted state
26 * (`olds` in provider `diff`/`delete`/`read`) is a `Date` again — not the
27 * bare ISO string `JSON.stringify` would otherwise leave behind.
28 */
29 export const DATE_MARKER = "__date__";
30
31 /**
32 * JSON marker used to tag a byte array (`Uint8Array`) when writing state.
33 * The reviver rebuilds a real `Uint8Array`, so a byte-valued prop (a WAF
34 * byte-match string, a zip) read back out of persisted state is the same
35 * value the program declares — instead of an index-keyed object.
36 */
37 export const BYTES_MARKER = "__bytes__";
38
39 const decodeDate = (encoded: unknown): Date | undefined => {
40 if (typeof encoded !== "string") return undefined;
41 const date = new Date(encoded);
42 return Number.isNaN(date.getTime()) ? undefined : date;
43 };
44
45 /**
46 * Rebuild a {@link Duration.Duration} from `Duration.toJSON`'s
47 * `{_id,_tag,millis?,nanos?}` shape. Shared by state persistence and the
48 * RPC sidecar — that JSON is not a valid `Duration.Input`.
49 */
50 export const decodeDuration = (encoded: unknown): Duration.Duration | undefined => {
51 if (encoded === null || typeof encoded !== "object") return undefined;
52 const json = encoded as {
53 _tag?: "Millis" | "Nanos" | "Infinity" | "NegativeInfinity";
54 millis?: number;
55 nanos?: string;
56 };
57 switch (json._tag) {
58 case "Millis":
59 return json.millis !== undefined ? Duration.millis(json.millis) : undefined;
60 case "Nanos":
61 return json.nanos !== undefined ? Duration.nanos(BigInt(json.nanos)) : undefined;
62 case "Infinity":
63 return Duration.infinity;
64 case "NegativeInfinity":
65 return Duration.negativeInfinity;
66 default:
67 return undefined;
68 }
69 };
70
71 /**
72 * Recursively encode a state value for JSON serialisation.
73 *
74 * - `Redacted<T>` values are wrapped as `{ [REDACTED_MARKER]: <inner> }`
75 * so the actual string is persisted rather than the `<redacted>`
76 * placeholder produced by the default `toJSON`.
77 * - `Resource` instances are flattened to `{ id, type, props, attr }`
78 * so persisted state matches the schema used by the loader.
79 * - Plain objects and arrays are walked structurally.
80 */
81 export const encodeState = (value: unknown): unknown => {
82 if (
83 value === null ||
84 value === undefined ||
85 typeof value === "string" ||
86 typeof value === "number" ||
87 typeof value === "boolean"
88 )
89 return value;
90 if (Redacted.isRedacted(value)) {
91 return {
92 [REDACTED_MARKER]: value.pipe(Redacted.value, encodeState),
93 };
94 }
95 if (Duration.isDuration(value)) {
96 // `JSON.stringify(Duration.seconds(N))` already invokes Duration.toJSON,
97 // but encodeState is also called for code paths that don't go through
98 // `JSON.stringify` (e.g. the HTTP state-store). Tag with our marker so
99 // the reviver can unambiguously rebuild a real Duration instance —
100 // Duration.toJSON's `{_id,_tag,...}` shape is NOT a valid Duration.Input.
101 return {
102 [DURATION_MARKER]: value.toJSON(),
103 };
104 }
105 // Dates are serializable leaves and must round-trip: walking one
106 // structurally would persist `{}` (`Object.entries(new Date())` is empty)
107 // — and every later plan would then diff the empty object against the
108 // program's Date and churn a phantom update forever. Tag with our marker
109 // so the reviver rebuilds a real Date instance; rows written before the
110 // marker carry a bare ISO string, which `canonicalize` in Diff.ts still
111 // compares as equal to a live Date, so legacy rows never churn either.
112 if (value instanceof Date) {
113 return { [DATE_MARKER]: value.toJSON() };
114 }
115 if (value instanceof Uint8Array) {
116 return { [BYTES_MARKER]: bytesToBase64(value) };
117 }
118 if (isResource(value)) {
119 return {
120 id: value.LogicalId,
121 type: value.Type,
122 props: encodeState(value.Props),
123 attr: encodeState(value.Attributes),
124 };
125 }
126 if (Array.isArray(value)) return value.map(encodeState);
127 if (typeof value === "object") {
128 const result: Record<string, unknown> = {};
129 for (const [k, v] of Object.entries(value)) {
130 result[k] = encodeState(v);
131 }
132 return result;
133 }
134 return value;
135 };
136
137 /**
138 * JSON reviver that rebuilds `Redacted<T>` values that were written
139 * through {@link encodeState}. Intended for use with `JSON.parse`.
140 */
141 export const reviveState = (_key: string, value: unknown): unknown => {
142 if (value !== null && typeof value === "object" && !Array.isArray(value)) {
143 const obj = value as Record<string, unknown>;
144 if (REDACTED_MARKER in obj) {
145 return Redacted.make(obj[REDACTED_MARKER]);
146 }
147 if (DURATION_MARKER in obj) {
148 const decoded = decodeDuration(obj[DURATION_MARKER]);
149 if (decoded !== undefined) return decoded;
150 }
151 // Exact single-key match only — unlike the legacy REDACTED/DURATION
152 // markers there is no pre-marker data to tolerate, so a user object
153 // that merely CONTAINS the key alongside other fields is never
154 // collapsed into a Date (mirrors reviveStateRecursive's strictness).
155 if (DATE_MARKER in obj && Object.keys(obj).length === 1) {
156 const decoded = decodeDate(obj[DATE_MARKER]);
157 if (decoded !== undefined) return decoded;
158 }
159 if (
160 BYTES_MARKER in obj &&
161 Object.keys(obj).length === 1 &&
162 typeof obj[BYTES_MARKER] === "string"
163 ) {
164 return base64ToBytes(obj[BYTES_MARKER]);
165 }
166 }
167 return value;
168 };
169
170 /**
171 * Recursively walk an already-decoded value and rebuild `Redacted<T>`
172 * instances from `{ [REDACTED_MARKER]: <inner> }` envelopes. Mirror
173 * image of {@link encodeState} for callers that hold a parsed JS
174 * value rather than a JSON string (e.g. the HTTP state-store client,
175 * which receives values pre-parsed by `HttpApiClient`).
176 */
177 export const reviveStateRecursive = (value: unknown): unknown => {
178 if (value === null || typeof value !== "object") return value;
179 if (Array.isArray(value)) return value.map(reviveStateRecursive);
180 const obj = value as Record<string, unknown>;
181 const keys = Object.keys(obj);
182 if (keys.length === 1 && keys[0] === REDACTED_MARKER) {
183 return Redacted.make(reviveStateRecursive(obj[REDACTED_MARKER]));
184 }
185 if (keys.length === 1 && keys[0] === DURATION_MARKER) {
186 const decoded = decodeDuration(obj[DURATION_MARKER]);
187 if (decoded !== undefined) return decoded;
188 }
189 if (keys.length === 1 && keys[0] === DATE_MARKER) {
190 const decoded = decodeDate(obj[DATE_MARKER]);
191 if (decoded !== undefined) return decoded;
192 }
193 if (keys.length === 1 && keys[0] === BYTES_MARKER && typeof obj[BYTES_MARKER] === "string") {
194 return base64ToBytes(obj[BYTES_MARKER]);
195 }
196 const result: Record<string, unknown> = {};
197 for (const [k, v] of Object.entries(obj)) {
198 result[k] = reviveStateRecursive(v);
199 }
200 return result;
201 };