@get-bb/plugin-sdk 0.6.65 → 0.6.68

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.
@@ -94,24 +94,454 @@ import {
94
94
  useQueryClient,
95
95
  useMutation,
96
96
  useMutationState,
97
- replaceEqualDeep as replaceEqualDeep2
97
+ replaceEqualDeep as replaceEqualDeep3
98
98
  } from "@tanstack/react-query";
99
99
 
100
- // ../query-tags/src/optimistic.ts
100
+ // ../query-tags/src/clock.ts
101
+ var order = 0;
102
+ function tick() {
103
+ return ++order;
104
+ }
105
+
106
+ // ../query-tags/src/keyed-store.ts
101
107
  import {
102
108
  notifyManager,
103
109
  replaceEqualDeep
104
110
  } from "@tanstack/react-query";
111
+ var KeyedCollection = class {
112
+ constructor(name) {
113
+ this.name = name;
114
+ }
115
+ name;
116
+ };
117
+ var stores = /* @__PURE__ */ new WeakMap();
118
+ function isObject(value) {
119
+ return typeof value === "object" && value !== null;
120
+ }
121
+ function collectionOf(store, token) {
122
+ let collection = store.collections.get(token);
123
+ if (collection === void 0) {
124
+ collection = {
125
+ base: /* @__PURE__ */ new Map(),
126
+ visible: /* @__PURE__ */ new Map(),
127
+ layers: [],
128
+ acknowledgedAt: /* @__PURE__ */ new Map(),
129
+ views: /* @__PURE__ */ new Map()
130
+ };
131
+ store.collections.set(token, collection);
132
+ }
133
+ return collection;
134
+ }
135
+ function readEntity(collection, id) {
136
+ const cached = collection.visible.get(id);
137
+ if (cached !== void 0) return cached;
138
+ let entity = collection.base.get(id);
139
+ if (entity === void 0) return void 0;
140
+ for (const layer of collection.layers)
141
+ if (layer.ids.has(id)) entity = layer.apply(entity, id);
142
+ collection.visible.set(id, entity);
143
+ return entity;
144
+ }
145
+ function changed(store, collection, ids) {
146
+ const dirty = new Set(ids);
147
+ for (const id of dirty) collection.visible.delete(id);
148
+ if (store.batching > 0) {
149
+ const pending = store.dirtyIds.get(collection) ?? /* @__PURE__ */ new Set();
150
+ for (const id of dirty) pending.add(id);
151
+ store.dirtyIds.set(collection, pending);
152
+ return;
153
+ }
154
+ const views = /* @__PURE__ */ new Map();
155
+ for (const id of dirty)
156
+ for (const view of collection.views.get(id) ?? []) {
157
+ const viewIds = views.get(view) ?? /* @__PURE__ */ new Set();
158
+ viewIds.add(id);
159
+ views.set(view, viewIds);
160
+ }
161
+ notifyManager.batch(() => {
162
+ for (const [view, viewIds] of views) rematerialize(store, view, viewIds);
163
+ });
164
+ }
165
+ function writeBase(store, collection, id, update) {
166
+ const current = collection.base.get(id);
167
+ const next = update(current);
168
+ if (next === void 0 || next === current) return;
169
+ collection.base.set(id, next);
170
+ changed(store, collection, [id]);
171
+ }
172
+ function ingest(store, skeleton, id, item, readStart) {
173
+ const fresh = readStart > (skeleton.collection.acknowledgedAt.get(id) ?? -1);
174
+ writeBase(
175
+ store,
176
+ skeleton.collection,
177
+ id,
178
+ (current) => skeleton.view.read(item, current, fresh)
179
+ );
180
+ }
181
+ function materializeItem(store, view, item, entity) {
182
+ if (!isObject(item) || !isObject(entity)) return view.render(item, entity);
183
+ let byEntity = store.rows.get(item);
184
+ if (byEntity === void 0) {
185
+ byEntity = /* @__PURE__ */ new WeakMap();
186
+ store.rows.set(item, byEntity);
187
+ }
188
+ const cached = byEntity.get(entity);
189
+ if (cached !== void 0) return cached;
190
+ const row = view.render(item, entity);
191
+ byEntity.set(entity, row);
192
+ return row;
193
+ }
194
+ function rematerialize(store, query, dirty) {
195
+ const skeleton = store.skeletons.get(query);
196
+ if (skeleton === void 0) return;
197
+ const { view, collection } = skeleton;
198
+ const previous = store.materialized.get(query);
199
+ const incremental = dirty !== void 0 && previous !== void 0;
200
+ const slotKeys = /* @__PURE__ */ new Set();
201
+ if (incremental) {
202
+ for (const id of dirty)
203
+ for (const slot of skeleton.slotsById.get(id) ?? []) slotKeys.add(slot);
204
+ } else for (const slot of skeleton.slots.keys()) slotKeys.add(slot);
205
+ if (slotKeys.size === 0) return;
206
+ const items = /* @__PURE__ */ new Map();
207
+ const materialized = new Map(previous);
208
+ for (const slot of slotKeys) {
209
+ const prior = previous?.get(slot);
210
+ const visible = /* @__PURE__ */ new Map();
211
+ const rows = [];
212
+ for (const entry of skeleton.slots.get(slot) ?? []) {
213
+ if (entry.id === null) {
214
+ rows.push(entry.item);
215
+ continue;
216
+ }
217
+ const entity = readEntity(collection, entry.id);
218
+ if (entity !== void 0 && view.shows !== void 0 && !view.shows(entity, query.queryKey))
219
+ continue;
220
+ const previousRow = incremental ? prior?.get(entry.id) : void 0;
221
+ const row = previousRow !== void 0 && dirty?.has(entry.id) === false ? previousRow : replaceEqualDeep(
222
+ previousRow,
223
+ entity === void 0 ? entry.item : materializeItem(store, view, entry.item, entity)
224
+ );
225
+ visible.set(entry.id, row);
226
+ rows.push(row);
227
+ }
228
+ const unchanged = prior !== void 0 && prior.size === rows.length && [...prior.values()].every((row, index) => row === rows[index]);
229
+ if (incremental && unchanged) continue;
230
+ items.set(slot, rows);
231
+ materialized.set(slot, visible);
232
+ }
233
+ if (items.size === 0) return;
234
+ let next = view.rebuild(
235
+ incremental ? query.state.data : skeleton.data,
236
+ items
237
+ );
238
+ if (!incremental) {
239
+ next = replaceEqualDeep(query.state.data, next);
240
+ for (const slot of view.slots(next) ?? []) {
241
+ const visible = /* @__PURE__ */ new Map();
242
+ for (const item of slot.items) {
243
+ const id = view.keyOf(item);
244
+ if (id !== void 0) visible.set(id, item);
245
+ }
246
+ materialized.set(slot.key, visible);
247
+ }
248
+ }
249
+ store.materialized.set(query, materialized);
250
+ if (next !== query.state.data) query.setState({ data: next });
251
+ }
252
+ function skeletonIds(skeleton) {
253
+ const ids = /* @__PURE__ */ new Set();
254
+ for (const entries of skeleton?.slots.values() ?? [])
255
+ for (const { id } of entries) if (id !== null) ids.add(id);
256
+ return ids;
257
+ }
258
+ function setSkeleton(store, query, skeleton) {
259
+ const previous = store.skeletons.get(query);
260
+ const previousIds = skeletonIds(previous);
261
+ const nextIds = skeletonIds(skeleton);
262
+ if (skeleton === void 0) {
263
+ store.skeletons.delete(query);
264
+ store.materialized.delete(query);
265
+ } else store.skeletons.set(query, skeleton);
266
+ const collection = skeleton?.collection ?? previous?.collection;
267
+ if (collection === void 0) return;
268
+ for (const id of nextIds) {
269
+ let views = collection.views.get(id);
270
+ if (views === void 0) {
271
+ views = /* @__PURE__ */ new Set();
272
+ collection.views.set(id, views);
273
+ }
274
+ views.add(query);
275
+ }
276
+ for (const id of previousIds) {
277
+ if (nextIds.has(id)) continue;
278
+ const views = collection.views.get(id);
279
+ views?.delete(query);
280
+ if (views === void 0 || views.size === 0) {
281
+ collection.views.delete(id);
282
+ collection.base.delete(id);
283
+ collection.visible.delete(id);
284
+ }
285
+ }
286
+ }
287
+ function priorItem(materialized, slot, id) {
288
+ const same = materialized?.get(slot)?.get(id);
289
+ if (same !== void 0) return same;
290
+ for (const visible of materialized?.values() ?? []) {
291
+ const item = visible.get(id);
292
+ if (item !== void 0) return item;
293
+ }
294
+ return void 0;
295
+ }
296
+ function isHidden(entry, visible) {
297
+ return entry.id !== null && !visible.has(entry.id);
298
+ }
299
+ function keepHiddenEntries(previous, next, visible) {
300
+ if (!previous.some((entry) => isHidden(entry, visible))) return next;
301
+ const result = [...next];
302
+ let insertAt = result.length;
303
+ for (let index = previous.length - 1; index >= 0; index--) {
304
+ const entry = previous[index];
305
+ const existing = entry.id === null ? -1 : result.findIndex(({ id }) => id === entry.id);
306
+ if (existing >= 0) insertAt = existing;
307
+ else if (isHidden(entry, visible)) result.splice(insertAt, 0, entry);
308
+ }
309
+ return result;
310
+ }
311
+ function keptInsertions(store, query, slot, readStart) {
312
+ const insertions = (store.insertions.get(query) ?? []).filter(
313
+ (insertion) => insertion.at > readStart
314
+ );
315
+ store.insertions.set(query, insertions);
316
+ return insertions.filter((insertion) => insertion.slot === slot);
317
+ }
318
+ function batch(store, run) {
319
+ store.batching++;
320
+ try {
321
+ notifyManager.batch(run);
322
+ } finally {
323
+ store.batching--;
324
+ }
325
+ if (store.batching > 0) return;
326
+ const full = new Set(store.dirtyViews);
327
+ const partial = /* @__PURE__ */ new Map();
328
+ for (const [collection, ids] of store.dirtyIds)
329
+ for (const id of ids)
330
+ for (const view of collection.views.get(id) ?? []) {
331
+ if (full.has(view)) continue;
332
+ const viewIds = partial.get(view) ?? /* @__PURE__ */ new Set();
333
+ viewIds.add(id);
334
+ partial.set(view, viewIds);
335
+ }
336
+ store.dirtyIds.clear();
337
+ store.dirtyViews.clear();
338
+ notifyManager.batch(() => {
339
+ for (const view of full) rematerialize(store, view);
340
+ for (const [view, ids] of partial) rematerialize(store, view, ids);
341
+ });
342
+ }
343
+ function onViewWritten(store, query, view, manual) {
344
+ const data = query.state.data;
345
+ const slots = data === void 0 ? void 0 : view.slots(data);
346
+ if (slots === void 0) {
347
+ setSkeleton(store, query, void 0);
348
+ return;
349
+ }
350
+ const collection = collectionOf(store, view.collection);
351
+ const target = { view, collection };
352
+ const previous = store.skeletons.get(query);
353
+ const materialized = manual ? store.materialized.get(query) : void 0;
354
+ const readStart = manual ? -1 : store.fetchStartedAt.get(query) ?? 0;
355
+ const receipt = manual ? void 0 : store.receipts.get(query);
356
+ if (receipt !== void 0) store.receipts.delete(query);
357
+ batch(store, () => {
358
+ const nextSlots = /* @__PURE__ */ new Map();
359
+ const slotsById = /* @__PURE__ */ new Map();
360
+ for (const slot of slots) {
361
+ const entries = [];
362
+ for (const item of slot.items) {
363
+ const id = view.keyOf(item);
364
+ entries.push({ id: id ?? null, item });
365
+ if (id === void 0) continue;
366
+ const prior = priorItem(materialized, slot.key, id);
367
+ if (prior !== void 0) {
368
+ if (prior !== item)
369
+ writeBase(
370
+ store,
371
+ collection,
372
+ id,
373
+ (current) => current === void 0 ? current : view.write(item, prior, current)
374
+ );
375
+ continue;
376
+ }
377
+ const start = receipt === void 0 ? readStart : receipt.get(id);
378
+ if (start !== void 0) ingest(store, target, id, item, start);
379
+ else if (!collection.base.has(id))
380
+ ingest(store, target, id, item, readStart);
381
+ }
382
+ const previousEntries = previous?.slots.get(slot.key);
383
+ const visible = materialized?.get(slot.key);
384
+ const kept = previousEntries !== void 0 && visible !== void 0 ? keepHiddenEntries(previousEntries, entries, visible) : entries;
385
+ if (!manual) {
386
+ for (const insertion of keptInsertions(
387
+ store,
388
+ query,
389
+ slot.key,
390
+ readStart
391
+ ))
392
+ if (!kept.some(({ id }) => id === insertion.entry.id))
393
+ kept.push(insertion.entry);
394
+ }
395
+ nextSlots.set(slot.key, kept);
396
+ for (const { id } of kept) {
397
+ if (id === null) continue;
398
+ const slotKeys = slotsById.get(id) ?? /* @__PURE__ */ new Set();
399
+ slotKeys.add(slot.key);
400
+ slotsById.set(id, slotKeys);
401
+ }
402
+ }
403
+ setSkeleton(store, query, {
404
+ view,
405
+ collection,
406
+ data,
407
+ slots: nextSlots,
408
+ slotsById
409
+ });
410
+ store.dirtyViews.add(query);
411
+ });
412
+ }
413
+ function viewOf(store, query) {
414
+ const exact = store.exact.get(query.queryHash);
415
+ if (exact !== void 0) return exact;
416
+ for (const resolve of store.resolvers) {
417
+ const view = resolve(query.queryKey);
418
+ if (view !== void 0) return view;
419
+ }
420
+ return void 0;
421
+ }
422
+ function storeOf(client) {
423
+ const existing = stores.get(client);
424
+ if (existing !== void 0) return existing;
425
+ const store = {
426
+ client,
427
+ collections: /* @__PURE__ */ new Map(),
428
+ resolvers: [],
429
+ exact: /* @__PURE__ */ new Map(),
430
+ skeletons: /* @__PURE__ */ new Map(),
431
+ insertions: /* @__PURE__ */ new WeakMap(),
432
+ materialized: /* @__PURE__ */ new WeakMap(),
433
+ fetchStartedAt: /* @__PURE__ */ new WeakMap(),
434
+ receipts: /* @__PURE__ */ new WeakMap(),
435
+ rows: /* @__PURE__ */ new WeakMap(),
436
+ batching: 0,
437
+ dirtyIds: /* @__PURE__ */ new Map(),
438
+ dirtyViews: /* @__PURE__ */ new Set()
439
+ };
440
+ stores.set(client, store);
441
+ client.getQueryCache().subscribe((event) => {
442
+ const { query } = event;
443
+ if (event.type === "removed") {
444
+ if (store.skeletons.has(query)) setSkeleton(store, query, void 0);
445
+ return;
446
+ }
447
+ if (event.type !== "updated") return;
448
+ const { type } = event.action;
449
+ if (type !== "fetch" && type !== "success") return;
450
+ const view = viewOf(store, query);
451
+ if (view === void 0) return;
452
+ if (event.action.type === "fetch") {
453
+ store.fetchStartedAt.set(query, tick());
454
+ return;
455
+ }
456
+ if (event.action.type === "success")
457
+ onViewWritten(store, query, view, event.action.manual === true);
458
+ });
459
+ return store;
460
+ }
461
+ function adopt(store, matches) {
462
+ for (const query of store.client.getQueryCache().getAll()) {
463
+ const view = matches(query);
464
+ if (view !== void 0 && query.state.data !== void 0)
465
+ onViewWritten(store, query, view, true);
466
+ }
467
+ }
468
+ function registerKeyedView(client, queryKey, view) {
469
+ const store = storeOf(client);
470
+ const { queryHash } = client.defaultQueryOptions({ queryKey });
471
+ if (store.exact.has(queryHash)) return;
472
+ store.exact.set(queryHash, view);
473
+ adopt(store, (query) => query.queryHash === queryHash ? view : void 0);
474
+ }
475
+ function recordKeyedRead(client, queryKey, startedAt) {
476
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
477
+ if (query !== void 0) storeOf(client).receipts.set(query, startedAt);
478
+ }
479
+ function bakeSettledLayers(collection) {
480
+ const baked = /* @__PURE__ */ new Set();
481
+ const pending = /* @__PURE__ */ new Set();
482
+ collection.layers = collection.layers.filter((layer) => {
483
+ const blocked = [...layer.ids].some((id) => pending.has(id));
484
+ if (!layer.settled || blocked) {
485
+ for (const id of layer.ids) pending.add(id);
486
+ return true;
487
+ }
488
+ for (const id of layer.ids) {
489
+ const current = collection.base.get(id);
490
+ if (current !== void 0)
491
+ collection.base.set(id, layer.apply(current, id));
492
+ baked.add(id);
493
+ }
494
+ return false;
495
+ });
496
+ return baked;
497
+ }
498
+ function predictKeyed(client, token, ids, apply) {
499
+ const store = storeOf(client);
500
+ const collection = collectionOf(store, token);
501
+ const layer = { ids, apply, settled: false };
502
+ collection.layers.push(layer);
503
+ changed(store, collection, ids);
504
+ const live = () => !layer.settled && collection.layers.includes(layer);
505
+ return {
506
+ accept() {
507
+ if (!live()) return;
508
+ const at = tick();
509
+ for (const id of ids) collection.acknowledgedAt.set(id, at);
510
+ layer.settled = true;
511
+ changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
512
+ },
513
+ remove() {
514
+ if (!live()) return;
515
+ collection.layers = collection.layers.filter((other) => other !== layer);
516
+ changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
517
+ }
518
+ };
519
+ }
520
+
521
+ // ../query-tags/src/optimistic.ts
522
+ import {
523
+ matchQuery,
524
+ notifyManager as notifyManager2,
525
+ replaceEqualDeep as replaceEqualDeep2
526
+ } from "@tanstack/react-query";
527
+ function optimisticKeyedUpdate(collection, key, update) {
528
+ return {
529
+ collection,
530
+ key,
531
+ update: (current, result) => update(current, result)
532
+ };
533
+ }
105
534
  function optimisticQueryUpdate(queryKey, update, path = []) {
106
535
  return {
107
536
  queryKey,
108
537
  path: [...path],
109
- update: (current) => update(current)
538
+ update: (current, result) => update(current, result)
110
539
  };
111
540
  }
112
541
  var predictions = /* @__PURE__ */ new WeakMap();
113
542
  var receipts = /* @__PURE__ */ new WeakMap();
114
- var order = 0;
543
+ var taggedMeta = /* @__PURE__ */ new WeakSet();
544
+ var syncedClients = /* @__PURE__ */ new WeakMap();
115
545
  function valueAt(data, path) {
116
546
  let value = data;
117
547
  for (const key of path) {
@@ -160,6 +590,22 @@ function confirmedValue(current, predicted, confirmed) {
160
590
  }
161
591
  return next;
162
592
  }
593
+ function rebase(base, visible, next) {
594
+ if (Object.is(visible, next)) return base;
595
+ if (typeof base !== "object" || base === null || typeof visible !== "object" || visible === null || typeof next !== "object" || next === null || Array.isArray(base) || Array.isArray(visible) || Array.isArray(next))
596
+ return next;
597
+ const result = {};
598
+ for (const key of Object.keys(base))
599
+ if (!Object.hasOwn(visible, key) && !Object.hasOwn(next, key))
600
+ result[key] = Reflect.get(base, key);
601
+ for (const key of Object.keys(next))
602
+ result[key] = Object.hasOwn(visible, key) && Object.hasOwn(base, key) ? rebase(
603
+ Reflect.get(base, key),
604
+ Reflect.get(visible, key),
605
+ Reflect.get(next, key)
606
+ ) : Reflect.get(next, key);
607
+ return result;
608
+ }
163
609
  function projected(state) {
164
610
  return state.layers.reduce((data, layer) => {
165
611
  const current = valueAt(data, layer.path);
@@ -185,38 +631,98 @@ function subscribeOptimisticQuery(query, listener) {
185
631
  if (listeners.size === 0) predictionListeners.delete(query);
186
632
  };
187
633
  }
634
+ function isTaggedQuery(query) {
635
+ return query.meta !== void 0 && taggedMeta.has(query.meta);
636
+ }
637
+ function applyLayer(data, layer) {
638
+ const current = valueAt(data, layer.path);
639
+ return replaceAt(
640
+ data,
641
+ layer.path,
642
+ layer.update(current === void 0 ? layer.initial : current.value)
643
+ );
644
+ }
645
+ function confirmLayers(query, state, ready) {
646
+ const tagged = isTaggedQuery(query);
647
+ while (state.layers[0] !== void 0 && ready(state.layers[0])) {
648
+ const layer = state.layers.shift();
649
+ state.base = applyLayer(state.base, layer);
650
+ if (tagged && !layer.fresh) state.guards.push(layer);
651
+ }
652
+ }
653
+ function confirmBeforeWrite(query, state) {
654
+ confirmLayers(query, state, (layer) => layer.acceptedAt !== null);
655
+ }
656
+ function isIdle(state) {
657
+ return state.layers.length === 0 && state.guards.length === 0;
658
+ }
659
+ function untrack(query, state) {
660
+ predictions.delete(query);
661
+ const synced = syncedClients.get(state.client);
662
+ if (synced === void 0) return;
663
+ synced.queries.delete(query);
664
+ if (synced.queries.size === 0) {
665
+ synced.unsubscribe();
666
+ syncedClients.delete(state.client);
667
+ }
668
+ }
669
+ function track(query, state) {
670
+ predictions.set(query, state);
671
+ let synced = syncedClients.get(state.client);
672
+ if (synced === void 0) {
673
+ const queries = /* @__PURE__ */ new Set();
674
+ const unsubscribe = state.client.getQueryCache().subscribe((event) => {
675
+ if (event.type !== "updated" || event.action.type !== "success") return;
676
+ const current = predictions.get(event.query);
677
+ if (current === void 0 || isTaggedQuery(event.query)) return;
678
+ const data = event.query.state.data;
679
+ if (event.action.manual) {
680
+ confirmBeforeWrite(event.query, current);
681
+ current.base = rebase(current.base, current.visible, data);
682
+ } else {
683
+ current.base = data;
684
+ }
685
+ publish(event.query, current);
686
+ });
687
+ synced = { queries, unsubscribe };
688
+ syncedClients.set(state.client, synced);
689
+ }
690
+ synced.queries.add(query);
691
+ }
188
692
  function publish(query, state) {
189
- query.setState({
190
- data: replaceEqualDeep(query.state.data, projected(state))
191
- });
192
- if (state.layers.length === 0) predictions.delete(query);
693
+ if (!isTaggedQuery(query))
694
+ confirmLayers(query, state, (layer) => layer.settled);
695
+ const data = replaceEqualDeep2(query.state.data, projected(state));
696
+ state.visible = data;
697
+ query.setState({ data });
698
+ if (isIdle(state)) untrack(query, state);
193
699
  for (const listener of predictionListeners.get(query) ?? []) listener();
194
700
  }
195
- function taggedReadReceipt(query) {
196
- const paths = [];
197
- return {
198
- start: () => ++order,
199
- record(started, loaded) {
200
- paths.push(...loaded.map((path) => ({ path, started })));
201
- },
202
- commit(data) {
203
- receipts.set(query, { data, paths });
204
- }
205
- };
701
+ function markTaggedQueryMeta(meta) {
702
+ taggedMeta.add(meta);
703
+ }
704
+ function commitTaggedReadReceipt(query, data, started) {
705
+ receipts.set(query, { data, started });
706
+ }
707
+ function consumeReceipt(query, next) {
708
+ const receipt = receipts.get(query);
709
+ if (receipt === void 0 || !Object.is(receipt.data, next)) return;
710
+ receipts.delete(query);
711
+ return receipt;
712
+ }
713
+ function refreshedBy(receipt, layer) {
714
+ return layer.acceptedAt !== null && receipt.started > layer.acceptedAt;
206
715
  }
207
716
  function taggedStructuralSharing(client, queryKey, previous, next) {
208
717
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
209
- const state = query === void 0 ? void 0 : predictions.get(query);
210
- if (query !== void 0) {
211
- const receipt = receipts.get(query);
212
- if (receipt !== void 0 && Object.is(receipt.data, next)) {
213
- receipts.delete(query);
214
- if (state !== void 0) {
718
+ if (query !== void 0 && Object.is(previous, query.state.data)) {
719
+ const receipt = consumeReceipt(query, next);
720
+ const state = predictions.get(query);
721
+ if (state !== void 0) {
722
+ if (receipt !== void 0) {
215
723
  const refreshed = /* @__PURE__ */ new Set();
216
724
  for (const layer of state.layers) {
217
- if (layer.acceptedAt !== null && receipt.paths.some(
218
- ({ path, started }) => started > layer.acceptedAt && prefix(path, layer.path)
219
- )) {
725
+ if (refreshedBy(receipt, layer)) {
220
726
  layer.fresh = true;
221
727
  refreshed.add(layer);
222
728
  }
@@ -225,60 +731,129 @@ function taggedStructuralSharing(client, queryKey, previous, next) {
225
731
  (layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
226
732
  );
227
733
  }
228
- }
229
- if (state !== void 0) {
230
- state.base = next;
734
+ if (receipt !== void 0) {
735
+ state.guards = state.guards.filter(
736
+ (guard) => !refreshedBy(receipt, guard)
737
+ );
738
+ state.base = state.guards.reduce(applyLayer, next);
739
+ } else {
740
+ confirmBeforeWrite(query, state);
741
+ state.base = rebase(state.base, previous, next);
742
+ }
231
743
  next = projected(state);
232
- if (state.layers.length === 0) predictions.delete(query);
744
+ state.visible = next;
745
+ if (isIdle(state)) untrack(query, state);
233
746
  }
234
747
  }
235
748
  const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
236
- return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep(previous, next);
749
+ return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep2(previous, next);
237
750
  }
238
751
  function getTaggedReadData(client, queryKey) {
239
752
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
240
753
  const state = query === void 0 ? void 0 : predictions.get(query);
241
754
  return state === void 0 ? query?.state.data : state.base;
242
755
  }
243
- function beginOptimisticMutation(client, updates) {
756
+ function isKeyedUpdate(update) {
757
+ return "collection" in update;
758
+ }
759
+ function beginKeyedPredictions(client, updates, result) {
760
+ const byCollection = /* @__PURE__ */ new Map();
761
+ for (const update of updates) {
762
+ const byKey = byCollection.get(update.collection) ?? /* @__PURE__ */ new Map();
763
+ byKey.set(update.key, [...byKey.get(update.key) ?? [], update]);
764
+ byCollection.set(update.collection, byKey);
765
+ }
766
+ return [...byCollection].map(
767
+ ([collection, byKey]) => predictKeyed(
768
+ client,
769
+ collection,
770
+ new Set(byKey.keys()),
771
+ (entity, key) => (byKey.get(key) ?? []).reduce(
772
+ (current, update) => update.update(current, result()),
773
+ entity
774
+ )
775
+ )
776
+ );
777
+ }
778
+ function beginOptimisticMutation(client, allUpdates) {
244
779
  const owner = {};
245
- const mutationOrder = ++order;
246
- let accepted = false;
780
+ const mutationOrder = tick();
781
+ let accepted;
782
+ let done = false;
783
+ const updates = allUpdates.filter(
784
+ (update) => !isKeyedUpdate(update)
785
+ );
786
+ const keyed = beginKeyedPredictions(
787
+ client,
788
+ allUpdates.filter(isKeyedUpdate),
789
+ () => accepted?.result.value === void 0 ? void 0 : accepted.result
790
+ );
247
791
  const affected = /* @__PURE__ */ new Map();
248
- const rollback = () => notifyManager.batch(() => {
249
- if (accepted) return;
792
+ const attached = new Map(
793
+ updates.map((update) => [update, /* @__PURE__ */ new Set()])
794
+ );
795
+ const attach = (query, update) => {
796
+ const queries = attached.get(update);
797
+ if (queries.has(query) || query.state.data === void 0) return;
798
+ const state = predictions.get(query) ?? {
799
+ client,
800
+ base: query.state.data,
801
+ visible: query.state.data,
802
+ layers: [],
803
+ guards: []
804
+ };
805
+ const current = valueAt(projected(state), update.path);
806
+ if (current === void 0) return;
807
+ queries.add(query);
808
+ const layer = {
809
+ owner,
810
+ order: mutationOrder,
811
+ path: update.path,
812
+ initial: current.value,
813
+ update: (value) => update.update(value, accepted?.result),
814
+ acceptedAt: accepted?.at ?? null,
815
+ fresh: false,
816
+ settled: false
817
+ };
818
+ const index = state.layers.findIndex((other) => other.order > layer.order);
819
+ if (index < 0) state.layers.push(layer);
820
+ else state.layers.splice(index, 0, layer);
821
+ track(query, state);
822
+ affected.set(query, state);
823
+ publish(query, state);
824
+ };
825
+ const unsubscribe = updates.length === 0 ? () => {
826
+ } : client.getQueryCache().subscribe((event) => {
827
+ if (event.type !== "updated" || event.action.type !== "success")
828
+ return;
829
+ for (const update of updates)
830
+ if (matchQuery(
831
+ { queryKey: update.queryKey, exact: true },
832
+ event.query
833
+ ))
834
+ attach(event.query, update);
835
+ });
836
+ const finish = () => {
837
+ done = true;
838
+ unsubscribe();
839
+ };
840
+ const rollback = () => notifyManager2.batch(() => {
841
+ if (accepted !== void 0 || done) return;
842
+ finish();
843
+ for (const prediction of keyed) prediction.remove();
250
844
  for (const [query, state] of affected) {
251
845
  state.layers = state.layers.filter((layer) => layer.owner !== owner);
252
846
  publish(query, state);
253
847
  }
254
848
  });
255
849
  try {
256
- notifyManager.batch(() => {
257
- for (const update of updates) {
258
- const query = client.getQueryCache().get(
259
- client.defaultQueryOptions({ queryKey: update.queryKey }).queryHash
260
- );
261
- if (query === void 0 || query.state.data === void 0) continue;
262
- const state = predictions.get(query) ?? {
263
- base: query.state.data,
264
- layers: []
265
- };
266
- const current = valueAt(projected(state), update.path);
267
- if (current === void 0) continue;
268
- state.layers.push({
269
- owner,
270
- order: mutationOrder,
271
- path: update.path,
272
- initial: current.value,
273
- update: update.update,
274
- acceptedAt: null,
275
- fresh: false,
276
- settled: false
277
- });
278
- predictions.set(query, state);
279
- affected.set(query, state);
280
- publish(query, state);
281
- }
850
+ notifyManager2.batch(() => {
851
+ for (const update of updates)
852
+ for (const query of client.getQueryCache().findAll({
853
+ queryKey: update.queryKey,
854
+ exact: true
855
+ }))
856
+ attach(query, update);
282
857
  });
283
858
  } catch (error) {
284
859
  rollback();
@@ -286,19 +861,27 @@ function beginOptimisticMutation(client, updates) {
286
861
  }
287
862
  return {
288
863
  rollback,
289
- accept() {
290
- accepted = true;
291
- const acceptedAt = ++order;
292
- for (const state of affected.values())
293
- for (const layer of state.layers)
294
- if (layer.owner === owner) layer.acceptedAt = acceptedAt;
864
+ accept(result) {
865
+ accepted = { at: tick(), result: { value: result } };
866
+ notifyManager2.batch(() => {
867
+ for (const prediction of keyed) prediction.accept();
868
+ for (const [query, state] of affected) {
869
+ for (const layer of state.layers)
870
+ if (layer.owner === owner) layer.acceptedAt = accepted.at;
871
+ publish(query, state);
872
+ }
873
+ });
295
874
  },
296
875
  settle() {
297
- notifyManager.batch(() => {
876
+ if (done) return;
877
+ finish();
878
+ notifyManager2.batch(() => {
298
879
  for (const [query, state] of affected) {
880
+ const tagged = isTaggedQuery(query);
299
881
  state.layers = state.layers.filter((layer) => {
300
882
  if (layer.owner !== owner) return true;
301
883
  layer.settled = true;
884
+ if (!tagged) return true;
302
885
  if (!layer.fresh) return true;
303
886
  if (!olderPending(state, layer)) return false;
304
887
  const current = valueAt(state.base, layer.path);
@@ -335,6 +918,7 @@ var registrations = /* @__PURE__ */ new WeakMap();
335
918
  var reads = /* @__PURE__ */ new WeakMap();
336
919
  function taggedQueryOptions(client, queryKey, registration) {
337
920
  const meta = {};
921
+ markTaggedQueryMeta(meta);
338
922
  registrations.set(meta, {
339
923
  scope: registration.scope,
340
924
  tagsOf: (data) => registration.tagsOf(data),
@@ -348,22 +932,20 @@ function taggedQueryOptions(client, queryKey, registration) {
348
932
  function registrationOf(query) {
349
933
  return query.meta === void 0 ? void 0 : registrations.get(query.meta);
350
934
  }
351
- async function runTaggedRead(client, queryKey, read, paths = () => [[]]) {
935
+ async function runTaggedRead(client, queryKey, read) {
352
936
  const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
353
937
  if (query === void 0) return read();
354
938
  const registration = registrationOf(query);
355
- const receipt = taggedReadReceipt(query);
356
939
  for (; ; ) {
357
940
  const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
358
941
  reads.set(query, pending);
359
- const started = receipt.start();
942
+ const started = tick();
360
943
  try {
361
944
  const result = await read();
362
- receipt.record(started, paths());
363
945
  const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
364
946
  if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
365
947
  if (pending.restart || overlap) continue;
366
- receipt.commit(result);
948
+ commitTaggedReadReceipt(query, result, started);
367
949
  return result;
368
950
  } catch (error) {
369
951
  if (pending.restart) continue;
@@ -411,10 +993,11 @@ async function invalidateTags(client, scope, tags) {
411
993
  }
412
994
  async function executeTaggedMutation(invalidate, call, prediction) {
413
995
  const { result, invalidated } = await call();
414
- prediction?.accept();
996
+ prediction?.accept(result);
415
997
  const refresh = async () => {
416
998
  try {
417
- if (invalidated.length > 0) await invalidate(invalidated);
999
+ if (invalidate !== void 0 && invalidated.length > 0)
1000
+ await invalidate(invalidated);
418
1001
  } finally {
419
1002
  prediction?.settle();
420
1003
  }
@@ -428,7 +1011,13 @@ function restartTaggedRead(query) {
428
1011
  const pending = reads.get(query);
429
1012
  if (pending) pending.restart = true;
430
1013
  }
431
- function useTaggedMutation(client, invalidate, call, optimistic) {
1014
+ function useTaggedMutation({
1015
+ client,
1016
+ invalidate,
1017
+ call,
1018
+ optimistic,
1019
+ meta
1020
+ }) {
432
1021
  const [owner] = useState(() => ({}));
433
1022
  const predict = useRef(optimistic);
434
1023
  useEffect(() => {
@@ -436,7 +1025,7 @@ function useTaggedMutation(client, invalidate, call, optimistic) {
436
1025
  }, [optimistic]);
437
1026
  const mutation = useMutation(
438
1027
  {
439
- meta: { taggedMutationOwner: owner },
1028
+ meta: { ...meta, taggedMutationOwner: owner },
440
1029
  mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
441
1030
  },
442
1031
  client
@@ -473,8 +1062,33 @@ function useTaggedMutation(client, invalidate, call, optimistic) {
473
1062
  reset: mutation.reset
474
1063
  };
475
1064
  }
1065
+ function hasRows(data) {
1066
+ return typeof data === "object" && data !== null && "result" in data && typeof data.result === "object" && data.result !== null;
1067
+ }
1068
+ var rowKey = (item) => Array.isArray(item) && typeof item[0] === "string" ? item[0] : void 0;
1069
+ var rowValue = (item) => Array.isArray(item) ? item[1] : void 0;
1070
+ function keyedRowsView(collection) {
1071
+ return {
1072
+ collection,
1073
+ slots: (data) => hasRows(data) ? [{ key: "result", items: Object.entries(data.result) }] : void 0,
1074
+ rebuild: (data, items) => hasRows(data) ? {
1075
+ ...data,
1076
+ result: Object.fromEntries(
1077
+ (items.get("result") ?? []).flatMap((item) => {
1078
+ const key = rowKey(item);
1079
+ return key === void 0 ? [] : [[key, rowValue(item)]];
1080
+ })
1081
+ )
1082
+ } : data,
1083
+ keyOf: rowKey,
1084
+ read: (item, current, fresh) => current === void 0 || fresh ? rowValue(item) : current,
1085
+ write: rowValue,
1086
+ render: (item, entity) => Object.is(rowValue(item), entity) ? item : [rowKey(item), entity]
1087
+ };
1088
+ }
476
1089
  function createTaggedKeyedQueryOwner(options) {
477
- const { client, queryKey, scope, read } = options;
1090
+ const { client, queryKey, scope, collection, read } = options;
1091
+ registerKeyedView(client, queryKey, keyedRowsView(collection));
478
1092
  const keys = /* @__PURE__ */ new Map();
479
1093
  let readingKeys = /* @__PURE__ */ new Set();
480
1094
  let missingOnly = false;
@@ -502,76 +1116,73 @@ function createTaggedKeyedQueryOwner(options) {
502
1116
  }),
503
1117
  queryFn: () => {
504
1118
  let previous = getTaggedReadData(client, queryKey);
505
- let loaded = [];
1119
+ const startedAt = /* @__PURE__ */ new Map();
506
1120
  let refresh = !missingOnly && dirtyKeys.size === 0;
507
1121
  missingOnly = false;
508
1122
  const refreshedKeys = /* @__PURE__ */ new Set();
509
1123
  let refreshedAll = false;
510
- return runTaggedRead(
511
- client,
512
- queryKey,
513
- async () => {
514
- const subscribed = await collectSubscribedKeys();
515
- const all = refreshAll || refresh;
516
- refresh = false;
517
- const dirty = new Set(dirtyKeys);
518
- for (const key of dirty) refreshedKeys.add(key);
519
- refreshedAll ||= all;
520
- dirtyKeys.clear();
521
- refreshAll = false;
522
- const requested = subscribed.filter(
523
- (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
1124
+ return runTaggedRead(client, queryKey, async () => {
1125
+ const subscribed = await collectSubscribedKeys();
1126
+ const all = refreshAll || refresh;
1127
+ refresh = false;
1128
+ const dirty = new Set(dirtyKeys);
1129
+ for (const key of dirty) refreshedKeys.add(key);
1130
+ refreshedAll ||= all;
1131
+ dirtyKeys.clear();
1132
+ refreshAll = false;
1133
+ const requested = subscribed.filter(
1134
+ (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
1135
+ );
1136
+ readingKeys = new Set(requested);
1137
+ const started = tick();
1138
+ try {
1139
+ const results = await Promise.all(
1140
+ Array.from(
1141
+ { length: Math.ceil(requested.length / 200) },
1142
+ async (_, i) => {
1143
+ const batch2 = requested.slice(i * 200, (i + 1) * 200);
1144
+ const response = await read(batch2);
1145
+ for (const key of batch2)
1146
+ if (!Object.hasOwn(response.result, key))
1147
+ throw new Error(`Keyed read omitted key ${key}`);
1148
+ return response;
1149
+ }
1150
+ )
524
1151
  );
525
- readingKeys = new Set(requested);
526
- try {
527
- const results = await Promise.all(
528
- Array.from(
529
- { length: Math.ceil(requested.length / 200) },
530
- async (_, i) => {
531
- const batch = requested.slice(i * 200, (i + 1) * 200);
532
- const response = await read(batch);
533
- for (const key of batch)
534
- if (!Object.hasOwn(response.result, key))
535
- throw new Error(`Keyed read omitted key ${key}`);
536
- return response;
537
- }
538
- )
539
- );
540
- const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
541
- loaded = requested;
542
- previous = {
543
- result: Object.fromEntries([
544
- ...Object.entries(previous?.result ?? {}).filter(
545
- ([key]) => retained(key)
546
- ),
547
- ...results.flatMap(
548
- (response) => Object.entries(response.result)
549
- )
550
- ]),
551
- tags: [
552
- .../* @__PURE__ */ new Set([
553
- ...all ? [] : previous?.tags ?? [],
554
- ...results.flatMap((r) => r.tags)
555
- ])
556
- ],
557
- keyTags: Object.fromEntries([
558
- ...Object.entries(previous?.keyTags ?? {}).filter(
559
- ([key]) => retained(key)
560
- ),
561
- ...results.flatMap(
562
- (response) => Object.entries(response.keyTags)
563
- )
1152
+ const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
1153
+ for (const key of requested) startedAt.set(key, started);
1154
+ previous = {
1155
+ result: Object.fromEntries([
1156
+ ...Object.entries(previous?.result ?? {}).filter(
1157
+ ([key]) => retained(key)
1158
+ ),
1159
+ ...results.flatMap((response) => Object.entries(response.result))
1160
+ ]),
1161
+ tags: [
1162
+ .../* @__PURE__ */ new Set([
1163
+ ...all ? [] : previous?.tags ?? [],
1164
+ ...results.flatMap((r) => r.tags)
564
1165
  ])
565
- };
566
- return previous;
567
- } catch (error) {
568
- for (const key of refreshedKeys) dirtyKeys.add(key);
569
- refreshAll ||= refreshedAll;
570
- throw error;
571
- }
572
- },
573
- () => loaded.map((key) => ["result", key])
574
- );
1166
+ ],
1167
+ keyTags: Object.fromEntries([
1168
+ ...Object.entries(previous?.keyTags ?? {}).filter(
1169
+ ([key]) => retained(key)
1170
+ ),
1171
+ ...results.flatMap(
1172
+ (response) => Object.entries(response.keyTags)
1173
+ )
1174
+ ])
1175
+ };
1176
+ return previous;
1177
+ } catch (error) {
1178
+ for (const key of refreshedKeys) dirtyKeys.add(key);
1179
+ refreshAll ||= refreshedAll;
1180
+ throw error;
1181
+ }
1182
+ }).then((data) => {
1183
+ recordKeyedRead(client, queryKey, startedAt);
1184
+ return data;
1185
+ });
575
1186
  }
576
1187
  });
577
1188
  const listeners = /* @__PURE__ */ new Set();
@@ -630,7 +1241,7 @@ function useQuerySelection(subscribe, getSnapshot, select) {
630
1241
  if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
631
1242
  cached = {
632
1243
  snapshot,
633
- value: replaceEqualDeep2(
1244
+ value: replaceEqualDeep3(
634
1245
  cached?.value ?? committed.current?.value,
635
1246
  select(snapshot)
636
1247
  )
@@ -669,14 +1280,23 @@ var jsonObjectSchema = z.record(
669
1280
  jsonValueSchema
670
1281
  );
671
1282
 
672
- // src/internal/rpc-query-host.ts
1283
+ // src/internal/rpc-tags.ts
673
1284
  import { z as z2 } from "zod";
674
- var envelopeSchema = z2.object({
675
- result: jsonValueSchema,
676
- tags: z2.array(z2.string()).default([]),
677
- keyTags: z2.record(z2.string(), z2.array(z2.string())).default({}),
678
- invalidated: z2.array(z2.string()).default([])
679
- });
1285
+ var rpcInvalidationTags = z2.array(z2.string().min(1)).min(1);
1286
+ function rpcResponseTags(declarations, input, output) {
1287
+ const tags = z2.array(z2.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
1288
+ const keyTags = {};
1289
+ if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
1290
+ for (const [key, value] of Object.entries(output)) {
1291
+ keyTags[key] = z2.array(z2.string().min(1)).parse(declarations.keyTags(key, value));
1292
+ }
1293
+ }
1294
+ const invalidated = z2.array(z2.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
1295
+ return { tags, keyTags, invalidated };
1296
+ }
1297
+
1298
+ // src/internal/rpc-query-host.ts
1299
+ import { z as z3 } from "zod";
680
1300
  var rpcQueryKey = (pluginId, method, input) => [
681
1301
  "plugin-rpc",
682
1302
  pluginId,
@@ -684,47 +1304,70 @@ var rpcQueryKey = (pluginId, method, input) => [
684
1304
  input
685
1305
  ];
686
1306
  var keyedQueryKey = (pluginId, method) => rpcQueryKey(pluginId, method, { keyed: true });
1307
+ var keyedCollections = /* @__PURE__ */ new Map();
1308
+ function keyedCollection(pluginId, method) {
1309
+ const name = JSON.stringify([pluginId, method]);
1310
+ let collection = keyedCollections.get(name);
1311
+ if (!collection) {
1312
+ collection = new KeyedCollection(name);
1313
+ keyedCollections.set(name, collection);
1314
+ }
1315
+ return collection;
1316
+ }
1317
+ function parsedUpdate(update) {
1318
+ return (current) => jsonValueSchema.parse(update(current));
1319
+ }
687
1320
  function optimisticCache(pluginId, updates) {
688
- const add = (prediction) => {
689
- updates.push({
690
- ...prediction,
691
- update: (current) => jsonValueSchema.parse(prediction.update(current))
692
- });
693
- };
694
1321
  return {
695
1322
  update(method, input, update) {
696
- add(
1323
+ updates.push(
697
1324
  optimisticQueryUpdate(
698
1325
  rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
699
- update,
1326
+ parsedUpdate(update),
700
1327
  ["result"]
701
1328
  )
702
1329
  );
703
1330
  },
704
1331
  updateKey(method, key, update) {
705
- add(
706
- optimisticQueryUpdate(keyedQueryKey(pluginId, method), update, [
707
- "result",
708
- key
709
- ])
1332
+ updates.push(
1333
+ optimisticKeyedUpdate(
1334
+ keyedCollection(pluginId, method),
1335
+ key,
1336
+ parsedUpdate(update)
1337
+ )
710
1338
  );
711
1339
  }
712
1340
  };
713
1341
  }
714
- async function callRpcEnvelope(host, pluginId, method, input) {
1342
+ async function callRpc(host, pluginId, contract, method, input) {
715
1343
  let raw;
716
1344
  try {
717
1345
  raw = await host.call(pluginId, method, input);
718
1346
  } catch (error) {
719
1347
  throw experimental_PluginRpcCallError.from(error);
720
1348
  }
721
- const parsed = envelopeSchema.safeParse(raw);
722
- if (!parsed.success)
1349
+ const result = jsonValueSchema.safeParse(raw);
1350
+ if (!result.success)
723
1351
  throw new experimental_PluginRpcCallError({
724
1352
  code: "invalid_response",
725
1353
  message: `Invalid RPC response for ${method}`
726
1354
  });
727
- return parsed.data;
1355
+ const methodContract = contract[method];
1356
+ if (methodContract === void 0)
1357
+ throw new experimental_PluginRpcCallError({
1358
+ code: "unknown_method",
1359
+ message: `rpc method "${method}" isn't in the contract`
1360
+ });
1361
+ const parsedInput = await methodContract.input["~standard"].validate(input);
1362
+ if (parsedInput.issues !== void 0)
1363
+ throw new experimental_PluginRpcCallError({
1364
+ code: "invalid_input",
1365
+ message: `rpc input validation failed for ${method}`
1366
+ });
1367
+ return {
1368
+ result: result.data,
1369
+ ...rpcResponseTags(methodContract, parsedInput.value, result.data)
1370
+ };
728
1371
  }
729
1372
  var tagsOf = (data) => [
730
1373
  ...data.tags,
@@ -755,7 +1398,13 @@ function createRpcQueryHooks(useHost) {
755
1398
  queryFn: () => runTaggedRead(
756
1399
  host.queryClient,
757
1400
  queryKey,
758
- async () => callRpcEnvelope(host, pluginId, options.method, input)
1401
+ async () => callRpc(
1402
+ host,
1403
+ pluginId,
1404
+ options.contract,
1405
+ options.method,
1406
+ input
1407
+ )
759
1408
  )
760
1409
  },
761
1410
  host.queryClient
@@ -779,7 +1428,7 @@ function createRpcQueryHooks(useHost) {
779
1428
  const enabled = options.enabled ?? true;
780
1429
  const identity = JSON.stringify([...new Set(options.keys)].sort());
781
1430
  const keys = useMemo2(
782
- () => z2.array(z2.string()).parse(JSON.parse(identity)),
1431
+ () => z3.array(z3.string()).parse(JSON.parse(identity)),
783
1432
  [identity]
784
1433
  );
785
1434
  let cache = owners.get(host.queryClient);
@@ -794,16 +1443,18 @@ function createRpcQueryHooks(useHost) {
794
1443
  client: host.queryClient,
795
1444
  queryKey: keyedQueryKey(pluginId, options.method),
796
1445
  scope: pluginTagScope(pluginId),
1446
+ collection: keyedCollection(pluginId, options.method),
797
1447
  read: async (keys2) => {
798
- const response = await callRpcEnvelope(
1448
+ const response = await callRpc(
799
1449
  host,
800
1450
  pluginId,
1451
+ options.contract,
801
1452
  options.method,
802
1453
  { keys: [...keys2] }
803
1454
  );
804
1455
  return {
805
1456
  ...response,
806
- result: z2.record(z2.string(), jsonValueSchema).parse(response.result)
1457
+ result: z3.record(z3.string(), jsonValueSchema).parse(response.result)
807
1458
  };
808
1459
  }
809
1460
  });
@@ -851,13 +1502,14 @@ function createRpcQueryHooks(useHost) {
851
1502
  function experimental_useRpcMutation(options) {
852
1503
  const host = useHost();
853
1504
  const pluginId = options.pluginId ?? host.pluginId;
854
- const mutation = useTaggedMutation(
855
- host.queryClient,
856
- (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
857
- async (input) => {
858
- const response = await callRpcEnvelope(
1505
+ const mutation = useTaggedMutation({
1506
+ client: host.queryClient,
1507
+ invalidate: (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
1508
+ call: async (input) => {
1509
+ const response = await callRpc(
859
1510
  host,
860
1511
  pluginId,
1512
+ options.contract,
861
1513
  options.method,
862
1514
  jsonValueSchema.parse(input)
863
1515
  );
@@ -866,7 +1518,7 @@ function createRpcQueryHooks(useHost) {
866
1518
  result: response.result
867
1519
  };
868
1520
  },
869
- (input) => {
1521
+ optimistic: (input) => {
870
1522
  const updates = [];
871
1523
  options.optimistic?.(
872
1524
  input,
@@ -874,7 +1526,7 @@ function createRpcQueryHooks(useHost) {
874
1526
  );
875
1527
  return updates;
876
1528
  }
877
- );
1529
+ });
878
1530
  const { mutate } = mutation;
879
1531
  return {
880
1532
  ...mutation,
@@ -921,21 +1573,6 @@ function createRpcQueryHooks(useHost) {
921
1573
  };
922
1574
  }
923
1575
 
924
- // src/internal/rpc-tags.ts
925
- import { z as z3 } from "zod";
926
- var rpcInvalidationTags = z3.array(z3.string().min(1)).min(1);
927
- function rpcResponseTags(declarations, input, output) {
928
- const tags = z3.array(z3.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
929
- const keyTags = {};
930
- if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
931
- for (const [key, value] of Object.entries(output)) {
932
- keyTags[key] = z3.array(z3.string().min(1)).parse(declarations.keyTags(key, value));
933
- }
934
- }
935
- const invalidated = z3.array(z3.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
936
- return { tags, keyTags, invalidated };
937
- }
938
-
939
1576
  // src/testing/app.tsx
940
1577
  import * as React from "react";
941
1578
  import {
@@ -1314,12 +1951,8 @@ function createComposerHandleBinding(key, initial) {
1314
1951
  }
1315
1952
  target().setDraft(appendComposerDraft(target().getDraft(), value, block));
1316
1953
  };
1317
- const submit = async (options) => {
1954
+ const submit = async (options = {}) => {
1318
1955
  requireAvailable();
1319
- const hostSubmit = target().submit;
1320
- if (hostSubmit === void 0) {
1321
- throw new Error("This composer cannot submit programmatically.");
1322
- }
1323
1956
  if (options.sendAt !== void 0 && (!Number.isFinite(options.sendAt) || options.sendAt <= Date.now())) {
1324
1957
  throw new Error("Pick a time in the future.");
1325
1958
  }
@@ -1329,15 +1962,18 @@ function createComposerHandleBinding(key, initial) {
1329
1962
  if (state.attachmentError !== null && state.attachmentError !== errorBefore) {
1330
1963
  throw new Error(state.attachmentError);
1331
1964
  }
1332
- if (state.isSubmittingBlocked) {
1333
- throw new Error(
1334
- state.submittingBlockedReason ?? "This composer can't submit right now."
1335
- );
1336
- }
1337
- await hostSubmit(
1338
- options,
1339
- options.experimental_data === void 0 ? void 0 : { pluginId: controller.pluginId, data: options.experimental_data }
1340
- );
1965
+ const submission = target().editorSubmit({
1966
+ mode: options.experimental_mode ?? "enter",
1967
+ ...options.sendAt === void 0 ? {} : { sendAt: options.sendAt },
1968
+ ...options.experimental_data === void 0 ? {} : {
1969
+ pluginSubmission: {
1970
+ pluginId: controller.pluginId,
1971
+ data: options.experimental_data
1972
+ }
1973
+ }
1974
+ });
1975
+ if (submission === null) throw new Error(OFF_SCREEN_MESSAGE);
1976
+ await submission;
1341
1977
  };
1342
1978
  const setSelection = async (selection) => {
1343
1979
  requireAvailable();
@@ -1904,24 +2540,8 @@ var experimental_THREAD_ACTION_GROUPS = {
1904
2540
  lifecycle: "4_lifecycle"
1905
2541
  };
1906
2542
 
1907
- // src/internal/plugin-app-collector.ts
1908
- import { z as z5 } from "zod";
1909
- var CODE_FENCE_LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]*$/;
2543
+ // src/internal/sidebar-footer-runtime.ts
1910
2544
  var sidebarFooterCommandSequence = 0;
1911
- var SIDEBAR_FOOTER_ACTION_KEYS = /* @__PURE__ */ new Set([
1912
- "id",
1913
- "label",
1914
- "icon",
1915
- "kind",
1916
- "onActivate"
1917
- ]);
1918
- var SIDEBAR_FOOTER_DISCLOSURE_KEYS = /* @__PURE__ */ new Set([
1919
- "id",
1920
- "label",
1921
- "icon",
1922
- "kind",
1923
- "component"
1924
- ]);
1925
2545
  var SidebarFooterItemRuntime = class {
1926
2546
  listeners = /* @__PURE__ */ new Set();
1927
2547
  snapshot = {
@@ -1967,6 +2587,25 @@ function adaptSidebarFooterAction(registration) {
1967
2587
  runtime: new SidebarFooterItemRuntime()
1968
2588
  };
1969
2589
  }
2590
+ var sidebarFooterItemsByRegistrationSet = /* @__PURE__ */ new WeakMap();
2591
+
2592
+ // src/internal/plugin-app-registration-collector.ts
2593
+ import { z as z5 } from "zod";
2594
+ var CODE_FENCE_LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]*$/;
2595
+ var SIDEBAR_FOOTER_ACTION_KEYS = /* @__PURE__ */ new Set([
2596
+ "id",
2597
+ "label",
2598
+ "icon",
2599
+ "kind",
2600
+ "onActivate"
2601
+ ]);
2602
+ var SIDEBAR_FOOTER_DISCLOSURE_KEYS = /* @__PURE__ */ new Set([
2603
+ "id",
2604
+ "label",
2605
+ "icon",
2606
+ "kind",
2607
+ "component"
2608
+ ]);
1970
2609
  var SidebarFooterCollector = class {
1971
2610
  constructor(collected, allCollected, seenIds) {
1972
2611
  this.collected = collected;
@@ -2028,20 +2667,18 @@ var SidebarFooterCollector = class {
2028
2667
  }
2029
2668
  }
2030
2669
  };
2031
- var NAV_PANEL_REGISTRATION_KEYS = new Set(
2032
- Object.keys({
2033
- id: true,
2034
- title: true,
2035
- icon: true,
2036
- path: true,
2037
- component: true,
2038
- fixedTabs: true,
2039
- experimental_useBadge: true,
2040
- experimental_usePageTitle: true,
2041
- experimental_sidebar: true,
2042
- headerContent: true
2043
- })
2044
- );
2670
+ var NAV_PANEL_REGISTRATION_KEYS = {
2671
+ id: true,
2672
+ title: true,
2673
+ icon: true,
2674
+ path: true,
2675
+ component: true,
2676
+ fixedTabs: true,
2677
+ experimental_useBadge: true,
2678
+ experimental_usePageTitle: true,
2679
+ experimental_sidebar: true,
2680
+ headerContent: true
2681
+ };
2045
2682
  var RENAMED_NAV_PANEL_KEYS = /* @__PURE__ */ new Map([
2046
2683
  ["experimental_fixedTabs", 'was renamed to "fixedTabs" in SDK 0.4.16']
2047
2684
  ]);
@@ -2053,7 +2690,7 @@ var RETIRED_NAV_PANEL_KEYS = /* @__PURE__ */ new Map([
2053
2690
  ]);
2054
2691
  function checkStaleNavPanelKeys(kind, registration, onWarning) {
2055
2692
  for (const key of Object.keys(registration)) {
2056
- if (NAV_PANEL_REGISTRATION_KEYS.has(key)) continue;
2693
+ if (Object.hasOwn(NAV_PANEL_REGISTRATION_KEYS, key)) continue;
2057
2694
  const renamed = RENAMED_NAV_PANEL_KEYS.get(key);
2058
2695
  if (renamed !== void 0) {
2059
2696
  throw new Error(`${kind}: "${key}" ${renamed}`);
@@ -2068,28 +2705,29 @@ function checkStaleNavPanelKeys(kind, registration, onWarning) {
2068
2705
  }
2069
2706
  }
2070
2707
  }
2071
- var commandShortcutSchema = z5.object({
2072
- key: z5.string().min(1).max(32).refine(
2073
- (key) => ![
2074
- "Alt",
2075
- "Control",
2076
- "Meta",
2077
- "OS",
2078
- "Shift",
2079
- "Dead",
2080
- "Unidentified"
2081
- ].includes(key)
2082
- ),
2083
- mod: z5.boolean().default(false),
2084
- meta: z5.boolean().default(false),
2085
- control: z5.boolean().default(false),
2086
- alt: z5.boolean().default(false),
2087
- shift: z5.boolean().default(false)
2088
- }).strict().refine(
2089
- (shortcut) => shortcut.mod || shortcut.meta || shortcut.control || shortcut.alt || /^F(?:[1-9]|1[0-9]|2[0-4])$/u.test(shortcut.key),
2090
- "Use Command, Control, or Alt with a key, or a function key"
2091
- );
2092
- var sidebarFooterItemsByRegistrationSet = /* @__PURE__ */ new WeakMap();
2708
+ function createCommandShortcutSchema() {
2709
+ return z5.object({
2710
+ key: z5.string().min(1).max(32).refine(
2711
+ (key) => ![
2712
+ "Alt",
2713
+ "Control",
2714
+ "Meta",
2715
+ "OS",
2716
+ "Shift",
2717
+ "Dead",
2718
+ "Unidentified"
2719
+ ].includes(key)
2720
+ ),
2721
+ mod: z5.boolean().default(false),
2722
+ meta: z5.boolean().default(false),
2723
+ control: z5.boolean().default(false),
2724
+ alt: z5.boolean().default(false),
2725
+ shift: z5.boolean().default(false)
2726
+ }).strict().refine(
2727
+ (shortcut) => shortcut.mod || shortcut.meta || shortcut.control || shortcut.alt || /^F(?:[1-9]|1[0-9]|2[0-4])$/u.test(shortcut.key),
2728
+ "Use Command, Control, or Alt with a key, or a function key"
2729
+ );
2730
+ }
2093
2731
  function collectTitledComponent(kind, seen, registration) {
2094
2732
  const id = requireSlotId(kind, registration?.id);
2095
2733
  requireUniqueId(kind, seen, id);
@@ -2124,6 +2762,7 @@ function collectPanelAction(kind, seen, registration) {
2124
2762
  };
2125
2763
  }
2126
2764
  function collectPluginAppRegistrations(definition, onWarning = (message) => console.warn(message)) {
2765
+ const commandShortcutSchema = createCommandShortcutSchema();
2127
2766
  const sidebarFooterItems = [];
2128
2767
  const collected = {
2129
2768
  homepageSections: [],
@@ -3596,9 +4235,7 @@ var testPluginSdkApp = {
3596
4235
  },
3597
4236
  experimental_useSidebarNavigationSplit(itemId, _options) {
3598
4237
  const env = useSlotEnv("experimental_useSidebarNavigationSplit");
3599
- const kind = env.sidebarNavigation.items.find(
3600
- (item) => item.id === itemId
3601
- )?.action.kind;
4238
+ const kind = env.sidebarNavigation.items.find((item) => item.id === itemId)?.action.kind;
3602
4239
  const isAvailable = kind === "new-thread" || kind === "open-plugin-panel";
3603
4240
  return useMemo3(
3604
4241
  () => ({
@@ -3865,7 +4502,7 @@ function renderSlot(registration, props, options = {}) {
3865
4502
  return parsed.value;
3866
4503
  };
3867
4504
  const queryClient = new QueryClient();
3868
- const callRpc = async (method, input) => {
4505
+ const callRpc2 = async (method, input) => {
3869
4506
  const normalizedInput = input === void 0 ? null : strictJsonRoundTrip(input, `rpc "${method}" input`);
3870
4507
  rpcCalls.push({ method, input: normalizedInput });
3871
4508
  const handler = rpcHandlers[method];
@@ -3884,18 +4521,10 @@ function renderSlot(registration, props, options = {}) {
3884
4521
  throw experimental_PluginRpcCallError.from(error, "handler_error");
3885
4522
  }
3886
4523
  const parsedOutput = declaration ? await parseRpcValue(declaration.output, result2, "invalid_output") : result2;
3887
- const envelope = rpcResponseTags(
3888
- declaration ?? {},
3889
- parsedInput,
3890
- parsedOutput
3891
- );
3892
- return {
3893
- result: strictJsonRoundTrip(parsedOutput, `rpc "${method}" result`),
3894
- ...envelope
3895
- };
4524
+ return strictJsonRoundTrip(parsedOutput, `rpc "${method}" result`);
3896
4525
  };
3897
4526
  const rpcClient = {
3898
- call: async (method, input) => (await callRpc(method, input)).result
4527
+ call: (method, input) => callRpc2(method, input)
3899
4528
  };
3900
4529
  const realtimeHandlers = /* @__PURE__ */ new Map();
3901
4530
  let realtimeConnectionState = options.realtimeConnectionState ?? "connected";
@@ -4286,6 +4915,17 @@ ${block}
4286
4915
  },
4287
4916
  subscribeEditorState: () => () => {
4288
4917
  },
4918
+ async editorSubmit({ mode, sendAt, pluginSubmission }) {
4919
+ const reason = composerBlockedReason();
4920
+ if (reason !== null) throw new Error(reason);
4921
+ composerLog.submits.push({
4922
+ ...mode === "enter" ? {} : { experimental_mode: mode },
4923
+ ...sendAt === void 0 ? {} : { sendAt },
4924
+ ...pluginSubmission === void 0 ? {} : { experimental_data: pluginSubmission.data }
4925
+ });
4926
+ commitComposerDraft("", []);
4927
+ for (const listener of submissionListeners) listener();
4928
+ },
4289
4929
  insertAtCursor(value, block) {
4290
4930
  composerTarget.setDraft(
4291
4931
  appendComposerDraft(composerDraft(), value, block)
@@ -4296,11 +4936,6 @@ ${block}
4296
4936
  focus() {
4297
4937
  composerLog.focusCount += 1;
4298
4938
  },
4299
- async submit(submitOptions) {
4300
- composerLog.submits.push(submitOptions);
4301
- commitComposerDraft("", []);
4302
- for (const listener of submissionListeners) listener();
4303
- },
4304
4939
  async setSelection(selection) {
4305
4940
  if (composerScope.kind === "queued-message") {
4306
4941
  throw new Error("This composer has no pickers to set.");
@@ -4389,7 +5024,7 @@ ${block}
4389
5024
  queryClient,
4390
5025
  subscribe: () => () => {
4391
5026
  },
4392
- call: (_pluginId, method, input) => callRpc(method, input)
5027
+ call: (_pluginId, method, input) => callRpc2(method, input)
4393
5028
  };
4394
5029
  const env = {
4395
5030
  rpcQueryHost,