Open History to see the last commit
1import type { Atom } from '@tanstack/store'
2
3export { createAtom } from '@tanstack/store'
4export type { Atom }
5
6function isPlainObject(value: unknown): value is Record<string, unknown> {
7 if (value === null || typeof value !== 'object' || Array.isArray(value)) {
8 return false
9 }
10 const proto: unknown = Object.getPrototypeOf(value)
11 return proto === Object.prototype || proto === null
12}
13
14/**
15 * Shallow copy, then freeze. Use for published snapshot fields that must not
16 * alias client internals. Only plain objects and arrays are copied. Any other
17 * object (Blob, Map, Date, class instance) is returned as it is, because a
18 * spread copy loses its prototype.
19 */
20export function cloneSnapshotValue<T>(value: T): T {
21 if (Array.isArray(value)) return Object.freeze([...value]) as T
22 return isPlainObject(value) ? (Object.freeze({ ...value }) as T) : value
23}
24
25/**
26 * Report an error thrown by a listener without stopping the caller. The
27 * browser's `reportError` reaches `window.onerror` and error trackers. Other
28 * runtimes log it.
29 */
30export function reportListenerError(error: unknown): void {
31 if (typeof globalThis.reportError === 'function') {
32 globalThis.reportError(error)
33 } else {
34 console.error(error)
35 }
36}
37
38/** Call every listener. One listener's throw does not skip the others. */
39export function notifyListeners<TArgs extends Array<unknown>>(
40 listeners: Iterable<(...args: TArgs) => void>,
41 ...args: TArgs
42): void {
43 for (const listener of listeners) {
44 try {
45 listener(...args)
46 } catch (error) {
47 reportListenerError(error)
48 }
49 }
50}
51
52/** Deep-freeze plain JSON. Class instances stay as they are. */
53function freezePlainData(value: unknown): unknown {
54 if (Array.isArray(value)) {
55 return Object.freeze(value.map(freezePlainData))
56 }
57 if (!isPlainObject(value)) return value
58 const copy: Record<string, unknown> = {}
59 for (const key of Object.keys(value)) {
60 copy[key] = freezePlainData(value[key])
61 }
62 return Object.freeze(copy)
63}
64
65/**
66 * Freeze a copy of one message part. Tool `input` / `output`, `source`,
67 * `approval`, tool-result `content`, and subagent transcripts are copies.
68 * A subagent `stop` function stays the live function.
69 */
70export function freezeSnapshotPart<TPart extends object>(
71 part: TPart,
72 cache: WeakMap<object, object> = new WeakMap(),
73): TPart {
74 const record = part as Record<string, unknown>
75 const copy: Record<string, unknown> = { ...record }
76 if (isPlainObject(record.source)) {
77 copy.source = Object.freeze({ ...record.source })
78 }
79 if (record.type === 'tool-call' && isPlainObject(record.approval)) {
80 copy.approval = Object.freeze({ ...record.approval })
81 }
82 if (record.type === 'tool-result' && Array.isArray(record.content)) {
83 copy.content = Object.freeze(
84 record.content.map((contentPart: unknown) =>
85 typeof contentPart === 'object' && contentPart !== null
86 ? freezeSnapshotPart(contentPart, cache)
87 : contentPart,
88 ),
89 )
90 }
91 if ('input' in record) copy.input = freezePlainData(record.input)
92 if ('output' in record) copy.output = freezePlainData(record.output)
93 if (record.type === 'subagent' && isPlainObject(record.subagent)) {
94 const sub = record.subagent
95 copy.subagent = Object.freeze(
96 Array.isArray(sub.messages)
97 ? {
98 ...sub,
99 messages: freezeSnapshotMessages(
100 cache,
101 sub.messages as Array<{ parts: ReadonlyArray<object> }>,
102 ),
103 }
104 : { ...sub },
105 )
106 }
107 return Object.freeze(copy) as TPart
108}
109
110function cached<T extends object>(
111 cache: WeakMap<object, object>,
112 value: T,
113 freeze: (value: T) => T,
114): T {
115 let frozen = cache.get(value) as T | undefined
116 if (!frozen) {
117 frozen = freeze(value)
118 cache.set(value, frozen)
119 }
120 return frozen
121}
122
123/**
124 * Freeze a copy of each message and its parts. The client replaces a message
125 * or a part object when it changes, so `cache` gives an unchanged message or
126 * part the same frozen copy. UI memo keys on message identity, and a streamed
127 * token copies only the part that changed.
128 */
129export function freezeSnapshotMessages<
130 TMessage extends { parts: ReadonlyArray<object> },
131>(
132 cache: WeakMap<object, object>,
133 messages: ReadonlyArray<TMessage>,
134): ReadonlyArray<TMessage> {
135 return Object.freeze(
136 messages.map((message) =>
137 cached(cache, message, () =>
138 Object.freeze({
139 ...message,
140 parts: Object.freeze(
141 message.parts.map((part) =>
142 cached(cache, part, () => freezeSnapshotPart(part, cache)),
143 ),
144 ),
145 }),
146 ),
147 ),
148 )
149}
150
151/**
152 * Merge a partial update into an object atom and freeze the result. Skips
153 * notify when every provided field is `Object.is`-equal to the current value.
154 */
155export function patchAtom<T extends object>(
156 atom: Atom<T>,
157 patch: Partial<T>,
158): void {
159 atom.set((prev) => {
160 let changed = false
161 const next = { ...prev }
162 for (const key of Object.keys(patch) as Array<keyof T>) {
163 if (Object.is(prev[key], patch[key])) continue
164 next[key] = patch[key] as T[keyof T]
165 changed = true
166 }
167 return changed ? Object.freeze(next) : prev
168 })
169}
170
171const MAX_LISTENER_REENTRY = 8
172
173/**
174 * Subscribe to an atom with the `() => void` unsubscribe that framework
175 * stores expect.
176 */
177export function subscribeAtom<T>(
178 atom: Pick<Atom<T>, 'get' | 'subscribe'>,
179 listener: () => void,
180): () => void {
181 const { unsubscribe } = atom.subscribe(() => {
182 // Store calls this inside an effect. A change made while `listener`
183 // runs (a Solid effect or Vue watcher that calls `stop()`) does not
184 // notify this subscriber again, so call it again until the value stays.
185 // One listener's throw must not skip the other subscribers, and must
186 // not escape into the setter that published this snapshot.
187 let seen: T
188 let spins = 0
189 do {
190 seen = atom.get()
191 try {
192 listener()
193 } catch (error) {
194 reportListenerError(error)
195 }
196 spins++
197 } while (atom.get() !== seen && spins < MAX_LISTENER_REENTRY)
198 })
199 return unsubscribe
200}