@get-bb/plugin-sdk 0.6.60 → 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.
@@ -1,16 +1,1591 @@
1
- // src/testing/app.tsx
2
- import * as React from "react";
1
+ // src/rpc-contract.ts
2
+ var rpcErrorCodes = [
3
+ "forbidden",
4
+ "not_found",
5
+ "conflict",
6
+ "invalid",
7
+ "invalid_json",
8
+ "invalid_input",
9
+ "handler_error",
10
+ "invalid_output",
11
+ "non_json_result",
12
+ "unknown_method",
13
+ "transport_error",
14
+ "invalid_response",
15
+ "unknown_error"
16
+ ];
17
+ var callErrorBrand = /* @__PURE__ */ Symbol.for("@get-bb/plugin-sdk/rpc-call-error");
18
+ var experimental_PluginRpcCallError = class _experimental_PluginRpcCallError extends Error {
19
+ /** Recognizes errors across the packed SDK's separately bundled entries. */
20
+ static [Symbol.hasInstance](value) {
21
+ return typeof value === "object" && value !== null && Reflect.get(value, callErrorBrand) === true && rpcErrorCodes.some((code) => code === Reflect.get(value, "code")) && typeof Reflect.get(value, "message") === "string";
22
+ }
23
+ code;
24
+ issues;
25
+ status;
26
+ serverCode;
27
+ constructor(args) {
28
+ super(args.message);
29
+ this.name = "experimental_PluginRpcCallError";
30
+ Object.defineProperty(this, callErrorBrand, { value: true });
31
+ this.code = args.code;
32
+ this.issues = args.issues;
33
+ this.status = args.status;
34
+ this.serverCode = args.serverCode;
35
+ }
36
+ /** Normalize failures at the RPC boundary; preserves an existing client error. */
37
+ static from(error, fallback = "transport_error") {
38
+ if (error instanceof _experimental_PluginRpcCallError) return error;
39
+ const record = typeof error === "object" && error !== null ? error : {};
40
+ const rawCode = Reflect.get(record, "code");
41
+ const code = rpcErrorCodes.find((value) => value === rawCode);
42
+ const message = Reflect.get(record, "message");
43
+ const status = Reflect.get(record, "status");
44
+ const rawIssues = Reflect.get(record, "issues");
45
+ const issues = [];
46
+ if (Array.isArray(rawIssues))
47
+ for (const issue of rawIssues) {
48
+ if (typeof issue !== "object" || issue === null || typeof Reflect.get(issue, "message") !== "string")
49
+ continue;
50
+ const path = Reflect.get(issue, "path");
51
+ if (path !== void 0 && (!Array.isArray(path) || !path.every(
52
+ (part) => typeof part === "string" || typeof part === "number" && Number.isFinite(part)
53
+ )))
54
+ continue;
55
+ issues.push({
56
+ message: Reflect.get(issue, "message"),
57
+ ...path === void 0 ? {} : { path }
58
+ });
59
+ }
60
+ return new _experimental_PluginRpcCallError({
61
+ code: code ?? (typeof rawCode === "string" ? "unknown_error" : fallback),
62
+ message: typeof message === "string" ? message : typeof error === "string" ? error : "Plugin RPC request failed",
63
+ ...issues.length === 0 ? {} : { issues },
64
+ ...typeof status === "number" ? { status } : {},
65
+ ...typeof rawCode === "string" && code === void 0 ? { serverCode: rawCode } : {}
66
+ });
67
+ }
68
+ };
69
+ var refusalBrand = /* @__PURE__ */ Symbol.for("@get-bb/plugin-sdk/rpc-refusal");
70
+ var experimental_PluginRpcRefusal = class extends Error {
71
+ [refusalBrand] = true;
72
+ code;
73
+ issues;
74
+ constructor(args) {
75
+ super(args.message);
76
+ this.name = "experimental_PluginRpcRefusal";
77
+ this.code = args.code;
78
+ this.issues = args.issues;
79
+ }
80
+ };
81
+
82
+ // ../query-tags/src/index.ts
3
83
  import {
4
- createContext,
5
84
  useCallback,
6
- useContext,
7
- useLayoutEffect,
8
85
  useEffect,
9
86
  useMemo,
10
87
  useRef,
11
88
  useState,
12
89
  useSyncExternalStore
13
90
  } from "react";
91
+ import {
92
+ QueryObserver,
93
+ useQuery,
94
+ useQueryClient,
95
+ useMutation,
96
+ useMutationState,
97
+ replaceEqualDeep as replaceEqualDeep3
98
+ } from "@tanstack/react-query";
99
+
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
107
+ import {
108
+ notifyManager,
109
+ replaceEqualDeep
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
+ }
534
+ function optimisticQueryUpdate(queryKey, update, path = []) {
535
+ return {
536
+ queryKey,
537
+ path: [...path],
538
+ update: (current, result) => update(current, result)
539
+ };
540
+ }
541
+ var predictions = /* @__PURE__ */ new WeakMap();
542
+ var receipts = /* @__PURE__ */ new WeakMap();
543
+ var taggedMeta = /* @__PURE__ */ new WeakSet();
544
+ var syncedClients = /* @__PURE__ */ new WeakMap();
545
+ function valueAt(data, path) {
546
+ let value = data;
547
+ for (const key of path) {
548
+ if (typeof value !== "object" || value === null || !Object.hasOwn(value, key))
549
+ return;
550
+ value = Reflect.get(value, key);
551
+ }
552
+ return value === void 0 ? void 0 : { value };
553
+ }
554
+ function replaceAt(data, path, value) {
555
+ const [key, ...rest] = path;
556
+ if (key === void 0) return value;
557
+ if (typeof data !== "object" || data === null) return data;
558
+ const next = Array.isArray(data) ? [...data] : { ...data };
559
+ Reflect.set(next, key, replaceAt(Reflect.get(data, key), rest, value));
560
+ return next;
561
+ }
562
+ function prefix(left, right) {
563
+ return left.length <= right.length && left.every((part, index) => part === right[index]);
564
+ }
565
+ function olderPending(state, layer) {
566
+ return state.layers.some(
567
+ (other) => other.order < layer.order && !other.settled && (prefix(other.path, layer.path) || prefix(layer.path, other.path))
568
+ );
569
+ }
570
+ function confirmedValue(current, predicted, confirmed) {
571
+ if (Object.is(predicted, confirmed)) return current;
572
+ if (typeof current !== "object" || current === null || typeof predicted !== "object" || predicted === null || typeof confirmed !== "object" || confirmed === null || Array.isArray(predicted) !== Array.isArray(confirmed) || Array.isArray(predicted) && (!Array.isArray(confirmed) || predicted.length !== confirmed.length))
573
+ return confirmed;
574
+ const next = Array.isArray(current) ? [...current] : { ...current };
575
+ for (const key of /* @__PURE__ */ new Set([
576
+ ...Object.keys(predicted),
577
+ ...Object.keys(confirmed)
578
+ ])) {
579
+ if (!Object.hasOwn(confirmed, key)) Reflect.deleteProperty(next, key);
580
+ else
581
+ Reflect.set(
582
+ next,
583
+ key,
584
+ confirmedValue(
585
+ Reflect.get(current, key),
586
+ Reflect.get(predicted, key),
587
+ Reflect.get(confirmed, key)
588
+ )
589
+ );
590
+ }
591
+ return next;
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
+ }
609
+ function projected(state) {
610
+ return state.layers.reduce((data, layer) => {
611
+ const current = valueAt(data, layer.path);
612
+ return replaceAt(
613
+ data,
614
+ layer.path,
615
+ layer.update(current === void 0 ? layer.initial : current.value)
616
+ );
617
+ }, state.base);
618
+ }
619
+ var predictionListeners = /* @__PURE__ */ new WeakMap();
620
+ function subscribeOptimisticQuery(query, listener) {
621
+ if (query === void 0) return () => {
622
+ };
623
+ let listeners = predictionListeners.get(query);
624
+ if (listeners === void 0) {
625
+ listeners = /* @__PURE__ */ new Set();
626
+ predictionListeners.set(query, listeners);
627
+ }
628
+ listeners.add(listener);
629
+ return () => {
630
+ listeners.delete(listener);
631
+ if (listeners.size === 0) predictionListeners.delete(query);
632
+ };
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
+ }
692
+ function publish(query, state) {
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);
699
+ for (const listener of predictionListeners.get(query) ?? []) listener();
700
+ }
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;
715
+ }
716
+ function taggedStructuralSharing(client, queryKey, previous, next) {
717
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
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) {
723
+ const refreshed = /* @__PURE__ */ new Set();
724
+ for (const layer of state.layers) {
725
+ if (refreshedBy(receipt, layer)) {
726
+ layer.fresh = true;
727
+ refreshed.add(layer);
728
+ }
729
+ }
730
+ state.layers = state.layers.filter(
731
+ (layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
732
+ );
733
+ }
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
+ }
743
+ next = projected(state);
744
+ state.visible = next;
745
+ if (isIdle(state)) untrack(query, state);
746
+ }
747
+ }
748
+ const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
749
+ return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep2(previous, next);
750
+ }
751
+ function getTaggedReadData(client, queryKey) {
752
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
753
+ const state = query === void 0 ? void 0 : predictions.get(query);
754
+ return state === void 0 ? query?.state.data : state.base;
755
+ }
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) {
779
+ const owner = {};
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
+ );
791
+ const affected = /* @__PURE__ */ new Map();
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();
844
+ for (const [query, state] of affected) {
845
+ state.layers = state.layers.filter((layer) => layer.owner !== owner);
846
+ publish(query, state);
847
+ }
848
+ });
849
+ try {
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);
857
+ });
858
+ } catch (error) {
859
+ rollback();
860
+ throw error;
861
+ }
862
+ return {
863
+ rollback,
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
+ });
874
+ },
875
+ settle() {
876
+ if (done) return;
877
+ finish();
878
+ notifyManager2.batch(() => {
879
+ for (const [query, state] of affected) {
880
+ const tagged = isTaggedQuery(query);
881
+ state.layers = state.layers.filter((layer) => {
882
+ if (layer.owner !== owner) return true;
883
+ layer.settled = true;
884
+ if (!tagged) return true;
885
+ if (!layer.fresh) return true;
886
+ if (!olderPending(state, layer)) return false;
887
+ const current = valueAt(state.base, layer.path);
888
+ if (current !== void 0) {
889
+ const update = layer.update;
890
+ const predicted = update(current.value);
891
+ layer.update = (value) => confirmedValue(update(value), predicted, current.value);
892
+ }
893
+ return true;
894
+ });
895
+ publish(query, state);
896
+ }
897
+ });
898
+ }
899
+ };
900
+ }
901
+
902
+ // ../query-tags/src/index.ts
903
+ function useTaggedQuery(options, client) {
904
+ const queryClient = useQueryClient(client);
905
+ const result = useQuery(options, queryClient);
906
+ const query = queryClient.getQueryCache().get(queryClient.defaultQueryOptions(options).queryHash);
907
+ const subscribed = options.subscribed !== false;
908
+ const subscribe = useCallback(
909
+ (listener) => subscribed ? subscribeOptimisticQuery(query, listener) : () => {
910
+ },
911
+ [query, subscribed]
912
+ );
913
+ const snapshot = useCallback(() => query?.state.data, [query]);
914
+ useSyncExternalStore(subscribe, snapshot, snapshot);
915
+ return result;
916
+ }
917
+ var registrations = /* @__PURE__ */ new WeakMap();
918
+ var reads = /* @__PURE__ */ new WeakMap();
919
+ function taggedQueryOptions(client, queryKey, registration) {
920
+ const meta = {};
921
+ markTaggedQueryMeta(meta);
922
+ registrations.set(meta, {
923
+ scope: registration.scope,
924
+ tagsOf: (data) => registration.tagsOf(data),
925
+ onInvalidate: (data, tags) => registration.onInvalidate?.(data, tags)
926
+ });
927
+ return {
928
+ meta,
929
+ structuralSharing: (previous, next) => taggedStructuralSharing(client, queryKey, previous, next)
930
+ };
931
+ }
932
+ function registrationOf(query) {
933
+ return query.meta === void 0 ? void 0 : registrations.get(query.meta);
934
+ }
935
+ async function runTaggedRead(client, queryKey, read) {
936
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
937
+ if (query === void 0) return read();
938
+ const registration = registrationOf(query);
939
+ for (; ; ) {
940
+ const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
941
+ reads.set(query, pending);
942
+ const started = tick();
943
+ try {
944
+ const result = await read();
945
+ const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
946
+ if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
947
+ if (pending.restart || overlap) continue;
948
+ commitTaggedReadReceipt(query, result, started);
949
+ return result;
950
+ } catch (error) {
951
+ if (pending.restart) continue;
952
+ throw error;
953
+ } finally {
954
+ if (reads.get(query) === pending) reads.delete(query);
955
+ }
956
+ }
957
+ }
958
+ async function invalidateTags(client, scope, tags) {
959
+ if (tags?.length === 0) return;
960
+ const matched = /* @__PURE__ */ new Set();
961
+ const pendingReads = [];
962
+ for (const query of client.getQueryCache().getAll()) {
963
+ const registration = registrationOf(query);
964
+ if (registration?.scope !== scope) continue;
965
+ const pending = reads.get(query);
966
+ const data = getTaggedReadData(client, query.queryKey);
967
+ const matches = tags === null || data === void 0 && pending === void 0 || data !== void 0 && registration.tagsOf(data).some((tag) => tags.includes(tag));
968
+ if (matches) registration.onInvalidate?.(data, tags);
969
+ if (pending !== void 0) {
970
+ if (matches) pending.restart = true;
971
+ else for (const tag of tags ?? []) pending.tags.add(tag);
972
+ if (query.isActive() && query.promise !== void 0)
973
+ pendingReads.push(query.promise);
974
+ }
975
+ if (matches) {
976
+ matched.add(query);
977
+ if (pending === void 0 && query.isActive() && query.state.fetchStatus === "fetching" && query.promise !== void 0) {
978
+ const refetch = () => client.invalidateQueries(
979
+ { predicate: (candidate) => candidate === query },
980
+ { cancelRefetch: false }
981
+ );
982
+ pendingReads.push(query.promise.then(refetch, refetch));
983
+ }
984
+ }
985
+ }
986
+ await Promise.allSettled([
987
+ client.invalidateQueries(
988
+ { predicate: (query) => matched.has(query) },
989
+ { cancelRefetch: false }
990
+ ),
991
+ ...pendingReads
992
+ ]);
993
+ }
994
+ async function executeTaggedMutation(invalidate, call, prediction) {
995
+ const { result, invalidated } = await call();
996
+ prediction?.accept(result);
997
+ const refresh = async () => {
998
+ try {
999
+ if (invalidate !== void 0 && invalidated.length > 0)
1000
+ await invalidate(invalidated);
1001
+ } finally {
1002
+ prediction?.settle();
1003
+ }
1004
+ };
1005
+ void refresh().catch(() => {
1006
+ });
1007
+ return result;
1008
+ }
1009
+ var pluginTagScope = (pluginId) => `plugin:${pluginId}`;
1010
+ function restartTaggedRead(query) {
1011
+ const pending = reads.get(query);
1012
+ if (pending) pending.restart = true;
1013
+ }
1014
+ function useTaggedMutation({
1015
+ client,
1016
+ invalidate,
1017
+ call,
1018
+ optimistic,
1019
+ meta
1020
+ }) {
1021
+ const [owner] = useState(() => ({}));
1022
+ const predict = useRef(optimistic);
1023
+ useEffect(() => {
1024
+ predict.current = optimistic;
1025
+ }, [optimistic]);
1026
+ const mutation = useMutation(
1027
+ {
1028
+ meta: { ...meta, taggedMutationOwner: owner },
1029
+ mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
1030
+ },
1031
+ client
1032
+ );
1033
+ const pendingInputs = useMutationState(
1034
+ {
1035
+ filters: {
1036
+ status: "pending",
1037
+ predicate: (entry) => entry.options.meta?.taggedMutationOwner === owner
1038
+ },
1039
+ select: (entry) => entry.state.variables.input
1040
+ },
1041
+ client
1042
+ );
1043
+ const { mutateAsync } = mutation;
1044
+ const mutate = useCallback(
1045
+ (input) => {
1046
+ const prediction = beginOptimisticMutation(
1047
+ client,
1048
+ predict.current?.(input) ?? []
1049
+ );
1050
+ return mutateAsync({ input, prediction }).catch((error) => {
1051
+ prediction.rollback();
1052
+ throw error;
1053
+ });
1054
+ },
1055
+ [client, mutateAsync]
1056
+ );
1057
+ return {
1058
+ mutate,
1059
+ pendingInputs,
1060
+ isPending: pendingInputs.length > 0,
1061
+ error: mutation.error,
1062
+ reset: mutation.reset
1063
+ };
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
+ }
1089
+ function createTaggedKeyedQueryOwner(options) {
1090
+ const { client, queryKey, scope, collection, read } = options;
1091
+ registerKeyedView(client, queryKey, keyedRowsView(collection));
1092
+ const keys = /* @__PURE__ */ new Map();
1093
+ let readingKeys = /* @__PURE__ */ new Set();
1094
+ let missingOnly = false;
1095
+ let refreshAll = false;
1096
+ const dirtyKeys = /* @__PURE__ */ new Set();
1097
+ const collectSubscribedKeys = () => new Promise((resolve) => {
1098
+ queueMicrotask(() => resolve([...keys.keys()]));
1099
+ });
1100
+ const observer = new QueryObserver(client, {
1101
+ queryKey,
1102
+ ...taggedQueryOptions(client, queryKey, {
1103
+ scope,
1104
+ tagsOf: (data) => [
1105
+ ...data.tags,
1106
+ ...Object.values(data.keyTags).flat()
1107
+ ],
1108
+ onInvalidate: (data, tags) => {
1109
+ if (tags === null || data === void 0 || data.tags.some((tag) => tags.includes(tag))) {
1110
+ refreshAll = true;
1111
+ } else {
1112
+ for (const [key, ownTags] of Object.entries(data.keyTags))
1113
+ if (ownTags.some((tag) => tags.includes(tag))) dirtyKeys.add(key);
1114
+ }
1115
+ }
1116
+ }),
1117
+ queryFn: () => {
1118
+ let previous = getTaggedReadData(client, queryKey);
1119
+ const startedAt = /* @__PURE__ */ new Map();
1120
+ let refresh = !missingOnly && dirtyKeys.size === 0;
1121
+ missingOnly = false;
1122
+ const refreshedKeys = /* @__PURE__ */ new Set();
1123
+ let refreshedAll = false;
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
+ )
1151
+ );
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)
1165
+ ])
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
+ });
1186
+ }
1187
+ });
1188
+ const listeners = /* @__PURE__ */ new Set();
1189
+ let stop;
1190
+ return {
1191
+ observer,
1192
+ subscribe(requested, listener) {
1193
+ let added = false;
1194
+ for (const key of requested) {
1195
+ if (!keys.has(key)) added = true;
1196
+ keys.set(key, (keys.get(key) ?? 0) + 1);
1197
+ }
1198
+ const cached = getTaggedReadData(client, queryKey);
1199
+ const missing = requested.filter(
1200
+ (key) => !Object.hasOwn(cached?.result ?? {}, key)
1201
+ );
1202
+ if (!stop) missingOnly = cached === void 0;
1203
+ listeners.add(listener);
1204
+ if (!stop) {
1205
+ stop = observer.subscribe(() => {
1206
+ for (const notify of listeners) notify();
1207
+ });
1208
+ }
1209
+ if (added && missing.length > 0) {
1210
+ if (observer.getCurrentResult().isFetching) {
1211
+ if (readingKeys.size > 0 && missing.some((key) => !readingKeys.has(key)))
1212
+ restartTaggedRead(observer.getCurrentQuery());
1213
+ } else {
1214
+ missingOnly = true;
1215
+ void observer.refetch({ cancelRefetch: false });
1216
+ }
1217
+ }
1218
+ return () => {
1219
+ listeners.delete(listener);
1220
+ for (const key of requested) {
1221
+ const count = (keys.get(key) ?? 1) - 1;
1222
+ if (count > 0) keys.set(key, count);
1223
+ else keys.delete(key);
1224
+ }
1225
+ queueMicrotask(() => {
1226
+ if (listeners.size === 0) {
1227
+ stop?.();
1228
+ stop = void 0;
1229
+ }
1230
+ });
1231
+ };
1232
+ }
1233
+ };
1234
+ }
1235
+ function useQuerySelection(subscribe, getSnapshot, select) {
1236
+ const committed = useRef(null);
1237
+ const getSelection = useMemo(() => {
1238
+ let cached;
1239
+ return () => {
1240
+ const snapshot = getSnapshot();
1241
+ if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
1242
+ cached = {
1243
+ snapshot,
1244
+ value: replaceEqualDeep3(
1245
+ cached?.value ?? committed.current?.value,
1246
+ select(snapshot)
1247
+ )
1248
+ };
1249
+ return cached.value;
1250
+ };
1251
+ }, [getSnapshot, select]);
1252
+ const value = useSyncExternalStore(subscribe, getSelection, getSelection);
1253
+ useEffect(() => {
1254
+ committed.current = { value };
1255
+ }, [value]);
1256
+ return value;
1257
+ }
1258
+
1259
+ // src/testing/app.tsx
1260
+ import { QueryClient } from "@tanstack/react-query";
1261
+
1262
+ // src/internal/rpc-query-host.ts
1263
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2 } from "react";
1264
+ import { useIsFetching } from "@tanstack/react-query";
1265
+
1266
+ // ../domain/src/json-value.ts
1267
+ import { z } from "zod";
1268
+ var jsonValueSchema = z.lazy(
1269
+ () => z.union([
1270
+ z.string(),
1271
+ z.number(),
1272
+ z.boolean(),
1273
+ z.null(),
1274
+ z.array(jsonValueSchema),
1275
+ z.record(z.string(), jsonValueSchema)
1276
+ ])
1277
+ );
1278
+ var jsonObjectSchema = z.record(
1279
+ z.string(),
1280
+ jsonValueSchema
1281
+ );
1282
+
1283
+ // src/internal/rpc-tags.ts
1284
+ import { z as z2 } from "zod";
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";
1300
+ var rpcQueryKey = (pluginId, method, input) => [
1301
+ "plugin-rpc",
1302
+ pluginId,
1303
+ method,
1304
+ input
1305
+ ];
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
+ }
1320
+ function optimisticCache(pluginId, updates) {
1321
+ return {
1322
+ update(method, input, update) {
1323
+ updates.push(
1324
+ optimisticQueryUpdate(
1325
+ rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
1326
+ parsedUpdate(update),
1327
+ ["result"]
1328
+ )
1329
+ );
1330
+ },
1331
+ updateKey(method, key, update) {
1332
+ updates.push(
1333
+ optimisticKeyedUpdate(
1334
+ keyedCollection(pluginId, method),
1335
+ key,
1336
+ parsedUpdate(update)
1337
+ )
1338
+ );
1339
+ }
1340
+ };
1341
+ }
1342
+ async function callRpc(host, pluginId, contract, method, input) {
1343
+ let raw;
1344
+ try {
1345
+ raw = await host.call(pluginId, method, input);
1346
+ } catch (error) {
1347
+ throw experimental_PluginRpcCallError.from(error);
1348
+ }
1349
+ const result = jsonValueSchema.safeParse(raw);
1350
+ if (!result.success)
1351
+ throw new experimental_PluginRpcCallError({
1352
+ code: "invalid_response",
1353
+ message: `Invalid RPC response for ${method}`
1354
+ });
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
+ };
1371
+ }
1372
+ var tagsOf = (data) => [
1373
+ ...data.tags,
1374
+ ...Object.values(data.keyTags).flat()
1375
+ ];
1376
+ var owners = /* @__PURE__ */ new WeakMap();
1377
+ function createRpcQueryHooks(useHost) {
1378
+ function useSubscription(host, pluginId, enabled) {
1379
+ useEffect2(
1380
+ () => enabled ? host.subscribe(pluginId) : void 0,
1381
+ [host, pluginId, enabled]
1382
+ );
1383
+ }
1384
+ const experimental_useRpcQuery = (options) => {
1385
+ const host = useHost();
1386
+ const pluginId = options.pluginId ?? host.pluginId;
1387
+ const input = jsonValueSchema.parse(options.input ?? null);
1388
+ const queryKey = rpcQueryKey(pluginId, options.method, input);
1389
+ useSubscription(host, pluginId, options.enabled ?? true);
1390
+ const query = useTaggedQuery(
1391
+ {
1392
+ queryKey,
1393
+ enabled: options.enabled,
1394
+ ...taggedQueryOptions(host.queryClient, queryKey, {
1395
+ scope: pluginTagScope(pluginId),
1396
+ tagsOf
1397
+ }),
1398
+ queryFn: () => runTaggedRead(
1399
+ host.queryClient,
1400
+ queryKey,
1401
+ async () => callRpc(
1402
+ host,
1403
+ pluginId,
1404
+ options.contract,
1405
+ options.method,
1406
+ input
1407
+ )
1408
+ )
1409
+ },
1410
+ host.queryClient
1411
+ );
1412
+ return {
1413
+ data: query.data?.result,
1414
+ error: query.error === null ? null : experimental_PluginRpcCallError.from(
1415
+ query.error,
1416
+ "invalid_response"
1417
+ ),
1418
+ isLoading: (options.enabled ?? true) && query.isLoading,
1419
+ isFetching: query.isFetching,
1420
+ refetch: async () => {
1421
+ await query.refetch();
1422
+ }
1423
+ };
1424
+ };
1425
+ function experimental_useRpcKeyedQuery(options) {
1426
+ const host = useHost();
1427
+ const pluginId = options.pluginId ?? host.pluginId;
1428
+ const enabled = options.enabled ?? true;
1429
+ const identity = JSON.stringify([...new Set(options.keys)].sort());
1430
+ const keys = useMemo2(
1431
+ () => z3.array(z3.string()).parse(JSON.parse(identity)),
1432
+ [identity]
1433
+ );
1434
+ let cache = owners.get(host.queryClient);
1435
+ if (!cache) {
1436
+ cache = /* @__PURE__ */ new Map();
1437
+ owners.set(host.queryClient, cache);
1438
+ }
1439
+ const id = JSON.stringify([pluginId, options.method]);
1440
+ let owner = cache.get(id);
1441
+ if (!owner) {
1442
+ owner = createTaggedKeyedQueryOwner({
1443
+ client: host.queryClient,
1444
+ queryKey: keyedQueryKey(pluginId, options.method),
1445
+ scope: pluginTagScope(pluginId),
1446
+ collection: keyedCollection(pluginId, options.method),
1447
+ read: async (keys2) => {
1448
+ const response = await callRpc(
1449
+ host,
1450
+ pluginId,
1451
+ options.contract,
1452
+ options.method,
1453
+ { keys: [...keys2] }
1454
+ );
1455
+ return {
1456
+ ...response,
1457
+ result: z3.record(z3.string(), jsonValueSchema).parse(response.result)
1458
+ };
1459
+ }
1460
+ });
1461
+ cache.set(id, owner);
1462
+ }
1463
+ const current = owner;
1464
+ useSubscription(host, pluginId, enabled && keys.length > 0);
1465
+ const subscribe = useCallback2(
1466
+ (listener) => enabled && keys.length > 0 ? current.subscribe(keys, listener) : () => {
1467
+ },
1468
+ [current, keys, enabled]
1469
+ );
1470
+ const getSnapshot = useCallback2(
1471
+ () => current.observer.getCurrentResult(),
1472
+ [current]
1473
+ );
1474
+ const { select: selectRows } = options;
1475
+ const select = useCallback2(
1476
+ (query2) => {
1477
+ const rows = query2.data?.result ?? {};
1478
+ const data = Object.fromEntries(
1479
+ keys.filter((key) => Object.hasOwn(rows, key)).map((key) => [key, rows[key]])
1480
+ );
1481
+ return {
1482
+ data: selectRows ? selectRows(data) : data,
1483
+ error: query2.error === null ? null : experimental_PluginRpcCallError.from(
1484
+ query2.error,
1485
+ "invalid_response"
1486
+ ),
1487
+ isLoading: enabled && keys.some((key) => !Object.hasOwn(rows, key)) && query2.isFetching,
1488
+ isFetching: query2.isFetching
1489
+ };
1490
+ },
1491
+ [keys, enabled, selectRows]
1492
+ );
1493
+ const query = useQuerySelection(subscribe, getSnapshot, select);
1494
+ const refetch = useCallback2(async () => {
1495
+ await current.observer.refetch();
1496
+ }, [current]);
1497
+ return {
1498
+ ...query,
1499
+ refetch
1500
+ };
1501
+ }
1502
+ function experimental_useRpcMutation(options) {
1503
+ const host = useHost();
1504
+ const pluginId = options.pluginId ?? host.pluginId;
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(
1510
+ host,
1511
+ pluginId,
1512
+ options.contract,
1513
+ options.method,
1514
+ jsonValueSchema.parse(input)
1515
+ );
1516
+ return {
1517
+ ...response,
1518
+ result: response.result
1519
+ };
1520
+ },
1521
+ optimistic: (input) => {
1522
+ const updates = [];
1523
+ options.optimistic?.(
1524
+ input,
1525
+ optimisticCache(pluginId, updates)
1526
+ );
1527
+ return updates;
1528
+ }
1529
+ });
1530
+ const { mutate } = mutation;
1531
+ return {
1532
+ ...mutation,
1533
+ error: mutation.error === null ? null : experimental_PluginRpcCallError.from(
1534
+ mutation.error,
1535
+ "invalid_input"
1536
+ ),
1537
+ mutate: useCallback2(
1538
+ async (...args) => {
1539
+ try {
1540
+ return await mutate(
1541
+ args[0] ?? null
1542
+ );
1543
+ } catch (error) {
1544
+ throw experimental_PluginRpcCallError.from(error);
1545
+ }
1546
+ },
1547
+ [mutate]
1548
+ )
1549
+ };
1550
+ }
1551
+ function experimental_useRpcRefresh() {
1552
+ const host = useHost();
1553
+ const isRefreshing = useIsFetching(
1554
+ { queryKey: ["plugin-rpc", host.pluginId] },
1555
+ host.queryClient
1556
+ ) > 0;
1557
+ return {
1558
+ isRefreshing,
1559
+ refresh: () => {
1560
+ void invalidateTags(
1561
+ host.queryClient,
1562
+ pluginTagScope(host.pluginId),
1563
+ null
1564
+ );
1565
+ }
1566
+ };
1567
+ }
1568
+ return {
1569
+ experimental_useRpcQuery,
1570
+ experimental_useRpcKeyedQuery,
1571
+ experimental_useRpcMutation,
1572
+ experimental_useRpcRefresh
1573
+ };
1574
+ }
1575
+
1576
+ // src/testing/app.tsx
1577
+ import * as React from "react";
1578
+ import {
1579
+ createContext,
1580
+ useCallback as useCallback3,
1581
+ useContext,
1582
+ useLayoutEffect,
1583
+ useEffect as useEffect3,
1584
+ useMemo as useMemo3,
1585
+ useRef as useRef2,
1586
+ useState as useState2,
1587
+ useSyncExternalStore as useSyncExternalStore2
1588
+ } from "react";
14
1589
  import { act, render } from "@testing-library/react";
15
1590
 
16
1591
  // src/internal/composer-view.ts
@@ -75,71 +1650,71 @@ function reconcileComposerMentions(currentText, nextText, mentions) {
75
1650
  }
76
1651
 
77
1652
  // src/internal/composer-draft-actions.ts
78
- import { z } from "zod";
1653
+ import { z as z4 } from "zod";
79
1654
  var range = {
80
- from: z.number().int().nonnegative(),
81
- to: z.number().int().nonnegative(),
82
- label: z.string()
1655
+ from: z4.number().int().nonnegative(),
1656
+ to: z4.number().int().nonnegative(),
1657
+ label: z4.string()
83
1658
  };
84
- var mentionSchema = z.discriminatedUnion("kind", [
85
- z.object({
1659
+ var mentionSchema = z4.discriminatedUnion("kind", [
1660
+ z4.object({
86
1661
  ...range,
87
- kind: z.literal("thread"),
88
- threadId: z.string(),
89
- projectId: z.string().optional()
1662
+ kind: z4.literal("thread"),
1663
+ threadId: z4.string(),
1664
+ projectId: z4.string().optional()
90
1665
  }),
91
- z.object({ ...range, kind: z.literal("project"), projectId: z.string() }),
92
- z.object({ ...range, kind: z.literal("section"), sectionId: z.string() }),
93
- z.object({
1666
+ z4.object({ ...range, kind: z4.literal("project"), projectId: z4.string() }),
1667
+ z4.object({ ...range, kind: z4.literal("section"), sectionId: z4.string() }),
1668
+ z4.object({
94
1669
  ...range,
95
- kind: z.literal("path"),
96
- path: z.string(),
97
- source: z.enum(["workspace", "thread-storage"]),
98
- entryKind: z.enum(["file", "directory"])
1670
+ kind: z4.literal("path"),
1671
+ path: z4.string(),
1672
+ source: z4.enum(["workspace", "thread-storage"]),
1673
+ entryKind: z4.enum(["file", "directory"])
99
1674
  }),
100
- z.object({
1675
+ z4.object({
101
1676
  ...range,
102
- kind: z.literal("command"),
103
- trigger: z.enum(["/", "$"]),
104
- name: z.string(),
105
- source: z.enum(["skill", "command"]),
106
- origin: z.enum(["builtin", "project", "user"]),
107
- argumentHint: z.string().nullable()
1677
+ kind: z4.literal("command"),
1678
+ trigger: z4.enum(["/", "$"]),
1679
+ name: z4.string(),
1680
+ source: z4.enum(["skill", "command"]),
1681
+ origin: z4.enum(["builtin", "project", "user"]),
1682
+ argumentHint: z4.string().nullable()
108
1683
  }),
109
- z.object({ ...range, kind: z.literal("attachment"), path: z.string() }),
110
- z.object({
1684
+ z4.object({ ...range, kind: z4.literal("attachment"), path: z4.string() }),
1685
+ z4.object({
111
1686
  ...range,
112
- kind: z.literal("plugin"),
113
- pluginId: z.string(),
114
- provider: z.string().min(1).refine((value) => !value.includes(":")),
115
- id: z.string(),
116
- icon: z.string().nullable().optional()
1687
+ kind: z4.literal("plugin"),
1688
+ pluginId: z4.string(),
1689
+ provider: z4.string().min(1).refine((value) => !value.includes(":")),
1690
+ id: z4.string(),
1691
+ icon: z4.string().nullable().optional()
117
1692
  })
118
1693
  ]);
119
1694
  var attachmentFields = {
120
- type: z.enum(["localImage", "localFile"]),
121
- path: z.string().min(1),
122
- name: z.string(),
123
- mimeType: z.string().optional(),
124
- sizeBytes: z.number().nonnegative().optional()
1695
+ type: z4.enum(["localImage", "localFile"]),
1696
+ path: z4.string().min(1),
1697
+ name: z4.string(),
1698
+ mimeType: z4.string().optional(),
1699
+ sizeBytes: z4.number().nonnegative().optional()
125
1700
  };
126
- var attachmentsSchema = z.array(
127
- z.union([
128
- z.object({
1701
+ var attachmentsSchema = z4.array(
1702
+ z4.union([
1703
+ z4.object({
129
1704
  ...attachmentFields,
130
- hostId: z.string().min(1),
131
- sourceProjectId: z.undefined().optional()
1705
+ hostId: z4.string().min(1),
1706
+ sourceProjectId: z4.undefined().optional()
132
1707
  }),
133
- z.object({
1708
+ z4.object({
134
1709
  ...attachmentFields,
135
- sourceProjectId: z.string().min(1).optional(),
136
- hostId: z.undefined().optional()
1710
+ sourceProjectId: z4.string().min(1).optional(),
1711
+ hostId: z4.undefined().optional()
137
1712
  })
138
1713
  ])
139
1714
  );
140
- var replacementSchema = z.object({
141
- text: z.string(),
142
- mentions: z.array(mentionSchema),
1715
+ var replacementSchema = z4.object({
1716
+ text: z4.string(),
1717
+ mentions: z4.array(mentionSchema),
143
1718
  attachments: attachmentsSchema.optional()
144
1719
  }).superRefine((draft, context) => {
145
1720
  let end = 0;
@@ -376,12 +1951,8 @@ function createComposerHandleBinding(key, initial) {
376
1951
  }
377
1952
  target().setDraft(appendComposerDraft(target().getDraft(), value, block));
378
1953
  };
379
- const submit = async (options) => {
1954
+ const submit = async (options = {}) => {
380
1955
  requireAvailable();
381
- const hostSubmit = target().submit;
382
- if (hostSubmit === void 0) {
383
- throw new Error("This composer cannot submit programmatically.");
384
- }
385
1956
  if (options.sendAt !== void 0 && (!Number.isFinite(options.sendAt) || options.sendAt <= Date.now())) {
386
1957
  throw new Error("Pick a time in the future.");
387
1958
  }
@@ -391,15 +1962,18 @@ function createComposerHandleBinding(key, initial) {
391
1962
  if (state.attachmentError !== null && state.attachmentError !== errorBefore) {
392
1963
  throw new Error(state.attachmentError);
393
1964
  }
394
- if (state.isSubmittingBlocked) {
395
- throw new Error(
396
- state.submittingBlockedReason ?? "This composer can't submit right now."
397
- );
398
- }
399
- await hostSubmit(
400
- options,
401
- options.experimental_data === void 0 ? void 0 : { pluginId: controller.pluginId, data: options.experimental_data }
402
- );
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;
403
1977
  };
404
1978
  const setSelection = async (selection) => {
405
1979
  requireAvailable();
@@ -966,24 +2540,8 @@ var experimental_THREAD_ACTION_GROUPS = {
966
2540
  lifecycle: "4_lifecycle"
967
2541
  };
968
2542
 
969
- // src/internal/plugin-app-collector.ts
970
- import { z as z2 } from "zod";
971
- var CODE_FENCE_LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]*$/;
2543
+ // src/internal/sidebar-footer-runtime.ts
972
2544
  var sidebarFooterCommandSequence = 0;
973
- var SIDEBAR_FOOTER_ACTION_KEYS = /* @__PURE__ */ new Set([
974
- "id",
975
- "label",
976
- "icon",
977
- "kind",
978
- "onActivate"
979
- ]);
980
- var SIDEBAR_FOOTER_DISCLOSURE_KEYS = /* @__PURE__ */ new Set([
981
- "id",
982
- "label",
983
- "icon",
984
- "kind",
985
- "component"
986
- ]);
987
2545
  var SidebarFooterItemRuntime = class {
988
2546
  listeners = /* @__PURE__ */ new Set();
989
2547
  snapshot = {
@@ -1029,6 +2587,25 @@ function adaptSidebarFooterAction(registration) {
1029
2587
  runtime: new SidebarFooterItemRuntime()
1030
2588
  };
1031
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
+ ]);
1032
2609
  var SidebarFooterCollector = class {
1033
2610
  constructor(collected, allCollected, seenIds) {
1034
2611
  this.collected = collected;
@@ -1090,18 +2667,18 @@ var SidebarFooterCollector = class {
1090
2667
  }
1091
2668
  }
1092
2669
  };
1093
- var NAV_PANEL_REGISTRATION_KEYS = new Set(
1094
- Object.keys({
1095
- id: true,
1096
- title: true,
1097
- icon: true,
1098
- path: true,
1099
- component: true,
1100
- fixedTabs: true,
1101
- experimental_useBadge: true,
1102
- headerContent: true
1103
- })
1104
- );
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
+ };
1105
2682
  var RENAMED_NAV_PANEL_KEYS = /* @__PURE__ */ new Map([
1106
2683
  ["experimental_fixedTabs", 'was renamed to "fixedTabs" in SDK 0.4.16']
1107
2684
  ]);
@@ -1113,7 +2690,7 @@ var RETIRED_NAV_PANEL_KEYS = /* @__PURE__ */ new Map([
1113
2690
  ]);
1114
2691
  function checkStaleNavPanelKeys(kind, registration, onWarning) {
1115
2692
  for (const key of Object.keys(registration)) {
1116
- if (NAV_PANEL_REGISTRATION_KEYS.has(key)) continue;
2693
+ if (Object.hasOwn(NAV_PANEL_REGISTRATION_KEYS, key)) continue;
1117
2694
  const renamed = RENAMED_NAV_PANEL_KEYS.get(key);
1118
2695
  if (renamed !== void 0) {
1119
2696
  throw new Error(`${kind}: "${key}" ${renamed}`);
@@ -1128,28 +2705,29 @@ function checkStaleNavPanelKeys(kind, registration, onWarning) {
1128
2705
  }
1129
2706
  }
1130
2707
  }
1131
- var commandShortcutSchema = z2.object({
1132
- key: z2.string().min(1).max(32).refine(
1133
- (key) => ![
1134
- "Alt",
1135
- "Control",
1136
- "Meta",
1137
- "OS",
1138
- "Shift",
1139
- "Dead",
1140
- "Unidentified"
1141
- ].includes(key)
1142
- ),
1143
- mod: z2.boolean().default(false),
1144
- meta: z2.boolean().default(false),
1145
- control: z2.boolean().default(false),
1146
- alt: z2.boolean().default(false),
1147
- shift: z2.boolean().default(false)
1148
- }).strict().refine(
1149
- (shortcut) => shortcut.mod || shortcut.meta || shortcut.control || shortcut.alt || /^F(?:[1-9]|1[0-9]|2[0-4])$/u.test(shortcut.key),
1150
- "Use Command, Control, or Alt with a key, or a function key"
1151
- );
1152
- 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
+ }
1153
2731
  function collectTitledComponent(kind, seen, registration) {
1154
2732
  const id = requireSlotId(kind, registration?.id);
1155
2733
  requireUniqueId(kind, seen, id);
@@ -1184,6 +2762,7 @@ function collectPanelAction(kind, seen, registration) {
1184
2762
  };
1185
2763
  }
1186
2764
  function collectPluginAppRegistrations(definition, onWarning = (message) => console.warn(message)) {
2765
+ const commandShortcutSchema = createCommandShortcutSchema();
1187
2766
  const sidebarFooterItems = [];
1188
2767
  const collected = {
1189
2768
  homepageSections: [],
@@ -1358,6 +2937,16 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
1358
2937
  `${kind}: "experimental_useBadge" must be a React hook function when set`
1359
2938
  );
1360
2939
  }
2940
+ if (registration.experimental_sidebar !== void 0 && typeof registration.experimental_sidebar !== "function") {
2941
+ throw new Error(
2942
+ `${kind}: "experimental_sidebar" must be a React component function when set`
2943
+ );
2944
+ }
2945
+ if (registration.experimental_usePageTitle !== void 0 && typeof registration.experimental_usePageTitle !== "function") {
2946
+ throw new Error(
2947
+ `${kind}: "experimental_usePageTitle" must be a React hook function when set`
2948
+ );
2949
+ }
1361
2950
  const fixedTabs = (() => {
1362
2951
  if (registration.fixedTabs === void 0) return [];
1363
2952
  if (!Array.isArray(registration.fixedTabs)) {
@@ -1418,6 +3007,10 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
1418
3007
  ...registration.experimental_useBadge !== void 0 ? {
1419
3008
  experimental_useBadge: registration.experimental_useBadge
1420
3009
  } : {},
3010
+ ...registration.experimental_usePageTitle !== void 0 ? {
3011
+ experimental_usePageTitle: registration.experimental_usePageTitle
3012
+ } : {},
3013
+ ...registration.experimental_sidebar !== void 0 ? { experimental_sidebar: registration.experimental_sidebar } : {},
1421
3014
  ...registration.headerContent !== void 0 ? { headerContent: registration.headerContent } : {}
1422
3015
  });
1423
3016
  },
@@ -1775,7 +3368,7 @@ function attachLegacySidebarHeaders(navigations, headers, onWarning) {
1775
3368
  }
1776
3369
 
1777
3370
  // src/testing/app.tsx
1778
- import { jsx, jsxs } from "react/jsx-runtime";
3371
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
1779
3372
  function TestSidebarNavigationIcon({
1780
3373
  icon,
1781
3374
  className
@@ -1874,7 +3467,7 @@ function SlotLifecycleGuard({
1874
3467
  children,
1875
3468
  onUnmount
1876
3469
  }) {
1877
- useEffect(() => () => onUnmount(), [onUnmount]);
3470
+ useEffect3(() => () => onUnmount(), [onUnmount]);
1878
3471
  return children;
1879
3472
  }
1880
3473
  var SlotEnvContext = createContext(null);
@@ -1934,7 +3527,7 @@ function useTestMenuOpenState({
1934
3527
  onOpenChange,
1935
3528
  onCloseAutoFocus
1936
3529
  }) {
1937
- const [open, setOpen] = useState(false);
3530
+ const [open, setOpen] = useState2(false);
1938
3531
  return {
1939
3532
  open,
1940
3533
  show: () => {
@@ -1958,7 +3551,7 @@ function TestThreadActionsMenu({
1958
3551
  onCloseAutoFocus
1959
3552
  }) {
1960
3553
  const menu = useTestMenuOpenState({ onOpenChange, onCloseAutoFocus });
1961
- const triggerElement = useRef(null);
3554
+ const triggerElement = useRef2(null);
1962
3555
  useLayoutEffect(() => {
1963
3556
  const element = triggerElement.current;
1964
3557
  if (element?.getAttribute("aria-haspopup") !== "menu") {
@@ -2179,7 +3772,7 @@ function TestNewThreadComposer({
2179
3772
  draftKey,
2180
3773
  onSubmit
2181
3774
  }) {
2182
- const [text, setText] = useState(initialPrompt ?? "");
3775
+ const [text, setText] = useState2(initialPrompt ?? "");
2183
3776
  return /* @__PURE__ */ jsxs(
2184
3777
  "div",
2185
3778
  {
@@ -2239,9 +3832,9 @@ function TestProviderModelPicker({
2239
3832
  disabled,
2240
3833
  className
2241
3834
  }) {
2242
- const [draft, setDraft] = useState(value);
3835
+ const [draft, setDraft] = useState2(value);
2243
3836
  const { providerId, model, reasoningLevel, serviceTier } = value;
2244
- useEffect(
3837
+ useEffect3(
2245
3838
  () => setDraft({
2246
3839
  providerId,
2247
3840
  model,
@@ -2469,16 +4062,17 @@ function captureClipboardWrites(result) {
2469
4062
  }
2470
4063
  var testPluginSdkApp = {
2471
4064
  definePluginApp,
4065
+ ...createRpcQueryHooks(() => useSlotEnv("rpc query").rpcQueryHost),
2472
4066
  useRpc() {
2473
4067
  return useSlotEnv("useRpc").rpcClient;
2474
4068
  },
2475
4069
  useRealtime(channel, handler) {
2476
4070
  const env = useSlotEnv("useRealtime");
2477
- const handlerRef = useRef(handler);
2478
- useEffect(() => {
4071
+ const handlerRef = useRef2(handler);
4072
+ useEffect3(() => {
2479
4073
  handlerRef.current = handler;
2480
4074
  });
2481
- useEffect(() => {
4075
+ useEffect3(() => {
2482
4076
  const listener = (payload) => handlerRef.current(payload);
2483
4077
  let listeners = env.realtimeHandlers.get(channel);
2484
4078
  if (!listeners) {
@@ -2495,7 +4089,7 @@ var testPluginSdkApp = {
2495
4089
  const connection = useSlotEnv(
2496
4090
  "useRealtimeConnectionState"
2497
4091
  ).realtimeConnection;
2498
- return useSyncExternalStore(
4092
+ return useSyncExternalStore2(
2499
4093
  connection.subscribe,
2500
4094
  connection.getSnapshot,
2501
4095
  connection.getSnapshot
@@ -2521,7 +4115,7 @@ var testPluginSdkApp = {
2521
4115
  },
2522
4116
  experimental_useFixedTabTarget(tab) {
2523
4117
  const store = useSlotEnv("experimental_useFixedTabTarget").fixedTabTarget;
2524
- const state = useSyncExternalStore(
4118
+ const state = useSyncExternalStore2(
2525
4119
  store.subscribe,
2526
4120
  store.getSnapshot,
2527
4121
  store.getSnapshot
@@ -2542,7 +4136,7 @@ var testPluginSdkApp = {
2542
4136
  },
2543
4137
  useComposer() {
2544
4138
  const composer = useSlotEnv("useComposer").composer;
2545
- useSyncExternalStore(
4139
+ useSyncExternalStore2(
2546
4140
  composer.subscribe,
2547
4141
  composer.getVersionSnapshot,
2548
4142
  composer.getVersionSnapshot
@@ -2551,7 +4145,7 @@ var testPluginSdkApp = {
2551
4145
  },
2552
4146
  useComposers() {
2553
4147
  const composer = useSlotEnv("useComposers").composer;
2554
- useSyncExternalStore(
4148
+ useSyncExternalStore2(
2555
4149
  composer.subscribe,
2556
4150
  composer.getVersionSnapshot,
2557
4151
  composer.getVersionSnapshot
@@ -2622,7 +4216,7 @@ var testPluginSdkApp = {
2622
4216
  const calls = useSlotEnv(
2623
4217
  "experimental_useArchiveEnvironmentThreads"
2624
4218
  ).environmentArchiveCalls;
2625
- return useCallback(
4219
+ return useCallback3(
2626
4220
  async (environmentId) => {
2627
4221
  calls.push(environmentId);
2628
4222
  },
@@ -2634,32 +4228,35 @@ var testPluginSdkApp = {
2634
4228
  },
2635
4229
  experimental_ThreadActionsMenu: TestThreadActionsMenu,
2636
4230
  experimental_ThreadActionsContextMenu: TestThreadActionsContextMenu,
4231
+ experimental_PluginRpcCallError,
2637
4232
  experimental_THREAD_ACTION_GROUPS,
2638
4233
  experimental_useSidebarNavigation() {
2639
4234
  return useSlotEnv("experimental_useSidebarNavigation").sidebarNavigation;
2640
4235
  },
2641
4236
  experimental_useSidebarNavigationSplit(itemId, _options) {
2642
4237
  const env = useSlotEnv("experimental_useSidebarNavigationSplit");
2643
- return useMemo(
4238
+ const kind = env.sidebarNavigation.items.find((item) => item.id === itemId)?.action.kind;
4239
+ const isAvailable = kind === "new-thread" || kind === "open-plugin-panel";
4240
+ return useMemo3(
2644
4241
  () => ({
2645
- splitProps: {
4242
+ splitProps: isAvailable ? {
2646
4243
  onPointerDown: () => {
2647
4244
  env.sidebarNavigationCalls.push({
2648
4245
  method: "beginSplitDrag",
2649
4246
  itemId
2650
4247
  });
2651
4248
  }
2652
- },
2653
- isAvailable: true,
4249
+ } : {},
4250
+ isAvailable,
2654
4251
  layout: null
2655
4252
  }),
2656
- [env, itemId]
4253
+ [env, isAvailable, itemId]
2657
4254
  );
2658
4255
  },
2659
4256
  experimental_SidebarNavigationIcon: TestSidebarNavigationIcon,
2660
4257
  experimental_useSidebarThreadSplit(threadId) {
2661
4258
  const env = useSlotEnv("experimental_useSidebarThreadSplit");
2662
- return useMemo(
4259
+ return useMemo3(
2663
4260
  () => ({
2664
4261
  splitProps: {
2665
4262
  onPointerDown: () => {
@@ -2674,7 +4271,7 @@ var testPluginSdkApp = {
2674
4271
  },
2675
4272
  useSidebarThreadDraft(threadId) {
2676
4273
  const env = useSlotEnv("useSidebarThreadDraft");
2677
- return useMemo(
4274
+ return useMemo3(
2678
4275
  () => ({ hasUnsubmittedDraft: env.sidebarDraftThreadIds.has(threadId) }),
2679
4276
  [env, threadId]
2680
4277
  );
@@ -2706,7 +4303,7 @@ var testPluginSdkApp = {
2706
4303
  },
2707
4304
  experimental_useSidebarThreadPullRequest(threadId) {
2708
4305
  const env = useSlotEnv("experimental_useSidebarThreadPullRequest");
2709
- return useMemo(
4306
+ return useMemo3(
2710
4307
  () => ({
2711
4308
  isLoading: false,
2712
4309
  pullRequest: env.sidebarPullRequests.get(threadId) ?? null
@@ -2716,12 +4313,12 @@ var testPluginSdkApp = {
2716
4313
  },
2717
4314
  useComposerView() {
2718
4315
  const composer = useSlotEnv("useComposerView").composer;
2719
- const version = useSyncExternalStore(
4316
+ const version = useSyncExternalStore2(
2720
4317
  composer.subscribe,
2721
4318
  composer.getVersionSnapshot,
2722
4319
  composer.getVersionSnapshot
2723
4320
  );
2724
- return useMemo(() => {
4321
+ return useMemo3(() => {
2725
4322
  const text = composer.getText();
2726
4323
  const attachmentCount = composer.getAttachmentCount();
2727
4324
  return {
@@ -2895,19 +4492,39 @@ function renderSlot(registration, props, options = {}) {
2895
4492
  installTestPluginRuntime();
2896
4493
  const rpcCalls = [];
2897
4494
  const rpcHandlers = options.rpc ?? {};
2898
- const rpcClient = {
2899
- async call(method, input) {
2900
- const normalizedInput = input === void 0 ? null : strictJsonRoundTrip(input, `rpc "${method}" input`);
2901
- rpcCalls.push({ method, input: normalizedInput });
2902
- const handler = rpcHandlers[method];
2903
- if (!handler) {
2904
- throw new Error(
2905
- `no rpc handler for "${method}" \u2014 add it to renderSlot options.rpc`
2906
- );
2907
- }
2908
- const result2 = await handler(normalizedInput);
2909
- return strictJsonRoundTrip(result2, `rpc "${method}" result`);
4495
+ const parseRpcValue = async (schema, value, code) => {
4496
+ const parsed = await schema["~standard"].validate(value);
4497
+ if (parsed.issues !== void 0)
4498
+ throw new experimental_PluginRpcCallError({
4499
+ code,
4500
+ message: parsed.issues.map((issue) => issue.message).join("; ")
4501
+ });
4502
+ return parsed.value;
4503
+ };
4504
+ const queryClient = new QueryClient();
4505
+ const callRpc2 = async (method, input) => {
4506
+ const normalizedInput = input === void 0 ? null : strictJsonRoundTrip(input, `rpc "${method}" input`);
4507
+ rpcCalls.push({ method, input: normalizedInput });
4508
+ const handler = rpcHandlers[method];
4509
+ if (!handler) {
4510
+ throw new experimental_PluginRpcCallError({
4511
+ code: "unknown_method",
4512
+ message: `no rpc handler for "${method}" \u2014 add it to renderSlot options.rpc`
4513
+ });
4514
+ }
4515
+ const declaration = options.experimental_rpcContract?.[method];
4516
+ const parsedInput = declaration ? await parseRpcValue(declaration.input, normalizedInput, "invalid_input") : normalizedInput;
4517
+ let result2;
4518
+ try {
4519
+ result2 = await handler(parsedInput);
4520
+ } catch (error) {
4521
+ throw experimental_PluginRpcCallError.from(error, "handler_error");
2910
4522
  }
4523
+ const parsedOutput = declaration ? await parseRpcValue(declaration.output, result2, "invalid_output") : result2;
4524
+ return strictJsonRoundTrip(parsedOutput, `rpc "${method}" result`);
4525
+ };
4526
+ const rpcClient = {
4527
+ call: (method, input) => callRpc2(method, input)
2911
4528
  };
2912
4529
  const realtimeHandlers = /* @__PURE__ */ new Map();
2913
4530
  let realtimeConnectionState = options.realtimeConnectionState ?? "connected";
@@ -3001,11 +4618,14 @@ function renderSlot(registration, props, options = {}) {
3001
4618
  sidebarNavigationCalls.push({
3002
4619
  method: "activate",
3003
4620
  itemId,
3004
- openInSplit: activationOptions.openInSplit
4621
+ target: activationOptions.target
3005
4622
  });
3006
4623
  },
3007
- goHome() {
3008
- sidebarNavigationCalls.push({ method: "goHome" });
4624
+ goHome(activationOptions) {
4625
+ sidebarNavigationCalls.push({
4626
+ method: "goHome",
4627
+ target: activationOptions?.target ?? "current"
4628
+ });
3009
4629
  },
3010
4630
  setVisible(itemId, isVisible) {
3011
4631
  sidebarNavigationCalls.push({
@@ -3295,6 +4915,17 @@ ${block}
3295
4915
  },
3296
4916
  subscribeEditorState: () => () => {
3297
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
+ },
3298
4929
  insertAtCursor(value, block) {
3299
4930
  composerTarget.setDraft(
3300
4931
  appendComposerDraft(composerDraft(), value, block)
@@ -3305,11 +4936,6 @@ ${block}
3305
4936
  focus() {
3306
4937
  composerLog.focusCount += 1;
3307
4938
  },
3308
- async submit(submitOptions) {
3309
- composerLog.submits.push(submitOptions);
3310
- commitComposerDraft("", []);
3311
- for (const listener of submissionListeners) listener();
3312
- },
3313
4939
  async setSelection(selection) {
3314
4940
  if (composerScope.kind === "queued-message") {
3315
4941
  throw new Error("This composer has no pickers to set.");
@@ -3393,7 +5019,15 @@ ${block}
3393
5019
  return () => composerListeners.delete(listener);
3394
5020
  }
3395
5021
  };
5022
+ const rpcQueryHost = {
5023
+ pluginId: options.pluginId ?? "test-plugin",
5024
+ queryClient,
5025
+ subscribe: () => () => {
5026
+ },
5027
+ call: (_pluginId, method, input) => callRpc2(method, input)
5028
+ };
3396
5029
  const env = {
5030
+ rpcQueryHost,
3397
5031
  rpcClient,
3398
5032
  rpcCalls,
3399
5033
  realtimeHandlers,
@@ -3453,7 +5087,19 @@ ${block}
3453
5087
  composerLog.textEffect = null;
3454
5088
  composerLog.inputLocked = false;
3455
5089
  };
3456
- const renderSlotTree = (ui) => /* @__PURE__ */ jsx(SlotEnvContext.Provider, { value: env, children: /* @__PURE__ */ jsx(SlotLifecycleGuard, { onUnmount: releaseComposerOwnership, children: ui }) });
5090
+ let pageTitle = null;
5091
+ const usePageTitle = registration.experimental_usePageTitle;
5092
+ function SlotPageTitle({ children }) {
5093
+ const value = usePageTitle ? usePageTitle(props) : null;
5094
+ useLayoutEffect(() => {
5095
+ pageTitle = value;
5096
+ return () => {
5097
+ pageTitle = null;
5098
+ };
5099
+ }, [value]);
5100
+ return /* @__PURE__ */ jsx(Fragment, { children });
5101
+ }
5102
+ const renderSlotTree = (ui) => /* @__PURE__ */ jsx(SlotEnvContext.Provider, { value: env, children: /* @__PURE__ */ jsx(SlotLifecycleGuard, { onUnmount: releaseComposerOwnership, children: /* @__PURE__ */ jsx(SlotPageTitle, { children: ui }) }) });
3457
5103
  const Component = registration.component;
3458
5104
  const element = renderSlotTree(/* @__PURE__ */ jsx(Component, { ...props }));
3459
5105
  const result = render(element);
@@ -3481,6 +5127,15 @@ ${block}
3481
5127
  notifyComposerListeners();
3482
5128
  });
3483
5129
  };
5130
+ const experimental_invalidateRpc = async (tags) => {
5131
+ await act(async () => {
5132
+ await invalidateTags(
5133
+ queryClient,
5134
+ pluginTagScope(rpcQueryHost.pluginId),
5135
+ tags
5136
+ );
5137
+ });
5138
+ };
3484
5139
  const unmountSlot = () => {
3485
5140
  if (!composerOwnership.active) return;
3486
5141
  result.unmount();
@@ -3490,6 +5145,7 @@ ${block}
3490
5145
  rerender: rerenderSlot,
3491
5146
  unmount: unmountSlot,
3492
5147
  rpcCalls,
5148
+ experimental_invalidateRpc,
3493
5149
  emitRealtime,
3494
5150
  setRealtimeConnectionState,
3495
5151
  setComposerText: setComposerText2,
@@ -3503,12 +5159,16 @@ ${block}
3503
5159
  experimental_clipboardWrites,
3504
5160
  composer: composerLog,
3505
5161
  behavior: {
5162
+ experimental_invalidateRpc,
3506
5163
  emitRealtime,
3507
5164
  setRealtimeConnectionState,
3508
5165
  setComposerText: setComposerText2,
3509
5166
  setComposerScope
3510
5167
  },
3511
5168
  inspection: {
5169
+ get experimental_pageTitle() {
5170
+ return pageTitle;
5171
+ },
3512
5172
  rpcCalls,
3513
5173
  navigateCalls,
3514
5174
  experimental_fixedTabOpenCalls,
@@ -3519,6 +5179,9 @@ ${block}
3519
5179
  experimental_clipboardWrites,
3520
5180
  composer: composerLog
3521
5181
  },
5182
+ get experimental_pageTitle() {
5183
+ return pageTitle;
5184
+ },
3522
5185
  lifecycle: { rerender: rerenderSlot, unmount: unmountSlot }
3523
5186
  };
3524
5187
  }