@sanity/sdk 2.16.0 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,311 @@
1
+ import {
2
+ type ListenEvent,
3
+ type MutationEvent,
4
+ type ReconnectEvent,
5
+ type WelcomeEvent,
6
+ } from '@sanity/client'
7
+ import {type SanityDocument} from '@sanity/types'
8
+ import {from, lastValueFrom, type Observable, Subject} from 'rxjs'
9
+ import {toArray} from 'rxjs/operators'
10
+ import {afterEach, describe, expect, it, vi} from 'vitest'
11
+
12
+ import {dedupeListenerEvents, groupTransactionEvents} from './listenerEventOperators'
13
+
14
+ function listenEventsOf(
15
+ ...events: ListenEvent<SanityDocument>[]
16
+ ): Observable<ListenEvent<SanityDocument>> {
17
+ return from(events)
18
+ }
19
+
20
+ function createMutationEvent({
21
+ transactionId,
22
+ documentId = 'doc1',
23
+ transactionCurrentEvent = 1,
24
+ transactionTotalEvents = 1,
25
+ }: {
26
+ transactionId: string
27
+ documentId?: string
28
+ transactionCurrentEvent?: number
29
+ transactionTotalEvents?: number
30
+ }): MutationEvent {
31
+ return {
32
+ type: 'mutation',
33
+ documentId,
34
+ eventId: `${transactionId}#${documentId}`,
35
+ identity: 'user',
36
+ mutations: [],
37
+ timestamp: new Date().toISOString(),
38
+ transactionId,
39
+ transactionCurrentEvent,
40
+ transactionTotalEvents,
41
+ transition: 'update',
42
+ visibility: 'query',
43
+ resultRev: transactionId,
44
+ }
45
+ }
46
+
47
+ const welcomeEvent: WelcomeEvent = {type: 'welcome', listenerName: 'listener'}
48
+ const reconnectEvent = {type: 'reconnect'} as ReconnectEvent
49
+
50
+ afterEach(() => {
51
+ vi.useRealTimers()
52
+ })
53
+
54
+ describe('dedupeListenerEvents', () => {
55
+ it('passes unique mutation events through', async () => {
56
+ const m1 = createMutationEvent({transactionId: 'txn1'})
57
+ const m2 = createMutationEvent({transactionId: 'txn2'})
58
+ const events = await lastValueFrom(
59
+ listenEventsOf(m1, m2).pipe(dedupeListenerEvents(), toArray()),
60
+ )
61
+ expect(events).toEqual([m1, m2])
62
+ })
63
+
64
+ it('drops replayed duplicates of the same transaction and document', async () => {
65
+ const m1 = createMutationEvent({transactionId: 'txn1'})
66
+ const replay = createMutationEvent({transactionId: 'txn1'})
67
+ const events = await lastValueFrom(
68
+ listenEventsOf(m1, replay).pipe(dedupeListenerEvents(), toArray()),
69
+ )
70
+ expect(events).toEqual([m1])
71
+ })
72
+
73
+ it('does not dedupe events of the same transaction for different documents', async () => {
74
+ const draft = createMutationEvent({transactionId: 'txn1', documentId: 'drafts.doc1'})
75
+ const published = createMutationEvent({transactionId: 'txn1', documentId: 'doc1'})
76
+ const events = await lastValueFrom(
77
+ listenEventsOf(draft, published).pipe(dedupeListenerEvents(), toArray()),
78
+ )
79
+ expect(events).toEqual([draft, published])
80
+ })
81
+
82
+ it('passes non-mutation events through untouched', async () => {
83
+ const events = await lastValueFrom(
84
+ listenEventsOf(welcomeEvent, reconnectEvent).pipe(dedupeListenerEvents(), toArray()),
85
+ )
86
+ expect(events).toEqual([welcomeEvent, reconnectEvent])
87
+ })
88
+
89
+ it('allows a key again after its TTL has passed', async () => {
90
+ vi.useFakeTimers()
91
+ const source = new Subject<ListenEvent<SanityDocument>>()
92
+ const received: ListenEvent<SanityDocument>[] = []
93
+ const subscription = source
94
+ .pipe(dedupeListenerEvents({ttl: 1000}))
95
+ .subscribe((e) => received.push(e))
96
+
97
+ source.next(createMutationEvent({transactionId: 'txn1'}))
98
+ source.next(createMutationEvent({transactionId: 'txn1'}))
99
+ expect(received).toHaveLength(1)
100
+
101
+ vi.advanceTimersByTime(1001)
102
+ source.next(createMutationEvent({transactionId: 'txn1'}))
103
+ expect(received).toHaveLength(2)
104
+
105
+ subscription.unsubscribe()
106
+ })
107
+
108
+ it('evicts the oldest entries when the cache exceeds maxEntries', async () => {
109
+ const source = new Subject<ListenEvent<SanityDocument>>()
110
+ const received: ListenEvent<SanityDocument>[] = []
111
+ const subscription = source
112
+ .pipe(dedupeListenerEvents({maxEntries: 2}))
113
+ .subscribe((e) => received.push(e))
114
+
115
+ source.next(createMutationEvent({transactionId: 'txn1'}))
116
+ source.next(createMutationEvent({transactionId: 'txn2'}))
117
+ source.next(createMutationEvent({transactionId: 'txn3'}))
118
+ // txn1 was evicted to make room, so a replay of it passes through again
119
+ source.next(createMutationEvent({transactionId: 'txn1'}))
120
+ expect(received).toHaveLength(4)
121
+
122
+ subscription.unsubscribe()
123
+ })
124
+ })
125
+
126
+ describe('groupTransactionEvents', () => {
127
+ it('passes single-event transactions through immediately', async () => {
128
+ const m1 = createMutationEvent({transactionId: 'txn1'})
129
+ const events = await lastValueFrom(listenEventsOf(m1).pipe(groupTransactionEvents(), toArray()))
130
+ expect(events).toEqual([m1])
131
+ })
132
+
133
+ it('holds multi-document transaction events until the transaction is complete', () => {
134
+ const source = new Subject<ListenEvent<SanityDocument>>()
135
+ const received: ListenEvent<SanityDocument>[] = []
136
+ const subscription = source.pipe(groupTransactionEvents()).subscribe((e) => received.push(e))
137
+
138
+ const draftEvent = createMutationEvent({
139
+ transactionId: 'txn-publish',
140
+ documentId: 'drafts.doc1',
141
+ transactionCurrentEvent: 1,
142
+ transactionTotalEvents: 2,
143
+ })
144
+ const publishedEvent = createMutationEvent({
145
+ transactionId: 'txn-publish',
146
+ documentId: 'doc1',
147
+ transactionCurrentEvent: 2,
148
+ transactionTotalEvents: 2,
149
+ })
150
+
151
+ source.next(draftEvent)
152
+ expect(received).toEqual([])
153
+
154
+ source.next(publishedEvent)
155
+ expect(received).toEqual([draftEvent, publishedEvent])
156
+
157
+ subscription.unsubscribe()
158
+ })
159
+
160
+ it('holds intervening events until the open transaction completes, then releases them after it', () => {
161
+ const source = new Subject<ListenEvent<SanityDocument>>()
162
+ const received: ListenEvent<SanityDocument>[] = []
163
+ const subscription = source.pipe(groupTransactionEvents()).subscribe((e) => received.push(e))
164
+
165
+ const draftEvent = createMutationEvent({
166
+ transactionId: 'txn-publish',
167
+ documentId: 'drafts.doc1',
168
+ transactionCurrentEvent: 1,
169
+ transactionTotalEvents: 2,
170
+ })
171
+ // an unrelated single-document mutation interleaved between the two
172
+ // halves of the publish (legacy listener pipeline behavior)
173
+ const intervening = createMutationEvent({transactionId: 'txn-other', documentId: 'doc9'})
174
+ const publishedEvent = createMutationEvent({
175
+ transactionId: 'txn-publish',
176
+ documentId: 'doc1',
177
+ transactionCurrentEvent: 2,
178
+ transactionTotalEvents: 2,
179
+ })
180
+
181
+ source.next(draftEvent)
182
+ source.next(intervening)
183
+ expect(received).toEqual([])
184
+
185
+ source.next(publishedEvent)
186
+ expect(received).toEqual([draftEvent, publishedEvent, intervening])
187
+
188
+ subscription.unsubscribe()
189
+ })
190
+
191
+ it('groups a held multi-document transaction after the open one completes', () => {
192
+ const source = new Subject<ListenEvent<SanityDocument>>()
193
+ const received: ListenEvent<SanityDocument>[] = []
194
+ const subscription = source.pipe(groupTransactionEvents()).subscribe((e) => received.push(e))
195
+
196
+ const a1 = createMutationEvent({
197
+ transactionId: 'txn-a',
198
+ documentId: 'drafts.doc1',
199
+ transactionTotalEvents: 2,
200
+ })
201
+ const b1 = createMutationEvent({
202
+ transactionId: 'txn-b',
203
+ documentId: 'drafts.doc2',
204
+ transactionTotalEvents: 2,
205
+ })
206
+ const b2 = createMutationEvent({
207
+ transactionId: 'txn-b',
208
+ documentId: 'doc2',
209
+ transactionTotalEvents: 2,
210
+ })
211
+ const a2 = createMutationEvent({
212
+ transactionId: 'txn-a',
213
+ documentId: 'doc1',
214
+ transactionTotalEvents: 2,
215
+ })
216
+
217
+ source.next(a1)
218
+ source.next(b1)
219
+ source.next(b2)
220
+ expect(received).toEqual([])
221
+
222
+ source.next(a2)
223
+ // txn-a completes and is emitted contiguously; the held txn-b events are
224
+ // re-processed and, being complete, emitted contiguously right after
225
+ expect(received).toEqual([a1, a2, b1, b2])
226
+
227
+ subscription.unsubscribe()
228
+ })
229
+
230
+ it('releases everything in arrival order when the held queue exceeds its cap', () => {
231
+ const source = new Subject<ListenEvent<SanityDocument>>()
232
+ const received: ListenEvent<SanityDocument>[] = []
233
+ const subscription = source
234
+ .pipe(groupTransactionEvents({maxHeldEvents: 2}))
235
+ .subscribe((e) => received.push(e))
236
+
237
+ const partial = createMutationEvent({
238
+ transactionId: 'txn-incomplete',
239
+ documentId: 'drafts.doc1',
240
+ transactionTotalEvents: 2,
241
+ })
242
+ const held1 = createMutationEvent({transactionId: 'txn-h1', documentId: 'doc8'})
243
+ const held2 = createMutationEvent({transactionId: 'txn-h2', documentId: 'doc9'})
244
+ const overflow = createMutationEvent({transactionId: 'txn-h3', documentId: 'doc10'})
245
+
246
+ source.next(partial)
247
+ source.next(held1)
248
+ source.next(held2)
249
+ expect(received).toEqual([])
250
+
251
+ source.next(overflow)
252
+ expect(received).toEqual([partial, held1, held2, overflow])
253
+
254
+ subscription.unsubscribe()
255
+ })
256
+
257
+ it('flushes buffered events before non-mutation events', () => {
258
+ const source = new Subject<ListenEvent<SanityDocument>>()
259
+ const received: ListenEvent<SanityDocument>[] = []
260
+ const subscription = source.pipe(groupTransactionEvents()).subscribe((e) => received.push(e))
261
+
262
+ const partial = createMutationEvent({
263
+ transactionId: 'txn-incomplete',
264
+ documentId: 'drafts.doc1',
265
+ transactionTotalEvents: 2,
266
+ })
267
+
268
+ source.next(partial)
269
+ source.next(reconnectEvent)
270
+ expect(received).toEqual([partial, reconnectEvent])
271
+
272
+ subscription.unsubscribe()
273
+ })
274
+
275
+ it('flushes an incomplete transaction and its held events after the deadline', () => {
276
+ vi.useFakeTimers()
277
+ const source = new Subject<ListenEvent<SanityDocument>>()
278
+ const received: ListenEvent<SanityDocument>[] = []
279
+ const subscription = source
280
+ .pipe(groupTransactionEvents({flushDeadline: 500}))
281
+ .subscribe((e) => received.push(e))
282
+
283
+ const partial = createMutationEvent({
284
+ transactionId: 'txn-incomplete',
285
+ documentId: 'drafts.doc1',
286
+ transactionTotalEvents: 2,
287
+ })
288
+ const heldBehind = createMutationEvent({transactionId: 'txn-held', documentId: 'doc9'})
289
+
290
+ source.next(partial)
291
+ source.next(heldBehind)
292
+ expect(received).toEqual([])
293
+
294
+ vi.advanceTimersByTime(500)
295
+ expect(received).toEqual([partial, heldBehind])
296
+
297
+ subscription.unsubscribe()
298
+ })
299
+
300
+ it('flushes buffered events on completion', async () => {
301
+ const partial = createMutationEvent({
302
+ transactionId: 'txn-incomplete',
303
+ documentId: 'drafts.doc1',
304
+ transactionTotalEvents: 2,
305
+ })
306
+ const events = await lastValueFrom(
307
+ listenEventsOf(partial).pipe(groupTransactionEvents(), toArray()),
308
+ )
309
+ expect(events).toEqual([partial])
310
+ })
311
+ })
@@ -0,0 +1,217 @@
1
+ import {type ListenEvent, type MutationEvent} from '@sanity/client'
2
+ import {type SanityDocument} from '@sanity/types'
3
+ import {defer, filter, type MonoTypeOperatorFunction, Observable} from 'rxjs'
4
+
5
+ import {setCleanupTimeout} from '../utils/setCleanupTimeout'
6
+
7
+ const DEDUPE_TTL = 120_000
8
+ const DEDUPE_MAX_ENTRIES = 1_000
9
+
10
+ /**
11
+ * How long to hold an incomplete multi-document transaction (and the events
12
+ * held behind it) before releasing everything anyway. Only reached when part
13
+ * of a transaction is lost.
14
+ */
15
+ const GROUP_FLUSH_DEADLINE = 30_000
16
+
17
+ /**
18
+ * How many intervening events to hold behind an incomplete multi-document
19
+ * transaction before giving up on grouping and releasing everything in
20
+ * arrival order.
21
+ */
22
+ const GROUP_MAX_HELD_EVENTS = 100
23
+
24
+ interface DedupeOptions {
25
+ ttl?: number
26
+ maxEntries?: number
27
+ }
28
+
29
+ /**
30
+ * Drops mutation events that have already been observed, keyed by
31
+ * `transactionId#documentId`. With `enableResume`, the listener replays
32
+ * missed events after a reconnect on an at-least-once basis, so the same
33
+ * event can be delivered twice. A duplicate would never chain onto the
34
+ * current base revision and would clog the sequencing buffer until it
35
+ * overflows into an `OutOfSyncError`.
36
+ *
37
+ * Seen keys expire after `ttl` milliseconds and the cache is capped at
38
+ * `maxEntries`, evicting the oldest entries first.
39
+ *
40
+ * @internal
41
+ */
42
+ export function dedupeListenerEvents(
43
+ options?: DedupeOptions,
44
+ ): MonoTypeOperatorFunction<ListenEvent<SanityDocument>> {
45
+ const {ttl = DEDUPE_TTL, maxEntries = DEDUPE_MAX_ENTRIES} = options ?? {}
46
+
47
+ return (source) =>
48
+ defer(() => {
49
+ // insertion-ordered map of dedupe key -> expiry timestamp
50
+ const seen = new Map<string, number>()
51
+
52
+ return source.pipe(
53
+ filter((event) => {
54
+ if (event.type !== 'mutation') return true
55
+
56
+ const key = `${event.transactionId}#${event.documentId}`
57
+ const now = Date.now()
58
+
59
+ const expiry = seen.get(key)
60
+ if (expiry !== undefined && expiry > now) return false
61
+
62
+ seen.delete(key)
63
+ seen.set(key, now + ttl)
64
+
65
+ for (const [existingKey, existingExpiry] of seen) {
66
+ if (seen.size <= maxEntries && existingExpiry > now) break
67
+ seen.delete(existingKey)
68
+ }
69
+
70
+ return true
71
+ }),
72
+ )
73
+ })
74
+ }
75
+
76
+ interface GroupTransactionEventsOptions {
77
+ flushDeadline?: number
78
+ maxHeldEvents?: number
79
+ }
80
+
81
+ /**
82
+ * Buffers the mutation events of multi-document transactions (e.g. a publish
83
+ * touching both the draft and the published document) until every event of
84
+ * the transaction has arrived, then emits them contiguously. Without this,
85
+ * a rebase can run between the two halves of a transaction and observe the
86
+ * dataset in a state that never existed on the server (draft deleted, but
87
+ * published not yet updated).
88
+ *
89
+ * The backend's streaming listener pipeline delivers a transaction's events
90
+ * contiguously and in order, but the legacy pipeline can interleave
91
+ * concurrent transactions. So while a multi-document transaction is
92
+ * incomplete, mutation events from other transactions are held (in arrival
93
+ * order) rather than emitted, and released right after the transaction
94
+ * completes; released events are re-processed so a held multi-document
95
+ * transaction is grouped too. Per-document `previousRev` sequencing
96
+ * downstream tolerates the reordering this introduces.
97
+ *
98
+ * Escape hatches so a lost event degrades to ungrouped delivery instead of
99
+ * stalling the stream: everything is released in arrival order when a
100
+ * non-mutation event (e.g. reconnect/welcome) arrives, when more than
101
+ * `maxHeldEvents` are held, or after `flushDeadline` milliseconds.
102
+ * Single-event transactions pass through untouched when nothing is buffered.
103
+ *
104
+ * @internal
105
+ */
106
+ export function groupTransactionEvents(
107
+ options?: GroupTransactionEventsOptions,
108
+ ): MonoTypeOperatorFunction<ListenEvent<SanityDocument>> {
109
+ const {flushDeadline = GROUP_FLUSH_DEADLINE, maxHeldEvents = GROUP_MAX_HELD_EVENTS} =
110
+ options ?? {}
111
+
112
+ return (source) =>
113
+ new Observable<ListenEvent<SanityDocument>>((subscriber) => {
114
+ interface OpenTransaction {
115
+ transactionId: string
116
+ events: MutationEvent[]
117
+ total: number
118
+ timer: ReturnType<typeof setTimeout>
119
+ }
120
+
121
+ let open: OpenTransaction | null = null
122
+ let held: MutationEvent[] = []
123
+
124
+ // emits the open transaction's events (complete or not) without
125
+ // releasing the held queue; callers decide what happens to `held`
126
+ const closeOpen = () => {
127
+ if (!open) return
128
+ clearTimeout(open.timer)
129
+ const {events} = open
130
+ open = null
131
+ for (const event of events) subscriber.next(event)
132
+ }
133
+
134
+ // re-processes the held queue so a held multi-document transaction
135
+ // gets grouped in turn. processing may open a new transaction and top
136
+ // up a new held queue; each drain only touches its own snapshot, so
137
+ // this terminates
138
+ const releaseHeld = () => {
139
+ const queue = held
140
+ held = []
141
+ for (const event of queue) processEvent(event)
142
+ }
143
+
144
+ const releaseEverything = () => {
145
+ closeOpen()
146
+ const queue = held
147
+ held = []
148
+ for (const event of queue) subscriber.next(event)
149
+ }
150
+
151
+ const processEvent = (event: ListenEvent<SanityDocument>) => {
152
+ if (event.type !== 'mutation') {
153
+ // connection-level events (welcome/welcomeback/reset/reconnect)
154
+ // reset the world downstream; release everything before them
155
+ releaseEverything()
156
+ subscriber.next(event)
157
+ return
158
+ }
159
+
160
+ const isMultiDocument = (event.transactionTotalEvents ?? 0) > 1
161
+
162
+ if (!open) {
163
+ if (!isMultiDocument) {
164
+ subscriber.next(event)
165
+ return
166
+ }
167
+ // isMultiDocument guarantees total >= 2, so a freshly opened
168
+ // transaction is always incomplete; completion is checked when
169
+ // subsequent events of the same transaction arrive below
170
+ open = {
171
+ transactionId: event.transactionId,
172
+ events: [event],
173
+ total: event.transactionTotalEvents,
174
+ timer: setCleanupTimeout(() => {
175
+ closeOpen()
176
+ releaseHeld()
177
+ }, flushDeadline),
178
+ }
179
+ return
180
+ }
181
+
182
+ if (event.transactionId === open.transactionId) {
183
+ open.events.push(event)
184
+ if (open.events.length >= open.total) {
185
+ closeOpen()
186
+ releaseHeld()
187
+ }
188
+ return
189
+ }
190
+
191
+ // an event from another transaction while one is incomplete: hold it
192
+ // (legacy listener pipeline interleaving) instead of giving up on the
193
+ // open transaction
194
+ held.push(event)
195
+ if (held.length > maxHeldEvents) releaseEverything()
196
+ }
197
+
198
+ const subscription = source.subscribe({
199
+ next: processEvent,
200
+ error: (error) => {
201
+ releaseEverything()
202
+ subscriber.error(error)
203
+ },
204
+ complete: () => {
205
+ releaseEverything()
206
+ subscriber.complete()
207
+ },
208
+ })
209
+
210
+ return () => {
211
+ if (open) clearTimeout(open.timer)
212
+ open = null
213
+ held = []
214
+ subscription.unsubscribe()
215
+ }
216
+ })
217
+ }
@@ -274,10 +274,51 @@ describe('set', () => {
274
274
  expect(output).toEqual({a: 1, nonexistent: {path: 999}})
275
275
  })
276
276
 
277
- it('creates an item from a key constraint if the key is not present', () => {
277
+ // Content Lake never creates array items when setting: a keyed or indexed
278
+ // segment that does not resolve is a silent no-op server-side. The applier
279
+ // used to append a degenerate item (without the key, even), which
280
+ // fabricated array items locally that would never exist on the server.
281
+ it('does not create an item from a key constraint if the key is not present', () => {
278
282
  const input = {items: [{_key: 'item1'}]}
279
283
  const output = set(input, {'items[_key=="item2"]': {_key: 'item2'}})
280
- expect(output).toEqual({items: [{_key: 'item1'}, {_key: 'item2'}]})
284
+ expect(output).toEqual({items: [{_key: 'item1'}]})
285
+ })
286
+
287
+ it('does not create an item when setting a property under an unresolvable key constraint', () => {
288
+ const input = {
289
+ blocks: [
290
+ {
291
+ _key: 'b1',
292
+ children: [{_key: 's1', _type: 'span', text: 'hello', marks: []}],
293
+ },
294
+ ],
295
+ }
296
+ const output = set(input, {'blocks[_key=="b1"].children[_key=="missing"].marks': ['mark1']})
297
+ expect(output).toEqual(input)
298
+ })
299
+
300
+ it('does not create an item when setting through an out-of-bounds index', () => {
301
+ const input = {items: [{_key: 'item1', value: 1}]}
302
+ const output = set(input, {'items[3].value': 99})
303
+ expect(output).toEqual(input)
304
+ })
305
+
306
+ it('still sets a missing property on an existing keyed item', () => {
307
+ const input = {items: [{_key: 'item1'}]}
308
+ const output = set(input, {'items[_key=="item1"].value': 42})
309
+ expect(output).toEqual({items: [{_key: 'item1', value: 42}]})
310
+ })
311
+
312
+ it('does not create anything when an array-addressing segment targets a non-array', () => {
313
+ const input = {items: {nested: true}}
314
+ const output = set(input, {'items[_key=="item1"].value': 42})
315
+ expect(output).toEqual(input)
316
+ })
317
+
318
+ it('does not create an item when setting through a negative out-of-bounds index', () => {
319
+ const input = {items: [{_key: 'item1', value: 1}]}
320
+ const output = set(input, {'items[-5].value': 99})
321
+ expect(output).toEqual(input)
281
322
  })
282
323
  })
283
324
 
@@ -299,6 +340,12 @@ describe('setIfMissing', () => {
299
340
  const output = setIfMissing(input, {'a.b': 42})
300
341
  expect(output).toEqual({a: {b: 1}})
301
342
  })
343
+
344
+ it('does not create an item under an unresolvable key constraint', () => {
345
+ const input = {items: [{_key: 'item1'}]}
346
+ const output = setIfMissing(input, {'items[_key=="missing"].value': 1})
347
+ expect(output).toEqual(input)
348
+ })
302
349
  })
303
350
 
304
351
  describe('unset', () => {
@@ -175,6 +175,54 @@ export const ensureArrayKeysDeep = memoize(<R>(input: R): R => {
175
175
  return Object.fromEntries(entries) as R
176
176
  })
177
177
 
178
+ /**
179
+ * Whether every array-addressing segment (keyed `[_key=="…"]` or numeric
180
+ * index) in the given match path resolves to an existing array item.
181
+ *
182
+ * This mirrors Content Lake, which auto-creates missing *object* properties
183
+ * when setting but never creates *array items*:
184
+ *
185
+ * ```js
186
+ * // object properties are created, even nested ones:
187
+ * set({}, {'meta.author.name': 'Ada'})
188
+ * // -> {meta: {author: {name: 'Ada'}}} (applies)
189
+ *
190
+ * // array items are not:
191
+ * set({items: [{_key: 'a'}]}, {'items[_key=="b"].title': 'x'})
192
+ * // -> {items: [{_key: 'a'}]} (no-op)
193
+ * ```
194
+ *
195
+ * Without this filter, the second example fabricated a degenerate item
196
+ * (`{title: 'x'}`, no `_key`) that would never exist on the server, which
197
+ * is how concurrent Portable Text edits grew phantom span-less children.
198
+ */
199
+ function resolvesArraySegments(input: unknown, path: SingleValuePath): boolean {
200
+ let current: unknown = input
201
+ for (const segment of path) {
202
+ if (typeof segment === 'string') {
203
+ // missing object properties (nested ones included) are created
204
+ // server-side, so a string segment may descend into undefined
205
+ current =
206
+ typeof current === 'object' && current !== null && !Array.isArray(current)
207
+ ? (current as Record<string, unknown>)[segment]
208
+ : undefined
209
+ continue
210
+ }
211
+ // keyed and numeric segments address array items, which are never created
212
+ if (!Array.isArray(current)) return false
213
+ if (isKeySegment(segment)) {
214
+ const index = getIndexForKey(current, segment._key)
215
+ if (index === undefined) return false
216
+ current = current[index]
217
+ } else {
218
+ const index = segment < 0 ? current.length + segment : segment
219
+ if (!(index in current)) return false
220
+ current = current[index]
221
+ }
222
+ }
223
+ return true
224
+ }
225
+
178
226
  /**
179
227
  * Given an input object and a record of path expressions to values, this
180
228
  * function will set each match with the given value.
@@ -198,6 +246,7 @@ export function set(input: unknown, pathExpressionValues: Record<string, unknown
198
246
  replacementValue,
199
247
  })),
200
248
  )
249
+ .filter(({path}) => resolvesArraySegments(input, path))
201
250
  .reduce((acc, {path, replacementValue}) => setDeep(acc, path, replacementValue), input)
202
251
 
203
252
  return ensureArrayKeysDeep(result)
@@ -231,6 +280,7 @@ export function setIfMissing(
231
280
  }))
232
281
  })
233
282
  .filter((matchEntry) => matchEntry.value === null || matchEntry.value === undefined)
283
+ .filter(({path}) => resolvesArraySegments(input, path))
234
284
  .reduce((acc, {path, replacementValue}) => setDeep(acc, path, replacementValue), input)
235
285
 
236
286
  return ensureArrayKeysDeep(result)