@get-bb/plugin-sdk 0.6.59 → 0.6.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,922 @@
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
+ // src/internal/rpc-query-host.ts
83
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2 } from "react";
84
+ import { useIsFetching } from "@tanstack/react-query";
85
+
86
+ // ../query-tags/src/index.ts
87
+ import {
88
+ useCallback,
89
+ useEffect,
90
+ useMemo,
91
+ useRef,
92
+ useState,
93
+ useSyncExternalStore
94
+ } from "react";
95
+ import {
96
+ QueryObserver,
97
+ useQuery,
98
+ useQueryClient,
99
+ useMutation,
100
+ useMutationState,
101
+ replaceEqualDeep as replaceEqualDeep2
102
+ } from "@tanstack/react-query";
103
+
104
+ // ../query-tags/src/optimistic.ts
105
+ import {
106
+ notifyManager,
107
+ replaceEqualDeep
108
+ } from "@tanstack/react-query";
109
+ function optimisticQueryUpdate(queryKey, update, path = []) {
110
+ return {
111
+ queryKey,
112
+ path: [...path],
113
+ update: (current) => update(current)
114
+ };
115
+ }
116
+ var predictions = /* @__PURE__ */ new WeakMap();
117
+ var receipts = /* @__PURE__ */ new WeakMap();
118
+ var order = 0;
119
+ function valueAt(data, path) {
120
+ let value = data;
121
+ for (const key of path) {
122
+ if (typeof value !== "object" || value === null || !Object.hasOwn(value, key))
123
+ return;
124
+ value = Reflect.get(value, key);
125
+ }
126
+ return value === void 0 ? void 0 : { value };
127
+ }
128
+ function replaceAt(data, path, value) {
129
+ const [key, ...rest] = path;
130
+ if (key === void 0) return value;
131
+ if (typeof data !== "object" || data === null) return data;
132
+ const next = Array.isArray(data) ? [...data] : { ...data };
133
+ Reflect.set(next, key, replaceAt(Reflect.get(data, key), rest, value));
134
+ return next;
135
+ }
136
+ function prefix(left, right) {
137
+ return left.length <= right.length && left.every((part, index) => part === right[index]);
138
+ }
139
+ function olderPending(state, layer) {
140
+ return state.layers.some(
141
+ (other) => other.order < layer.order && !other.settled && (prefix(other.path, layer.path) || prefix(layer.path, other.path))
142
+ );
143
+ }
144
+ function confirmedValue(current, predicted, confirmed) {
145
+ if (Object.is(predicted, confirmed)) return current;
146
+ 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))
147
+ return confirmed;
148
+ const next = Array.isArray(current) ? [...current] : { ...current };
149
+ for (const key of /* @__PURE__ */ new Set([
150
+ ...Object.keys(predicted),
151
+ ...Object.keys(confirmed)
152
+ ])) {
153
+ if (!Object.hasOwn(confirmed, key)) Reflect.deleteProperty(next, key);
154
+ else
155
+ Reflect.set(
156
+ next,
157
+ key,
158
+ confirmedValue(
159
+ Reflect.get(current, key),
160
+ Reflect.get(predicted, key),
161
+ Reflect.get(confirmed, key)
162
+ )
163
+ );
164
+ }
165
+ return next;
166
+ }
167
+ function projected(state) {
168
+ return state.layers.reduce((data, layer) => {
169
+ const current = valueAt(data, layer.path);
170
+ return replaceAt(
171
+ data,
172
+ layer.path,
173
+ layer.update(current === void 0 ? layer.initial : current.value)
174
+ );
175
+ }, state.base);
176
+ }
177
+ var predictionListeners = /* @__PURE__ */ new WeakMap();
178
+ function subscribeOptimisticQuery(query, listener) {
179
+ if (query === void 0) return () => {
180
+ };
181
+ let listeners = predictionListeners.get(query);
182
+ if (listeners === void 0) {
183
+ listeners = /* @__PURE__ */ new Set();
184
+ predictionListeners.set(query, listeners);
185
+ }
186
+ listeners.add(listener);
187
+ return () => {
188
+ listeners.delete(listener);
189
+ if (listeners.size === 0) predictionListeners.delete(query);
190
+ };
191
+ }
192
+ function publish(query, state) {
193
+ query.setState({
194
+ data: replaceEqualDeep(query.state.data, projected(state))
195
+ });
196
+ if (state.layers.length === 0) predictions.delete(query);
197
+ for (const listener of predictionListeners.get(query) ?? []) listener();
198
+ }
199
+ function taggedReadReceipt(query) {
200
+ const paths = [];
201
+ return {
202
+ start: () => ++order,
203
+ record(started, loaded) {
204
+ paths.push(...loaded.map((path) => ({ path, started })));
205
+ },
206
+ commit(data) {
207
+ receipts.set(query, { data, paths });
208
+ }
209
+ };
210
+ }
211
+ function taggedStructuralSharing(client, queryKey, previous, next) {
212
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
213
+ const state = query === void 0 ? void 0 : predictions.get(query);
214
+ if (query !== void 0) {
215
+ const receipt = receipts.get(query);
216
+ if (receipt !== void 0 && Object.is(receipt.data, next)) {
217
+ receipts.delete(query);
218
+ if (state !== void 0) {
219
+ const refreshed = /* @__PURE__ */ new Set();
220
+ for (const layer of state.layers) {
221
+ if (layer.acceptedAt !== null && receipt.paths.some(
222
+ ({ path, started }) => started > layer.acceptedAt && prefix(path, layer.path)
223
+ )) {
224
+ layer.fresh = true;
225
+ refreshed.add(layer);
226
+ }
227
+ }
228
+ state.layers = state.layers.filter(
229
+ (layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
230
+ );
231
+ }
232
+ }
233
+ if (state !== void 0) {
234
+ state.base = next;
235
+ next = projected(state);
236
+ if (state.layers.length === 0) predictions.delete(query);
237
+ }
238
+ }
239
+ const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
240
+ return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep(previous, next);
241
+ }
242
+ function getTaggedReadData(client, queryKey) {
243
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
244
+ const state = query === void 0 ? void 0 : predictions.get(query);
245
+ return state === void 0 ? query?.state.data : state.base;
246
+ }
247
+ function beginOptimisticMutation(client, updates) {
248
+ const owner = {};
249
+ const mutationOrder = ++order;
250
+ let accepted = false;
251
+ const affected = /* @__PURE__ */ new Map();
252
+ const rollback = () => notifyManager.batch(() => {
253
+ if (accepted) return;
254
+ for (const [query, state] of affected) {
255
+ state.layers = state.layers.filter((layer) => layer.owner !== owner);
256
+ publish(query, state);
257
+ }
258
+ });
259
+ try {
260
+ notifyManager.batch(() => {
261
+ for (const update of updates) {
262
+ const query = client.getQueryCache().get(
263
+ client.defaultQueryOptions({ queryKey: update.queryKey }).queryHash
264
+ );
265
+ if (query === void 0 || query.state.data === void 0) continue;
266
+ const state = predictions.get(query) ?? {
267
+ base: query.state.data,
268
+ layers: []
269
+ };
270
+ const current = valueAt(projected(state), update.path);
271
+ if (current === void 0) continue;
272
+ state.layers.push({
273
+ owner,
274
+ order: mutationOrder,
275
+ path: update.path,
276
+ initial: current.value,
277
+ update: update.update,
278
+ acceptedAt: null,
279
+ fresh: false,
280
+ settled: false
281
+ });
282
+ predictions.set(query, state);
283
+ affected.set(query, state);
284
+ publish(query, state);
285
+ }
286
+ });
287
+ } catch (error) {
288
+ rollback();
289
+ throw error;
290
+ }
291
+ return {
292
+ rollback,
293
+ accept() {
294
+ accepted = true;
295
+ const acceptedAt = ++order;
296
+ for (const state of affected.values())
297
+ for (const layer of state.layers)
298
+ if (layer.owner === owner) layer.acceptedAt = acceptedAt;
299
+ },
300
+ settle() {
301
+ notifyManager.batch(() => {
302
+ for (const [query, state] of affected) {
303
+ state.layers = state.layers.filter((layer) => {
304
+ if (layer.owner !== owner) return true;
305
+ layer.settled = true;
306
+ if (!layer.fresh) return true;
307
+ if (!olderPending(state, layer)) return false;
308
+ const current = valueAt(state.base, layer.path);
309
+ if (current !== void 0) {
310
+ const update = layer.update;
311
+ const predicted = update(current.value);
312
+ layer.update = (value) => confirmedValue(update(value), predicted, current.value);
313
+ }
314
+ return true;
315
+ });
316
+ publish(query, state);
317
+ }
318
+ });
319
+ }
320
+ };
321
+ }
322
+
323
+ // ../query-tags/src/index.ts
324
+ function useTaggedQuery(options, client) {
325
+ const queryClient = useQueryClient(client);
326
+ const result = useQuery(options, queryClient);
327
+ const query = queryClient.getQueryCache().get(queryClient.defaultQueryOptions(options).queryHash);
328
+ const subscribed = options.subscribed !== false;
329
+ const subscribe = useCallback(
330
+ (listener) => subscribed ? subscribeOptimisticQuery(query, listener) : () => {
331
+ },
332
+ [query, subscribed]
333
+ );
334
+ const snapshot = useCallback(() => query?.state.data, [query]);
335
+ useSyncExternalStore(subscribe, snapshot, snapshot);
336
+ return result;
337
+ }
338
+ var registrations = /* @__PURE__ */ new WeakMap();
339
+ var reads = /* @__PURE__ */ new WeakMap();
340
+ function taggedQueryOptions(client, queryKey, registration) {
341
+ const meta = {};
342
+ registrations.set(meta, {
343
+ scope: registration.scope,
344
+ tagsOf: (data) => registration.tagsOf(data),
345
+ onInvalidate: (data, tags) => registration.onInvalidate?.(data, tags)
346
+ });
347
+ return {
348
+ meta,
349
+ structuralSharing: (previous, next) => taggedStructuralSharing(client, queryKey, previous, next)
350
+ };
351
+ }
352
+ function registrationOf(query) {
353
+ return query.meta === void 0 ? void 0 : registrations.get(query.meta);
354
+ }
355
+ async function runTaggedRead(client, queryKey, read, paths = () => [[]]) {
356
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
357
+ if (query === void 0) return read();
358
+ const registration = registrationOf(query);
359
+ const receipt = taggedReadReceipt(query);
360
+ for (; ; ) {
361
+ const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
362
+ reads.set(query, pending);
363
+ const started = receipt.start();
364
+ try {
365
+ const result = await read();
366
+ receipt.record(started, paths());
367
+ const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
368
+ if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
369
+ if (pending.restart || overlap) continue;
370
+ receipt.commit(result);
371
+ return result;
372
+ } catch (error) {
373
+ if (pending.restart) continue;
374
+ throw error;
375
+ } finally {
376
+ if (reads.get(query) === pending) reads.delete(query);
377
+ }
378
+ }
379
+ }
380
+ async function invalidateTags(client, scope, tags) {
381
+ if (tags?.length === 0) return;
382
+ const matched = /* @__PURE__ */ new Set();
383
+ const pendingReads = [];
384
+ for (const query of client.getQueryCache().getAll()) {
385
+ const registration = registrationOf(query);
386
+ if (registration?.scope !== scope) continue;
387
+ const pending = reads.get(query);
388
+ const data = getTaggedReadData(client, query.queryKey);
389
+ const matches = tags === null || data === void 0 && pending === void 0 || data !== void 0 && registration.tagsOf(data).some((tag) => tags.includes(tag));
390
+ if (matches) registration.onInvalidate?.(data, tags);
391
+ if (pending !== void 0) {
392
+ if (matches) pending.restart = true;
393
+ else for (const tag of tags ?? []) pending.tags.add(tag);
394
+ if (query.isActive() && query.promise !== void 0)
395
+ pendingReads.push(query.promise);
396
+ }
397
+ if (matches) {
398
+ matched.add(query);
399
+ if (pending === void 0 && query.isActive() && query.state.fetchStatus === "fetching" && query.promise !== void 0) {
400
+ const refetch = () => client.invalidateQueries(
401
+ { predicate: (candidate) => candidate === query },
402
+ { cancelRefetch: false }
403
+ );
404
+ pendingReads.push(query.promise.then(refetch, refetch));
405
+ }
406
+ }
407
+ }
408
+ await Promise.allSettled([
409
+ client.invalidateQueries(
410
+ { predicate: (query) => matched.has(query) },
411
+ { cancelRefetch: false }
412
+ ),
413
+ ...pendingReads
414
+ ]);
415
+ }
416
+ async function executeTaggedMutation(invalidate, call, prediction) {
417
+ const { result, invalidated } = await call();
418
+ prediction?.accept();
419
+ const refresh = async () => {
420
+ try {
421
+ if (invalidated.length > 0) await invalidate(invalidated);
422
+ } finally {
423
+ prediction?.settle();
424
+ }
425
+ };
426
+ void refresh().catch(() => {
427
+ });
428
+ return result;
429
+ }
430
+ var pluginTagScope = (pluginId) => `plugin:${pluginId}`;
431
+ function restartTaggedRead(query) {
432
+ const pending = reads.get(query);
433
+ if (pending) pending.restart = true;
434
+ }
435
+ function useTaggedMutation(client, invalidate, call, optimistic) {
436
+ const [owner] = useState(() => ({}));
437
+ const predict = useRef(optimistic);
438
+ useEffect(() => {
439
+ predict.current = optimistic;
440
+ }, [optimistic]);
441
+ const mutation = useMutation(
442
+ {
443
+ meta: { taggedMutationOwner: owner },
444
+ mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
445
+ },
446
+ client
447
+ );
448
+ const pendingInputs = useMutationState(
449
+ {
450
+ filters: {
451
+ status: "pending",
452
+ predicate: (entry) => entry.options.meta?.taggedMutationOwner === owner
453
+ },
454
+ select: (entry) => entry.state.variables.input
455
+ },
456
+ client
457
+ );
458
+ const { mutateAsync } = mutation;
459
+ const mutate = useCallback(
460
+ (input) => {
461
+ const prediction = beginOptimisticMutation(
462
+ client,
463
+ predict.current?.(input) ?? []
464
+ );
465
+ return mutateAsync({ input, prediction }).catch((error) => {
466
+ prediction.rollback();
467
+ throw error;
468
+ });
469
+ },
470
+ [client, mutateAsync]
471
+ );
472
+ return {
473
+ mutate,
474
+ pendingInputs,
475
+ isPending: pendingInputs.length > 0,
476
+ error: mutation.error,
477
+ reset: mutation.reset
478
+ };
479
+ }
480
+ function createTaggedKeyedQueryOwner(options) {
481
+ const { client, queryKey, scope, read } = options;
482
+ const keys = /* @__PURE__ */ new Map();
483
+ let readingKeys = /* @__PURE__ */ new Set();
484
+ let missingOnly = false;
485
+ let refreshAll = false;
486
+ const dirtyKeys = /* @__PURE__ */ new Set();
487
+ const collectSubscribedKeys = () => new Promise((resolve) => {
488
+ queueMicrotask(() => resolve([...keys.keys()]));
489
+ });
490
+ const observer = new QueryObserver(client, {
491
+ queryKey,
492
+ ...taggedQueryOptions(client, queryKey, {
493
+ scope,
494
+ tagsOf: (data) => [
495
+ ...data.tags,
496
+ ...Object.values(data.keyTags).flat()
497
+ ],
498
+ onInvalidate: (data, tags) => {
499
+ if (tags === null || data === void 0 || data.tags.some((tag) => tags.includes(tag))) {
500
+ refreshAll = true;
501
+ } else {
502
+ for (const [key, ownTags] of Object.entries(data.keyTags))
503
+ if (ownTags.some((tag) => tags.includes(tag))) dirtyKeys.add(key);
504
+ }
505
+ }
506
+ }),
507
+ queryFn: () => {
508
+ let previous = getTaggedReadData(client, queryKey);
509
+ let loaded = [];
510
+ let refresh = !missingOnly && dirtyKeys.size === 0;
511
+ missingOnly = false;
512
+ const refreshedKeys = /* @__PURE__ */ new Set();
513
+ let refreshedAll = false;
514
+ return runTaggedRead(
515
+ client,
516
+ queryKey,
517
+ async () => {
518
+ const subscribed = await collectSubscribedKeys();
519
+ const all = refreshAll || refresh;
520
+ refresh = false;
521
+ const dirty = new Set(dirtyKeys);
522
+ for (const key of dirty) refreshedKeys.add(key);
523
+ refreshedAll ||= all;
524
+ dirtyKeys.clear();
525
+ refreshAll = false;
526
+ const requested = subscribed.filter(
527
+ (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
528
+ );
529
+ readingKeys = new Set(requested);
530
+ try {
531
+ const results = await Promise.all(
532
+ Array.from(
533
+ { length: Math.ceil(requested.length / 200) },
534
+ async (_, i) => {
535
+ const batch = requested.slice(i * 200, (i + 1) * 200);
536
+ const response = await read(batch);
537
+ for (const key of batch)
538
+ if (!Object.hasOwn(response.result, key))
539
+ throw new Error(`Keyed read omitted key ${key}`);
540
+ return response;
541
+ }
542
+ )
543
+ );
544
+ const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
545
+ loaded = requested;
546
+ previous = {
547
+ result: Object.fromEntries([
548
+ ...Object.entries(previous?.result ?? {}).filter(
549
+ ([key]) => retained(key)
550
+ ),
551
+ ...results.flatMap(
552
+ (response) => Object.entries(response.result)
553
+ )
554
+ ]),
555
+ tags: [
556
+ .../* @__PURE__ */ new Set([
557
+ ...all ? [] : previous?.tags ?? [],
558
+ ...results.flatMap((r) => r.tags)
559
+ ])
560
+ ],
561
+ keyTags: Object.fromEntries([
562
+ ...Object.entries(previous?.keyTags ?? {}).filter(
563
+ ([key]) => retained(key)
564
+ ),
565
+ ...results.flatMap(
566
+ (response) => Object.entries(response.keyTags)
567
+ )
568
+ ])
569
+ };
570
+ return previous;
571
+ } catch (error) {
572
+ for (const key of refreshedKeys) dirtyKeys.add(key);
573
+ refreshAll ||= refreshedAll;
574
+ throw error;
575
+ }
576
+ },
577
+ () => loaded.map((key) => ["result", key])
578
+ );
579
+ }
580
+ });
581
+ const listeners = /* @__PURE__ */ new Set();
582
+ let stop;
583
+ return {
584
+ observer,
585
+ subscribe(requested, listener) {
586
+ let added = false;
587
+ for (const key of requested) {
588
+ if (!keys.has(key)) added = true;
589
+ keys.set(key, (keys.get(key) ?? 0) + 1);
590
+ }
591
+ const cached = getTaggedReadData(client, queryKey);
592
+ const missing = requested.filter(
593
+ (key) => !Object.hasOwn(cached?.result ?? {}, key)
594
+ );
595
+ if (!stop) missingOnly = cached === void 0;
596
+ listeners.add(listener);
597
+ if (!stop) {
598
+ stop = observer.subscribe(() => {
599
+ for (const notify of listeners) notify();
600
+ });
601
+ }
602
+ if (added && missing.length > 0) {
603
+ if (observer.getCurrentResult().isFetching) {
604
+ if (readingKeys.size > 0 && missing.some((key) => !readingKeys.has(key)))
605
+ restartTaggedRead(observer.getCurrentQuery());
606
+ } else {
607
+ missingOnly = true;
608
+ void observer.refetch({ cancelRefetch: false });
609
+ }
610
+ }
611
+ return () => {
612
+ listeners.delete(listener);
613
+ for (const key of requested) {
614
+ const count = (keys.get(key) ?? 1) - 1;
615
+ if (count > 0) keys.set(key, count);
616
+ else keys.delete(key);
617
+ }
618
+ queueMicrotask(() => {
619
+ if (listeners.size === 0) {
620
+ stop?.();
621
+ stop = void 0;
622
+ }
623
+ });
624
+ };
625
+ }
626
+ };
627
+ }
628
+ function useQuerySelection(subscribe, getSnapshot, select) {
629
+ const committed = useRef(null);
630
+ const getSelection = useMemo(() => {
631
+ let cached;
632
+ return () => {
633
+ const snapshot = getSnapshot();
634
+ if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
635
+ cached = {
636
+ snapshot,
637
+ value: replaceEqualDeep2(
638
+ cached?.value ?? committed.current?.value,
639
+ select(snapshot)
640
+ )
641
+ };
642
+ return cached.value;
643
+ };
644
+ }, [getSnapshot, select]);
645
+ const value = useSyncExternalStore(subscribe, getSelection, getSelection);
646
+ useEffect(() => {
647
+ committed.current = { value };
648
+ }, [value]);
649
+ return value;
650
+ }
651
+
652
+ // ../domain/src/json-value.ts
653
+ import { z } from "zod";
654
+ var jsonValueSchema = z.lazy(
655
+ () => z.union([
656
+ z.string(),
657
+ z.number(),
658
+ z.boolean(),
659
+ z.null(),
660
+ z.array(jsonValueSchema),
661
+ z.record(z.string(), jsonValueSchema)
662
+ ])
663
+ );
664
+ var jsonObjectSchema = z.record(
665
+ z.string(),
666
+ jsonValueSchema
667
+ );
668
+
669
+ // src/internal/rpc-query-host.ts
670
+ import { z as z2 } from "zod";
671
+ var envelopeSchema = z2.object({
672
+ result: jsonValueSchema,
673
+ tags: z2.array(z2.string()).default([]),
674
+ keyTags: z2.record(z2.string(), z2.array(z2.string())).default({}),
675
+ invalidated: z2.array(z2.string()).default([])
676
+ });
677
+ var rpcQueryKey = (pluginId, method, input) => [
678
+ "plugin-rpc",
679
+ pluginId,
680
+ method,
681
+ input
682
+ ];
683
+ var keyedQueryKey = (pluginId, method) => rpcQueryKey(pluginId, method, { keyed: true });
684
+ function optimisticCache(pluginId, updates) {
685
+ const add = (prediction) => {
686
+ updates.push({
687
+ ...prediction,
688
+ update: (current) => jsonValueSchema.parse(prediction.update(current))
689
+ });
690
+ };
691
+ return {
692
+ update(method, input, update) {
693
+ add(
694
+ optimisticQueryUpdate(
695
+ rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
696
+ update,
697
+ ["result"]
698
+ )
699
+ );
700
+ },
701
+ updateKey(method, key, update) {
702
+ add(
703
+ optimisticQueryUpdate(keyedQueryKey(pluginId, method), update, [
704
+ "result",
705
+ key
706
+ ])
707
+ );
708
+ }
709
+ };
710
+ }
711
+ async function callRpcEnvelope(host, pluginId, method, input) {
712
+ let raw;
713
+ try {
714
+ raw = await host.call(pluginId, method, input);
715
+ } catch (error) {
716
+ throw experimental_PluginRpcCallError.from(error);
717
+ }
718
+ const parsed = envelopeSchema.safeParse(raw);
719
+ if (!parsed.success)
720
+ throw new experimental_PluginRpcCallError({
721
+ code: "invalid_response",
722
+ message: `Invalid RPC response for ${method}`
723
+ });
724
+ return parsed.data;
725
+ }
726
+ var tagsOf = (data) => [
727
+ ...data.tags,
728
+ ...Object.values(data.keyTags).flat()
729
+ ];
730
+ var owners = /* @__PURE__ */ new WeakMap();
731
+ function createRpcQueryHooks(useHost) {
732
+ function useSubscription(host, pluginId, enabled) {
733
+ useEffect2(
734
+ () => enabled ? host.subscribe(pluginId) : void 0,
735
+ [host, pluginId, enabled]
736
+ );
737
+ }
738
+ const experimental_useRpcQuery = (options) => {
739
+ const host = useHost();
740
+ const pluginId = options.pluginId ?? host.pluginId;
741
+ const input = jsonValueSchema.parse(options.input ?? null);
742
+ const queryKey = rpcQueryKey(pluginId, options.method, input);
743
+ useSubscription(host, pluginId, options.enabled ?? true);
744
+ const query = useTaggedQuery(
745
+ {
746
+ queryKey,
747
+ enabled: options.enabled,
748
+ ...taggedQueryOptions(host.queryClient, queryKey, {
749
+ scope: pluginTagScope(pluginId),
750
+ tagsOf
751
+ }),
752
+ queryFn: () => runTaggedRead(
753
+ host.queryClient,
754
+ queryKey,
755
+ async () => callRpcEnvelope(host, pluginId, options.method, input)
756
+ )
757
+ },
758
+ host.queryClient
759
+ );
760
+ return {
761
+ data: query.data?.result,
762
+ error: query.error === null ? null : experimental_PluginRpcCallError.from(
763
+ query.error,
764
+ "invalid_response"
765
+ ),
766
+ isLoading: (options.enabled ?? true) && query.isLoading,
767
+ isFetching: query.isFetching,
768
+ refetch: async () => {
769
+ await query.refetch();
770
+ }
771
+ };
772
+ };
773
+ function experimental_useRpcKeyedQuery(options) {
774
+ const host = useHost();
775
+ const pluginId = options.pluginId ?? host.pluginId;
776
+ const enabled = options.enabled ?? true;
777
+ const identity = JSON.stringify([...new Set(options.keys)].sort());
778
+ const keys = useMemo2(
779
+ () => z2.array(z2.string()).parse(JSON.parse(identity)),
780
+ [identity]
781
+ );
782
+ let cache = owners.get(host.queryClient);
783
+ if (!cache) {
784
+ cache = /* @__PURE__ */ new Map();
785
+ owners.set(host.queryClient, cache);
786
+ }
787
+ const id = JSON.stringify([pluginId, options.method]);
788
+ let owner = cache.get(id);
789
+ if (!owner) {
790
+ owner = createTaggedKeyedQueryOwner({
791
+ client: host.queryClient,
792
+ queryKey: keyedQueryKey(pluginId, options.method),
793
+ scope: pluginTagScope(pluginId),
794
+ read: async (keys2) => {
795
+ const response = await callRpcEnvelope(
796
+ host,
797
+ pluginId,
798
+ options.method,
799
+ { keys: [...keys2] }
800
+ );
801
+ return {
802
+ ...response,
803
+ result: z2.record(z2.string(), jsonValueSchema).parse(response.result)
804
+ };
805
+ }
806
+ });
807
+ cache.set(id, owner);
808
+ }
809
+ const current = owner;
810
+ useSubscription(host, pluginId, enabled && keys.length > 0);
811
+ const subscribe = useCallback2(
812
+ (listener) => enabled && keys.length > 0 ? current.subscribe(keys, listener) : () => {
813
+ },
814
+ [current, keys, enabled]
815
+ );
816
+ const getSnapshot = useCallback2(
817
+ () => current.observer.getCurrentResult(),
818
+ [current]
819
+ );
820
+ const { select: selectRows } = options;
821
+ const select = useCallback2(
822
+ (query2) => {
823
+ const rows = query2.data?.result ?? {};
824
+ const data = Object.fromEntries(
825
+ keys.filter((key) => Object.hasOwn(rows, key)).map((key) => [key, rows[key]])
826
+ );
827
+ return {
828
+ data: selectRows ? selectRows(data) : data,
829
+ error: query2.error === null ? null : experimental_PluginRpcCallError.from(
830
+ query2.error,
831
+ "invalid_response"
832
+ ),
833
+ isLoading: enabled && keys.some((key) => !Object.hasOwn(rows, key)) && query2.isFetching,
834
+ isFetching: query2.isFetching
835
+ };
836
+ },
837
+ [keys, enabled, selectRows]
838
+ );
839
+ const query = useQuerySelection(subscribe, getSnapshot, select);
840
+ const refetch = useCallback2(async () => {
841
+ await current.observer.refetch();
842
+ }, [current]);
843
+ return {
844
+ ...query,
845
+ refetch
846
+ };
847
+ }
848
+ function experimental_useRpcMutation(options) {
849
+ const host = useHost();
850
+ const pluginId = options.pluginId ?? host.pluginId;
851
+ const mutation = useTaggedMutation(
852
+ host.queryClient,
853
+ (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
854
+ async (input) => {
855
+ const response = await callRpcEnvelope(
856
+ host,
857
+ pluginId,
858
+ options.method,
859
+ jsonValueSchema.parse(input)
860
+ );
861
+ return {
862
+ ...response,
863
+ result: response.result
864
+ };
865
+ },
866
+ (input) => {
867
+ const updates = [];
868
+ options.optimistic?.(
869
+ input,
870
+ optimisticCache(pluginId, updates)
871
+ );
872
+ return updates;
873
+ }
874
+ );
875
+ const { mutate } = mutation;
876
+ return {
877
+ ...mutation,
878
+ error: mutation.error === null ? null : experimental_PluginRpcCallError.from(
879
+ mutation.error,
880
+ "invalid_input"
881
+ ),
882
+ mutate: useCallback2(
883
+ async (...args) => {
884
+ try {
885
+ return await mutate(
886
+ args[0] ?? null
887
+ );
888
+ } catch (error) {
889
+ throw experimental_PluginRpcCallError.from(error);
890
+ }
891
+ },
892
+ [mutate]
893
+ )
894
+ };
895
+ }
896
+ function experimental_useRpcRefresh() {
897
+ const host = useHost();
898
+ const isRefreshing = useIsFetching(
899
+ { queryKey: ["plugin-rpc", host.pluginId] },
900
+ host.queryClient
901
+ ) > 0;
902
+ return {
903
+ isRefreshing,
904
+ refresh: () => {
905
+ void invalidateTags(
906
+ host.queryClient,
907
+ pluginTagScope(host.pluginId),
908
+ null
909
+ );
910
+ }
911
+ };
912
+ }
913
+ return {
914
+ experimental_useRpcQuery,
915
+ experimental_useRpcKeyedQuery,
916
+ experimental_useRpcMutation,
917
+ experimental_useRpcRefresh
918
+ };
919
+ }
920
+ export {
921
+ createRpcQueryHooks
922
+ };