@sanity/sdk 2.17.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,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)
@@ -13,6 +13,7 @@ import {
13
13
  checkGrant,
14
14
  createMutationApplier,
15
15
  PermissionActionError,
16
+ preserveNumericOperations,
16
17
  } from './shared'
17
18
 
18
19
  export function handleEdit(
@@ -100,10 +101,16 @@ export function handleEdit(
100
101
  // when the caller asked us to preserve their operations, forward their
101
102
  // patches verbatim instead of re-deriving them from a snapshot diff. this
102
103
  // keeps keyed array operations addressable so concurrent edits from other
103
- // clients interleave instead of being overwritten
104
+ // clients interleave instead of being overwritten. otherwise, diff the
105
+ // snapshots but swap back any `inc`/`dec` the diff collapsed into a `set`,
106
+ // so concurrent increments accumulate instead of last-write-winning
104
107
  const patches = action.preserveOperations
105
108
  ? (action.patches ?? [])
106
- : diffValue(baseBefore, baseAfter)
109
+ : preserveNumericOperations(
110
+ baseBefore,
111
+ action.patches,
112
+ diffValue(baseBefore, baseAfter) as PatchOperations[],
113
+ )
107
114
 
108
115
  const workingMutations: Mutation[] = []
109
116
  if (!isReleasePerspective(action.perspective) && !working[draftId] && working[publishedId]) {
@@ -1,4 +1,5 @@
1
1
  import {diffValue} from '@sanity/diff-patch'
2
+ import {jsonMatch, stringifyPath} from '@sanity/json-match'
2
3
  import {type Mutation, type PatchOperations, type SanityDocument} from '@sanity/types'
3
4
  import {evaluateSync, type ExprNode} from 'groq-js'
4
5
 
@@ -92,6 +93,111 @@ export function createMutationApplier(options: {
92
93
  }
93
94
  }
94
95
 
96
+ /**
97
+ * Re-applies the operational intent of user-supplied `inc`/`dec` patches to a
98
+ * set of snapshot-diffed patches.
99
+ *
100
+ * The outgoing patches sent to Content Lake are re-derived by diffing the
101
+ * base document before and after the user's patches were applied. That diff
102
+ * collapses an `inc` into a `set` of the resulting number, which turns
103
+ * concurrent increments from different clients into last-write-wins. This
104
+ * helper finds diffed `set` operations that are exactly explained by the
105
+ * user's `inc`/`dec` operations and swaps them back, so the server applies
106
+ * the increment against whatever value is current at commit time.
107
+ *
108
+ * A `set` is only swapped when its value equals the base value plus the
109
+ * accumulated user deltas for that exact path; anything else (e.g. an `inc`
110
+ * combined with a `set` of the same field) keeps the diffed `set`.
111
+ *
112
+ * Content Lake fails the whole transaction when `inc`/`dec` targets a missing
113
+ * path (unlike `set`, which always succeeds). To avoid turning a concurrent
114
+ * field removal into a transaction revert, the emitted patch seeds the target
115
+ * with a `setIfMissing` of the base value; the server executes `setIfMissing`
116
+ * before `inc`/`dec` within a single patch, so a concurrently removed field
117
+ * degrades to the same result the diffed `set` would have produced. A path
118
+ * into a concurrently removed keyed array item can still fail the
119
+ * transaction (`setIfMissing` cannot create array items); the transaction is
120
+ * then reverted and reported, which is preferable to silently resurrecting
121
+ * the item.
122
+ */
123
+ export function preserveNumericOperations(
124
+ baseBefore: SanityDocument | null | undefined,
125
+ userPatches: PatchOperations[] | undefined,
126
+ diffedPatches: PatchOperations[],
127
+ ): PatchOperations[] {
128
+ if (!baseBefore || !userPatches?.length) return diffedPatches
129
+
130
+ // accumulate the user's inc/dec deltas per concrete (stringified) path,
131
+ // tracking the expected final value by replaying the additions in order
132
+ const targets = new Map<string, {baseValue: number; expectedValue: number; delta: number}>()
133
+ for (const patch of userPatches) {
134
+ for (const [op, sign] of [
135
+ ['inc', 1],
136
+ ['dec', -1],
137
+ ] as const) {
138
+ const record = patch[op]
139
+ if (!record) continue
140
+ for (const [pathExpression, amount] of Object.entries(record)) {
141
+ if (typeof amount !== 'number') continue
142
+ for (const match of jsonMatch(baseBefore, pathExpression)) {
143
+ const path = stringifyPath(match.path)
144
+ const existing = targets.get(path)
145
+ if (existing) {
146
+ existing.expectedValue += sign * amount
147
+ existing.delta += sign * amount
148
+ } else if (typeof match.value === 'number') {
149
+ targets.set(path, {
150
+ baseValue: match.value,
151
+ expectedValue: match.value + sign * amount,
152
+ delta: sign * amount,
153
+ })
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+ if (!targets.size) return diffedPatches
160
+
161
+ const preserved = new Map<string, {delta: number; baseValue: number}>()
162
+ const next = diffedPatches.flatMap((patch) => {
163
+ if (!patch.set) return [patch]
164
+
165
+ const keptSet: Record<string, unknown> = {}
166
+ for (const [path, value] of Object.entries(patch.set)) {
167
+ const target = targets.get(path)
168
+ if (target && typeof value === 'number' && value === target.expectedValue) {
169
+ preserved.set(path, {delta: target.delta, baseValue: target.baseValue})
170
+ } else {
171
+ keptSet[path] = value
172
+ }
173
+ }
174
+
175
+ if (Object.keys(keptSet).length === Object.keys(patch.set).length) return [patch]
176
+ const {set: _set, ...rest} = patch
177
+ const withKept = Object.keys(keptSet).length ? {...rest, set: keptSet} : rest
178
+ return Object.keys(withKept).length ? [withKept] : []
179
+ })
180
+
181
+ if (!preserved.size) return next
182
+
183
+ const setIfMissing: Record<string, unknown> = {}
184
+ const inc: Record<string, number> = {}
185
+ const dec: Record<string, number> = {}
186
+ for (const [path, {delta, baseValue}] of preserved) {
187
+ setIfMissing[path] = baseValue
188
+ if (delta >= 0) inc[path] = delta
189
+ else dec[path] = -delta
190
+ }
191
+ return [
192
+ ...next,
193
+ {
194
+ setIfMissing,
195
+ ...(Object.keys(inc).length && {inc}),
196
+ ...(Object.keys(dec).length && {dec}),
197
+ },
198
+ ]
199
+ }
200
+
95
201
  interface ApplySingleDocPatchOptions {
96
202
  base: DocumentSet
97
203
  working: DocumentSet
@@ -181,7 +287,11 @@ export function applySingleDocPatch({
181
287
  const baseAfter = base[documentId]
182
288
  const diffedPatches = preserveOperations
183
289
  ? (patches as PatchOperations[])
184
- : (diffValue(baseBefore, baseAfter) as PatchOperations[])
290
+ : preserveNumericOperations(
291
+ baseBefore,
292
+ patches,
293
+ diffValue(baseBefore, baseAfter) as PatchOperations[],
294
+ )
185
295
 
186
296
  const workingBefore = working[documentId] as SanityDocument
187
297
  if (!checkGrant(grants.update, workingBefore, identity)) {