@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 327 lines 12.3 KB
Raw
1 import * as Duration from "effect/Duration";
2 import * as Effect from "effect/Effect";
3 import * as Redacted from "effect/Redacted";
4 import type { Input } from "./Input.ts";
5 import * as Output from "./Output.ts";
6 import type { BindingNode } from "./Plan.ts";
7 import type { ResourceBinding } from "./Resource.ts";
8 import { bytesToBase64 } from "./Util/base64.ts";
9 import { isPlainData, isPrimitive, mapPlainData } from "./Util/data.ts";
10
11 export type Diff = NoopDiff | UpdateDiff | ReplaceDiff;
12
13 export interface NoopDiff {
14 action: "noop";
15 /**
16 * Properties that stay stable if `--force` upgrades this noop to an
17 * update. A plain noop exposes every persisted attribute downstream, so
18 * this only matters under `--force`, where the engine otherwise falls back
19 * to `provider.stables` and drops conditional stables (e.g. a
20 * rename-mutable `name` that is stable because the `name` prop is
21 * unchanged).
22 */
23 stables?: string[];
24 }
25
26 export interface UpdateDiff {
27 action: "update";
28 /** properties that won't change as part of this update */
29 stables?: string[];
30 }
31
32 export interface ReplaceDiff {
33 action: "replace";
34 deleteFirst?: boolean;
35 stables?: undefined;
36 }
37
38 /**
39 * Returns true when `value` (or any nested leaf) is still an unresolved
40 * plan-time expression — i.e. an `Output`/`Expr` or an `Effect` that was
41 * not fully evaluated by `resolveInput` in Plan.ts.
42 *
43 * Use at the top of a provider `diff` to short-circuit before field access:
44 *
45 * ```ts
46 * if (!isResolved(news)) return undefined;
47 * const resolved = news as MyProps;
48 * ```
49 */
50 export const hasUnresolvedInputs = <T>(value: Input<NoInfer<T>>): value is T =>
51 _hasUnresolved(value);
52
53 export const isResolved = <T>(value: Input<T>): value is T => !_hasUnresolved(value);
54
55 const _hasUnresolved = (value: unknown, seen: WeakSet<object> = new WeakSet()): boolean => {
56 if (value == null || isPrimitive(value)) return false;
57 if (Output.isExpr(value) || Effect.isEffect(value)) return true;
58 // Only plain data is traversed; any other class instance (Layer, Context,
59 // Date, SDK objects) is a resolved leaf — see isPlainData (#1082).
60 if (isPlainData(value)) {
61 if (seen.has(value)) return false;
62 seen.add(value);
63 return Object.values(value).some((v) => _hasUnresolved(v, seen));
64 }
65 return false;
66 };
67
68 /**
69 * Deeply replace every unresolved plan-time expression (an `Output`/`Expr`
70 * or an un-evaluated `Effect`) with `undefined`, leaving resolved values
71 * (including opaque `Redacted`/`Duration` instances) intact.
72 *
73 * Persisted resource state must only ever hold plain data. Durable (JSON)
74 * state stores already enforce this implicitly — Output proxies are
75 * function-typed, so `JSON.stringify` silently drops them — but the
76 * in-memory store used by tests retains live proxies, which would later be
77 * fed back into provider lifecycle operations as `olds` after an
78 * interrupted apply (e.g. `read` during a destroy plan) and blow up on
79 * first string coercion. Sanitizing at the commit boundary keeps both
80 * store kinds consistent with the provider contract that `olds` is
81 * resolved `Props`.
82 */
83 export const stripUnresolved = <T>(value: T): T => _stripUnresolved(value) as T;
84
85 const _stripUnresolved = (
86 value: unknown,
87 // Ancestor-path cycle guard: a value on its own ancestor chain is cut to
88 // `undefined` (a cycle can never persist). Sync DFS, so add/delete around
89 // the recursion is race-free and keeps shared diamond references intact
90 // (#1082).
91 ancestors: WeakSet<object> = new WeakSet(),
92 ): unknown => {
93 if (value == null || isPrimitive(value)) return value;
94 if (Output.isExpr(value) || Effect.isEffect(value)) return undefined;
95 // Serializable leaves — the only class instances persisted state may
96 // carry (StateEncoding knows Redacted/Duration/Date/bytes). Rebuilding
97 // them structurally would strip their prototype.
98 if (
99 Redacted.isRedacted(value) ||
100 Duration.isDuration(value) ||
101 value instanceof Date ||
102 value instanceof Uint8Array
103 ) {
104 return value;
105 }
106 if (isPlainData(value)) {
107 return mapPlainData(value, ancestors, (child) => _stripUnresolved(child, ancestors));
108 }
109 // Any other class instance (Layer, Context, SDK objects) is runtime-only
110 // wiring that can't round-trip through JSON — a beta.103 Context is even
111 // cyclic (#1082). Persisted state holds plain data only.
112 return undefined;
113 };
114
115 /**
116 * Deeply replace Effect-valued entries with `undefined`, leaving resolved
117 * values AND unresolved `Output`/`Expr`s intact.
118 *
119 * Effect-valued props — e.g. a tagged Worker class in `env` (the
120 * circular-bindings pattern) — can never be evaluated inside lifecycle
121 * operations, and {@link stripUnresolved} drops them from persisted state at
122 * the commit boundary. A provider `diff` that wants its structural change
123 * detection to still run despite them strips them first, so `isResolved`
124 * gates only on genuinely-unresolved Outputs (#874). The Effects' deploy-time
125 * identity is carried by the resolved binding data instead.
126 */
127 export const stripEffects = <T>(value: T): T => _stripEffects(value) as T;
128
129 const _stripEffects = (
130 value: unknown,
131 // Ancestor-path cycle guard — see _stripUnresolved (#1082).
132 ancestors: WeakSet<object> = new WeakSet(),
133 ): unknown => {
134 if (value == null || isPrimitive(value)) return value;
135 // Output proxies are left intact (so `isResolved` still sees them); they
136 // must be tested BEFORE `Effect.isEffect` because Output exprs are
137 // yieldable and would otherwise be misclassified as plain Effects.
138 if (Output.isExpr(value)) return value;
139 if (Effect.isEffect(value)) return undefined;
140 if (
141 Redacted.isRedacted(value) ||
142 Duration.isDuration(value) ||
143 value instanceof Date ||
144 value instanceof Uint8Array
145 ) {
146 return value;
147 }
148 if (isPlainData(value)) {
149 return mapPlainData(value, ancestors, (child) => _stripEffects(child, ancestors));
150 }
151 // Non-plain instances (Layer, Context, SDK objects) are dropped with
152 // Effects — same runtime-only rationale, and their internals may be
153 // cyclic (effect ≥4.0.0-beta.103's Context — #1082).
154 return undefined;
155 };
156
157 export const somePropsAreDifferent = <Props extends Record<string, any>>(
158 olds: Props,
159 news: Props,
160 props: (keyof Props)[],
161 ) => {
162 for (const prop of props) {
163 if (olds[prop] !== news[prop]) {
164 return true;
165 }
166 }
167 return false;
168 };
169
170 export const anyPropsAreDifferent = <Props extends Record<string, any>>(
171 olds: Props,
172 news: Props,
173 ) => {
174 for (const prop in olds) {
175 if (olds[prop] !== news[prop]) {
176 return true;
177 }
178 }
179 for (const prop in news) {
180 if (!(prop in olds)) {
181 return true;
182 }
183 }
184 return false;
185 };
186
187 export const havePropsChanged = <Props extends object>(
188 oldProps: Props | undefined,
189 newProps: Props,
190 ) =>
191 Output.hasOutputs(newProps) ||
192 // Compare both sides through `stripUnresolved` so the comparison is
193 // symmetric with the commit boundary: persisted props can never hold an
194 // Effect or Output expr (stripped at commit / silently dropped by JSON
195 // serialization), while desired props may still carry them — e.g. a tagged
196 // Worker class in `env` serializes via its `toJSON` to
197 // `{"_id":"Effect",...}` and would otherwise report a phantom change on
198 // every plan, forever (#874). Unresolved Outputs in `newProps` are already
199 // caught by the `hasOutputs` guard above, so stripping here never hides a
200 // real difference.
201 JSON.stringify(canonicalize(stripUnresolved(oldProps ?? {}), false)) !==
202 JSON.stringify(canonicalize(stripUnresolved(newProps ?? {}), false));
203
204 export type DeepEqualOptions = {
205 /**
206 * When true, treat `null` and `undefined` as equivalent at any depth.
207 * Useful when comparing cloud-API responses (which often return `null`
208 * for unconfigured optional fields) against desired-state shapes built
209 * from `props?.x` (which leave the same fields `undefined`).
210 *
211 * @default false
212 */
213 stripNullish?: boolean;
214 };
215
216 /**
217 * Sort-keys deep equality for plain data (objects, arrays, primitives).
218 * Use in provider `diff` handlers instead of ad-hoc `JSON.stringify` comparisons.
219 *
220 * By default, `null` and `undefined` are treated as distinct. Pass
221 * `{ stripNullish: true }` to opt into treating them as equivalent.
222 */
223 export const deepEqual = (a: unknown, b: unknown, options?: DeepEqualOptions): boolean =>
224 JSON.stringify(canonicalize(a, options?.stripNullish ?? false)) ===
225 JSON.stringify(canonicalize(b, options?.stripNullish ?? false));
226
227 const canonicalize = (
228 value: unknown,
229 stripNullish: boolean,
230 // Ancestor-path cycle guard — see _stripUnresolved (#1082).
231 ancestors: WeakSet<object> = new WeakSet(),
232 ): unknown => {
233 if (stripNullish && value == null) return undefined;
234 if (Redacted.isRedacted(value)) {
235 return {
236 _tag: "Redacted",
237 value: Redacted.value(value),
238 };
239 }
240 // JSON-safe leaves compare by their serialized form (Duration/Date have
241 // toJSON).
242 if (Duration.isDuration(value) || value instanceof Date) return value;
243 // Bytes compare by content.
244 if (value instanceof Uint8Array) return { __bytes__: bytesToBase64(value) };
245 if (isPlainData(value)) {
246 const rebuilt = mapPlainData(value, ancestors, (child) =>
247 canonicalize(child, stripNullish, ancestors),
248 );
249 if (rebuilt === undefined || Array.isArray(rebuilt)) return rebuilt;
250 // Deterministic key order for the JSON.stringify comparison. Filtering
251 // after the walk is JSON-equivalent to filtering before it —
252 // undefined-valued keys are dropped by JSON.stringify either way.
253 return Object.fromEntries(
254 Object.entries(rebuilt as Record<string, unknown>)
255 .filter(([, nested]) => !stripNullish || nested != null)
256 .sort(([a], [b]) => a.localeCompare(b)),
257 );
258 }
259 if (value && typeof value === "object") {
260 // Non-plain instances (Effect, Layer, Context, SDK objects) never
261 // canonicalize — walking them is unsafe (cyclic on effect
262 // ≥4.0.0-beta.103 — #1082) and comparing them is meaningless.
263 return undefined;
264 }
265 return value;
266 };
267
268 /**
269 * Deterministic ordering for binding rows.
270 *
271 * Bindings are registered by concurrently-built layers (a Function/Worker's
272 * capability layers run real IO — bundling, fs — before calling `host.bind`),
273 * so the registration order of `stack.bindings[fqn]` is not stable across
274 * deploys. `diffBindings` itself is sid-keyed and order-insensitive, but the
275 * row order flows into provider `diff`/`reconcile` inputs and persisted
276 * state — any consumer that hashes or deep-compares the binding array (e.g.
277 * a metadata hash over bindings) would churn on registration-order flips.
278 * Sorting by `sid` at every boundary makes binding rows stable.
279 */
280 const bySid = (a: { sid: string }, b: { sid: string }): number =>
281 a.sid < b.sid ? -1 : a.sid > b.sid ? 1 : 0;
282
283 export const sortBindings = <B extends { sid: string }>(bindings: B[]): B[] =>
284 [...bindings].sort(bySid);
285
286 /**
287 * Collapse bindings that share the same `sid`, keeping the last occurrence,
288 * and return them in deterministic (sid-sorted) order.
289 *
290 * The same binding can be recorded more than once on a target resource — e.g.
291 * a KV namespace bound to both a Worker and a Workflow ends up pushed twice to
292 * `stack.bindings[fqn]`. `diffBindings` already collapses these implicitly via
293 * its `Map` keyed by `sid`, so the `reconcile` path never observes duplicates.
294 * Use this helper to give a provider's `diff` handler the same de-duplicated
295 * binding set, keeping plan-time hashing consistent with deploy-time.
296 */
297 export const dedupeBindings = <B extends ResourceBinding>(bindings: B[]): B[] =>
298 sortBindings(Array.from(new Map(bindings.map((b) => [b.sid, b])).values()));
299
300 export const diffBindings = (
301 oldBindings: ResourceBinding[],
302 newBindings: ResourceBinding[],
303 ): BindingNode[] => {
304 const oldMap = new Map(oldBindings.map((b) => [b.sid, b]));
305 const newMap = new Map(newBindings.map((b) => [b.sid, b]));
306 return sortBindings([
307 ...Array.from(oldMap)
308 .filter(([sid]) => !newMap.has(sid))
309 .map(([sid, old]) => ({
310 sid,
311 action: "delete" as const,
312 data: old.data,
313 })),
314 ...Array.from(newMap).map(([sid, binding]) => {
315 const old = oldMap.get(sid);
316 return {
317 sid,
318 action: (!old
319 ? "create"
320 : havePropsChanged(old.data, binding.data)
321 ? "update"
322 : "noop") as BindingNode["action"],
323 data: binding.data,
324 };
325 }),
326 ]);
327 };