Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

StateEncoding.ts

141 lines4.8 KB

1import * as Duration from "effect/Duration";
2import * as Redacted from "effect/Redacted";
3import { isResource } from "../Resource.ts";
4​
5/**
6 * JSON marker used to tag a `Redacted<T>` value when writing state.
7 * The reviver recognises objects with exactly this key and rebuilds
8 * the `Redacted` wrapper on read.
9 */
10export const REDACTED_MARKER = "__redacted__";
11​
12/**
13 * JSON marker used to tag a `Duration` value when writing state.
14 * The reviver recognises objects with exactly this key and rebuilds
15 * a real `Duration` instance on read so that downstream code can call
16 * `Duration.toSeconds`, `Duration.toMillis`, etc. without first
17 * decoding `Duration.toJSON`'s `{_id,_tag,...}` shape.
18 */
19export const DURATION_MARKER = "__duration__";
20​
21const decodeDuration = (encoded: unknown): Duration.Duration | undefined => {
22 if (encoded === null || typeof encoded !== "object") return undefined;
23 const json = encoded as {
24 _tag?: "Millis" | "Nanos" | "Infinity" | "NegativeInfinity";
25 millis?: number;
26 nanos?: string;
27 };
28 switch (json._tag) {
29 case "Millis":
30 return json.millis !== undefined
31 ? Duration.millis(json.millis)
32 : undefined;
33 case "Nanos":
34 return json.nanos !== undefined
35 ? Duration.nanos(BigInt(json.nanos))
36 : undefined;
37 case "Infinity":
38 return Duration.infinity;
39 case "NegativeInfinity":
40 return Duration.zero; // Effect treats negatives as zero clamp
41 default:
42 return undefined;
43 }
44};
45​
46/**
47 * Recursively encode a state value for JSON serialisation.
48 *
49 * - `Redacted<T>` values are wrapped as `{ [REDACTED_MARKER]: <inner> }`
50 * so the actual string is persisted rather than the `<redacted>`
51 * placeholder produced by the default `toJSON`.
52 * - `Resource` instances are flattened to `{ id, type, props, attr }`
53 * so persisted state matches the schema used by the loader.
54 * - Plain objects and arrays are walked structurally.
55 */
56export const encodeState = (value: unknown): unknown => {
57 if (
58 value === null ||
59 value === undefined ||
60 typeof value === "string" ||
61 typeof value === "number" ||
62 typeof value === "boolean"
63 )
64 return value;
65 if (Redacted.isRedacted(value)) {
66 return {
67 [REDACTED_MARKER]: encodeState(Redacted.value(value)),
68 };
69 }
70 if (Duration.isDuration(value)) {
71 // `JSON.stringify(Duration.seconds(N))` already invokes Duration.toJSON,
72 // but encodeState is also called for code paths that don't go through
73 // `JSON.stringify` (e.g. the HTTP state-store). Tag with our marker so
74 // the reviver can unambiguously rebuild a real Duration instance —
75 // Duration.toJSON's `{_id,_tag,...}` shape is NOT a valid Duration.Input.
76 return {
77 [DURATION_MARKER]: value.toJSON(),
78 };
79 }
80 if (isResource(value)) {
81 return {
82 id: value.LogicalId,
83 type: value.Type,
84 props: encodeState(value.Props),
85 attr: encodeState(value.Attributes),
86 };
87 }
88 if (Array.isArray(value)) return value.map(encodeState);
89 if (typeof value === "object") {
90 const result: Record<string, unknown> = {};
91 for (const [k, v] of Object.entries(value)) {
92 result[k] = encodeState(v);
93 }
94 return result;
95 }
96 return value;
97};
98​
99/**
100 * JSON reviver that rebuilds `Redacted<T>` values that were written
101 * through {@link encodeState}. Intended for use with `JSON.parse`.
102 */
103export const reviveState = (_key: string, value: unknown): unknown => {
104 if (value !== null && typeof value === "object" && !Array.isArray(value)) {
105 const obj = value as Record<string, unknown>;
106 if (REDACTED_MARKER in obj) {
107 return Redacted.make(obj[REDACTED_MARKER]);
108 }
109 if (DURATION_MARKER in obj) {
110 const decoded = decodeDuration(obj[DURATION_MARKER]);
111 if (decoded !== undefined) return decoded;
112 }
113 }
114 return value;
115};
116​
117/**
118 * Recursively walk an already-decoded value and rebuild `Redacted<T>`
119 * instances from `{ [REDACTED_MARKER]: <inner> }` envelopes. Mirror
120 * image of {@link encodeState} for callers that hold a parsed JS
121 * value rather than a JSON string (e.g. the HTTP state-store client,
122 * which receives values pre-parsed by `HttpApiClient`).
123 */
124export const reviveStateRecursive = (value: unknown): unknown => {
125 if (value === null || typeof value !== "object") return value;
126 if (Array.isArray(value)) return value.map(reviveStateRecursive);
127 const obj = value as Record<string, unknown>;
128 const keys = Object.keys(obj);
129 if (keys.length === 1 && keys[0] === REDACTED_MARKER) {
130 return Redacted.make(reviveStateRecursive(obj[REDACTED_MARKER]));
131 }
132 if (keys.length === 1 && keys[0] === DURATION_MARKER) {
133 const decoded = decodeDuration(obj[DURATION_MARKER]);
134 if (decoded !== undefined) return decoded;
135 }
136 const result: Record<string, unknown> = {};
137 for (const [k, v] of Object.entries(obj)) {
138 result[k] = reviveStateRecursive(v);
139 }
140 return result;
141};