@almadar/ui 1.0.1 → 1.0.11

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,2834 @@
1
+ import { apiClient } from './chunk-XSEDIUM6.js';
2
+ import { useEventBus, SelectionContext } from './chunk-TTXKOHDO.js';
3
+ import { subscribe, getSnapshot, clearEntities, removeEntity, updateSingleton, updateEntity, spawnEntity, getSingleton, getAllEntities, getByType, getEntity } from './chunk-N7MVUW4R.js';
4
+ import { __privateAdd, __privateGet, __privateSet, __privateMethod } from './chunk-S7EYY36U.js';
5
+ import * as React6 from 'react';
6
+ import { useCallback, useState, useEffect, useMemo, useContext, useSyncExternalStore } from 'react';
7
+ import 'react/jsx-runtime';
8
+
9
+ function useOrbitalHistory(options) {
10
+ const { appId, authToken, userId, onHistoryChange, onRevertSuccess } = options;
11
+ const getHeaders = useCallback(() => {
12
+ const headers = {
13
+ "Content-Type": "application/json"
14
+ };
15
+ if (authToken) {
16
+ headers["Authorization"] = `Bearer ${authToken}`;
17
+ }
18
+ if (userId) {
19
+ headers["x-user-id"] = userId;
20
+ }
21
+ return headers;
22
+ }, [authToken, userId]);
23
+ const [timeline, setTimeline] = useState([]);
24
+ const [currentVersion, setCurrentVersion] = useState(1);
25
+ const [isLoading, setIsLoading] = useState(false);
26
+ const [error, setError] = useState(null);
27
+ const refresh = useCallback(async () => {
28
+ if (!appId) return;
29
+ setIsLoading(true);
30
+ setError(null);
31
+ try {
32
+ const headers = getHeaders();
33
+ const [changesetsRes, snapshotsRes] = await Promise.all([
34
+ fetch(`/api/graphs/${appId}/history/changesets`, { headers }),
35
+ fetch(`/api/graphs/${appId}/history/snapshots`, { headers })
36
+ ]);
37
+ if (!changesetsRes.ok) {
38
+ throw new Error(`Failed to fetch changesets: ${changesetsRes.status}`);
39
+ }
40
+ if (!snapshotsRes.ok) {
41
+ throw new Error(`Failed to fetch snapshots: ${snapshotsRes.status}`);
42
+ }
43
+ const changesetsData = await changesetsRes.json();
44
+ const snapshotsData = await snapshotsRes.json();
45
+ const changesetItems = (changesetsData.changesets || []).map((cs) => ({
46
+ id: cs.id,
47
+ type: "changeset",
48
+ version: cs.version,
49
+ timestamp: cs.timestamp,
50
+ description: `Version ${cs.version}`,
51
+ source: cs.source,
52
+ summary: cs.summary
53
+ }));
54
+ const snapshotItems = (snapshotsData.snapshots || []).map((snap) => ({
55
+ id: snap.id,
56
+ type: "snapshot",
57
+ version: snap.version,
58
+ timestamp: snap.timestamp,
59
+ description: snap.reason || `Snapshot v${snap.version}`,
60
+ reason: snap.reason
61
+ }));
62
+ const mergedTimeline = [...changesetItems, ...snapshotItems].sort(
63
+ (a, b) => b.timestamp - a.timestamp
64
+ );
65
+ setTimeline(mergedTimeline);
66
+ if (mergedTimeline.length > 0) {
67
+ setCurrentVersion(mergedTimeline[0].version);
68
+ }
69
+ } catch (err) {
70
+ console.error("[useOrbitalHistory] Failed to load history:", err);
71
+ setError(err instanceof Error ? err.message : "Failed to load history");
72
+ } finally {
73
+ setIsLoading(false);
74
+ }
75
+ }, [appId, getHeaders]);
76
+ const revertToSnapshot = useCallback(async (snapshotId) => {
77
+ if (!appId) {
78
+ return { success: false, error: "No app ID provided" };
79
+ }
80
+ try {
81
+ const response = await fetch(`/api/graphs/${appId}/history/revert/${snapshotId}`, {
82
+ method: "POST",
83
+ headers: getHeaders()
84
+ });
85
+ if (!response.ok) {
86
+ const errorData = await response.json().catch(() => ({}));
87
+ throw new Error(errorData.error || `Failed to revert: ${response.status}`);
88
+ }
89
+ const data = await response.json();
90
+ if (data.success && data.schema) {
91
+ await refresh();
92
+ onRevertSuccess?.(data.schema);
93
+ return {
94
+ success: true,
95
+ restoredSchema: data.schema
96
+ };
97
+ }
98
+ return {
99
+ success: false,
100
+ error: data.error || "Unknown error during revert"
101
+ };
102
+ } catch (err) {
103
+ console.error("[useOrbitalHistory] Failed to revert:", err);
104
+ return {
105
+ success: false,
106
+ error: err instanceof Error ? err.message : "Failed to revert"
107
+ };
108
+ }
109
+ }, [appId, getHeaders, refresh, onRevertSuccess]);
110
+ useEffect(() => {
111
+ if (appId && authToken && userId) {
112
+ refresh();
113
+ }
114
+ }, [appId, authToken, userId]);
115
+ useEffect(() => {
116
+ onHistoryChange?.(timeline);
117
+ }, [timeline]);
118
+ return {
119
+ timeline,
120
+ currentVersion,
121
+ isLoading,
122
+ error,
123
+ revertToSnapshot,
124
+ refresh
125
+ };
126
+ }
127
+ function useFileSystem() {
128
+ const [status, setStatus] = useState("idle");
129
+ const [error, setError] = useState(null);
130
+ const [isLoading, setIsLoading] = useState(false);
131
+ const [files, setFiles] = useState([]);
132
+ const [selectedFile, setSelectedFile] = useState(null);
133
+ const [selectedPath, setSelectedPath] = useState(null);
134
+ const [previewUrl, setPreviewUrl] = useState(null);
135
+ const [fileContents, setFileContents] = useState(/* @__PURE__ */ new Map());
136
+ const boot = useCallback(async () => {
137
+ setStatus("booting");
138
+ setError(null);
139
+ setIsLoading(true);
140
+ try {
141
+ console.log("[useFileSystem] Booting WebContainer...");
142
+ await new Promise((resolve) => setTimeout(resolve, 100));
143
+ setStatus("ready");
144
+ } catch (err) {
145
+ setError(err instanceof Error ? err.message : "Failed to boot");
146
+ setStatus("error");
147
+ } finally {
148
+ setIsLoading(false);
149
+ }
150
+ }, []);
151
+ const mountFiles = useCallback(async (filesToMount) => {
152
+ setIsLoading(true);
153
+ try {
154
+ let filesArray;
155
+ if (Array.isArray(filesToMount)) {
156
+ filesArray = filesToMount;
157
+ } else {
158
+ filesArray = [];
159
+ const flattenTree = (obj, basePath = "") => {
160
+ for (const [key, value] of Object.entries(obj)) {
161
+ const path = basePath ? `${basePath}/${key}` : key;
162
+ if (value && typeof value === "object" && "file" in value) {
163
+ const fileObj = value;
164
+ filesArray.push({ path, content: fileObj.file.contents || "" });
165
+ } else if (value && typeof value === "object" && "directory" in value) {
166
+ const dirObj = value;
167
+ flattenTree(dirObj.directory, path);
168
+ }
169
+ }
170
+ };
171
+ flattenTree(filesToMount);
172
+ }
173
+ const newContents = /* @__PURE__ */ new Map();
174
+ for (const file of filesArray) {
175
+ newContents.set(file.path, file.content);
176
+ }
177
+ setFileContents(newContents);
178
+ const newTree = [];
179
+ for (const file of filesArray) {
180
+ const parts = file.path.split("/").filter(Boolean);
181
+ let current = newTree;
182
+ for (let i = 0; i < parts.length; i++) {
183
+ const part = parts[i];
184
+ const isFile = i === parts.length - 1;
185
+ const currentPath = "/" + parts.slice(0, i + 1).join("/");
186
+ let node = current.find((n) => n.name === part);
187
+ if (!node) {
188
+ node = {
189
+ path: currentPath,
190
+ name: part,
191
+ type: isFile ? "file" : "directory",
192
+ children: isFile ? void 0 : []
193
+ };
194
+ current.push(node);
195
+ }
196
+ if (!isFile && node && node.children) {
197
+ current = node.children;
198
+ }
199
+ }
200
+ }
201
+ setFiles(newTree);
202
+ setStatus("running");
203
+ } catch (err) {
204
+ console.error("[useFileSystem] Failed to mount files:", err);
205
+ } finally {
206
+ setIsLoading(false);
207
+ }
208
+ }, []);
209
+ const readFile = useCallback(async (path) => {
210
+ return fileContents.get(path) || "";
211
+ }, [fileContents]);
212
+ const writeFile = useCallback(async (path, content) => {
213
+ setFileContents((prev) => {
214
+ const next = new Map(prev);
215
+ next.set(path, content);
216
+ return next;
217
+ });
218
+ }, []);
219
+ const selectFile = useCallback(async (path) => {
220
+ const content = fileContents.get(path) || "";
221
+ const ext = path.split(".").pop()?.toLowerCase() || "";
222
+ const languageMap = {
223
+ ts: "typescript",
224
+ tsx: "typescript",
225
+ js: "javascript",
226
+ jsx: "javascript",
227
+ json: "json",
228
+ md: "markdown",
229
+ css: "css",
230
+ html: "html",
231
+ orb: "json"
232
+ };
233
+ setSelectedPath(path);
234
+ setSelectedFile({
235
+ path,
236
+ content,
237
+ language: languageMap[ext] || "plaintext",
238
+ isDirty: false
239
+ });
240
+ }, [fileContents]);
241
+ const updateContent = useCallback((pathOrContent, contentArg) => {
242
+ const path = contentArg !== void 0 ? pathOrContent : selectedPath;
243
+ const content = contentArg !== void 0 ? contentArg : pathOrContent;
244
+ if (!path) {
245
+ console.warn("[useFileSystem] updateContent called without path and no file selected");
246
+ return;
247
+ }
248
+ setFileContents((prev) => {
249
+ const next = new Map(prev);
250
+ next.set(path, content);
251
+ return next;
252
+ });
253
+ if (selectedPath === path) {
254
+ setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
255
+ }
256
+ }, [selectedPath]);
257
+ const updateSelectedContent = useCallback((content) => {
258
+ setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
259
+ }, []);
260
+ const refreshTree = useCallback(async () => {
261
+ console.log("[useFileSystem] Refreshing tree");
262
+ }, []);
263
+ const runCommand = useCallback(async (command) => {
264
+ console.log("[useFileSystem] Running command:", command);
265
+ return { exitCode: 0, output: "" };
266
+ }, []);
267
+ const startDevServer = useCallback(async () => {
268
+ console.log("[useFileSystem] Starting dev server");
269
+ setPreviewUrl("http://localhost:5173");
270
+ }, []);
271
+ return {
272
+ status,
273
+ error,
274
+ isLoading,
275
+ files,
276
+ selectedFile,
277
+ selectedPath,
278
+ previewUrl,
279
+ boot,
280
+ mountFiles,
281
+ readFile,
282
+ writeFile,
283
+ selectFile,
284
+ updateContent,
285
+ updateSelectedContent,
286
+ refreshTree,
287
+ runCommand,
288
+ startDevServer
289
+ };
290
+ }
291
+ var defaultManifest = {
292
+ languages: {
293
+ typescript: { extensions: [".ts", ".tsx"], icon: "ts", color: "#3178c6" },
294
+ javascript: { extensions: [".js", ".jsx"], icon: "js", color: "#f7df1e" },
295
+ json: { extensions: [".json", ".orb"], icon: "json", color: "#000000" },
296
+ css: { extensions: [".css"], icon: "css", color: "#264de4" },
297
+ html: { extensions: [".html"], icon: "html", color: "#e34c26" },
298
+ markdown: { extensions: [".md", ".mdx"], icon: "md", color: "#083fa1" }
299
+ },
300
+ extensions: []
301
+ };
302
+ function useExtensions(options) {
303
+ const { appId, loadOnMount = true } = options;
304
+ const [extensions, setExtensions] = useState([]);
305
+ const [manifest] = useState(defaultManifest);
306
+ const [isLoading, setIsLoading] = useState(false);
307
+ const [error, setError] = useState(null);
308
+ const loadExtension = useCallback(async (extensionId) => {
309
+ console.log("[useExtensions] Loading extension:", extensionId);
310
+ }, []);
311
+ const loadExtensions = useCallback(async () => {
312
+ setIsLoading(true);
313
+ setError(null);
314
+ try {
315
+ const defaultExtensions = [
316
+ { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
317
+ { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
318
+ { id: "json", name: "JSON", language: "json", loaded: true },
319
+ { id: "css", name: "CSS", language: "css", loaded: true },
320
+ { id: "html", name: "HTML", language: "html", loaded: true },
321
+ { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
322
+ ];
323
+ setExtensions(defaultExtensions);
324
+ } catch (err) {
325
+ setError(err instanceof Error ? err.message : "Failed to load extensions");
326
+ } finally {
327
+ setIsLoading(false);
328
+ }
329
+ }, []);
330
+ const getExtensionForFile = useCallback((filename) => {
331
+ const ext = filename.split(".").pop()?.toLowerCase();
332
+ if (!ext) return null;
333
+ const languageMap = {
334
+ ts: "typescript",
335
+ tsx: "typescript",
336
+ js: "javascript",
337
+ jsx: "javascript",
338
+ json: "json",
339
+ md: "markdown",
340
+ css: "css",
341
+ html: "html",
342
+ orb: "json"
343
+ };
344
+ const language = languageMap[ext];
345
+ if (!language) return null;
346
+ return extensions.find((e) => e.language === language) || null;
347
+ }, [extensions]);
348
+ useEffect(() => {
349
+ if (!appId || !loadOnMount) return;
350
+ const loadExtensions2 = async () => {
351
+ setIsLoading(true);
352
+ setError(null);
353
+ try {
354
+ const defaultExtensions = [
355
+ { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
356
+ { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
357
+ { id: "json", name: "JSON", language: "json", loaded: true },
358
+ { id: "css", name: "CSS", language: "css", loaded: true },
359
+ { id: "html", name: "HTML", language: "html", loaded: true },
360
+ { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
361
+ ];
362
+ setExtensions(defaultExtensions);
363
+ } catch (err) {
364
+ setError(err instanceof Error ? err.message : "Failed to load extensions");
365
+ } finally {
366
+ setIsLoading(false);
367
+ }
368
+ };
369
+ loadExtensions2();
370
+ }, [appId, loadOnMount]);
371
+ return {
372
+ extensions,
373
+ manifest,
374
+ isLoading,
375
+ error,
376
+ loadExtension,
377
+ loadExtensions,
378
+ getExtensionForFile
379
+ };
380
+ }
381
+ function useFileEditor(options) {
382
+ const { extensions, fileSystem, onSchemaUpdate } = options;
383
+ const [openFiles, setOpenFiles] = useState([]);
384
+ const [activeFilePath, setActiveFilePath] = useState(null);
385
+ const [isSaving, setIsSaving] = useState(false);
386
+ const activeFile = openFiles.find((f) => f.path === activeFilePath) || null;
387
+ const openFile = useCallback(async (path) => {
388
+ const existing = openFiles.find((f) => f.path === path);
389
+ if (existing) {
390
+ setActiveFilePath(path);
391
+ return;
392
+ }
393
+ try {
394
+ const content = await fileSystem.readFile(path);
395
+ const ext = extensions.getExtensionForFile(path);
396
+ const newFile = {
397
+ path,
398
+ content,
399
+ isDirty: false,
400
+ language: ext?.language
401
+ };
402
+ setOpenFiles((prev) => [...prev, newFile]);
403
+ setActiveFilePath(path);
404
+ } catch (err) {
405
+ console.error("[useFileEditor] Failed to open file:", err);
406
+ }
407
+ }, [openFiles, fileSystem, extensions]);
408
+ const closeFile = useCallback((path) => {
409
+ setOpenFiles((prev) => prev.filter((f) => f.path !== path));
410
+ if (activeFilePath === path) {
411
+ const remaining = openFiles.filter((f) => f.path !== path);
412
+ setActiveFilePath(remaining.length > 0 ? remaining[0].path : null);
413
+ }
414
+ }, [activeFilePath, openFiles]);
415
+ const setActiveFile = useCallback((path) => {
416
+ setActiveFilePath(path);
417
+ }, []);
418
+ const updateFileContent = useCallback((path, content) => {
419
+ setOpenFiles(
420
+ (prev) => prev.map(
421
+ (f) => f.path === path ? { ...f, content, isDirty: true } : f
422
+ )
423
+ );
424
+ }, []);
425
+ const handleFileEdit = useCallback(async (path, content) => {
426
+ try {
427
+ await fileSystem.writeFile(path, content);
428
+ let action = "saved";
429
+ if (path.endsWith(".orb") || path.endsWith("schema.json")) {
430
+ try {
431
+ const schema = JSON.parse(content);
432
+ await onSchemaUpdate?.(schema);
433
+ action = "updated_schema";
434
+ } catch {
435
+ }
436
+ } else if (path.includes("/extensions/")) {
437
+ action = path.endsWith(".new") ? "converted_extension" : "saved_extension";
438
+ }
439
+ return { success: true, action };
440
+ } catch (err) {
441
+ return {
442
+ success: false,
443
+ error: err instanceof Error ? err.message : "Failed to save file"
444
+ };
445
+ }
446
+ }, [fileSystem, onSchemaUpdate]);
447
+ const saveFile = useCallback(async (path) => {
448
+ const file = openFiles.find((f) => f.path === path);
449
+ if (!file) return;
450
+ setIsSaving(true);
451
+ try {
452
+ await fileSystem.writeFile(path, file.content);
453
+ setOpenFiles(
454
+ (prev) => prev.map(
455
+ (f) => f.path === path ? { ...f, isDirty: false } : f
456
+ )
457
+ );
458
+ if (path.endsWith(".orb") || path.endsWith("schema.json")) {
459
+ try {
460
+ const schema = JSON.parse(file.content);
461
+ await onSchemaUpdate?.(schema);
462
+ } catch {
463
+ }
464
+ }
465
+ } catch (err) {
466
+ console.error("[useFileEditor] Failed to save file:", err);
467
+ } finally {
468
+ setIsSaving(false);
469
+ }
470
+ }, [openFiles, fileSystem, onSchemaUpdate]);
471
+ const saveAllFiles = useCallback(async () => {
472
+ setIsSaving(true);
473
+ try {
474
+ const dirtyFiles = openFiles.filter((f) => f.isDirty);
475
+ for (const file of dirtyFiles) {
476
+ await saveFile(file.path);
477
+ }
478
+ } finally {
479
+ setIsSaving(false);
480
+ }
481
+ }, [openFiles, saveFile]);
482
+ return {
483
+ openFiles,
484
+ activeFile,
485
+ isSaving,
486
+ openFile,
487
+ closeFile,
488
+ setActiveFile,
489
+ updateFileContent,
490
+ handleFileEdit,
491
+ saveFile,
492
+ saveAllFiles
493
+ };
494
+ }
495
+ function useCompile() {
496
+ const [isCompiling, setIsCompiling] = useState(false);
497
+ const [stage, setStage] = useState("idle");
498
+ const [lastResult, setLastResult] = useState(null);
499
+ const [error, setError] = useState(null);
500
+ const compileSchema = useCallback(async (schema) => {
501
+ setIsCompiling(true);
502
+ setStage("compiling");
503
+ setError(null);
504
+ try {
505
+ console.log("[useCompile] Compiling schema:", schema.name);
506
+ const result = {
507
+ success: true,
508
+ files: []
509
+ };
510
+ setLastResult(result);
511
+ setStage("done");
512
+ return result;
513
+ } catch (err) {
514
+ const errorMessage = err instanceof Error ? err.message : "Compilation failed";
515
+ setError(errorMessage);
516
+ setStage("error");
517
+ setLastResult({ success: false, errors: [errorMessage] });
518
+ return null;
519
+ } finally {
520
+ setIsCompiling(false);
521
+ }
522
+ }, []);
523
+ return {
524
+ isCompiling,
525
+ stage,
526
+ lastResult,
527
+ error,
528
+ compileSchema
529
+ };
530
+ }
531
+ function usePreview(options) {
532
+ const [previewUrl, setPreviewUrl] = useState(null);
533
+ const [isLoading, setIsLoading] = useState(!!options?.appId);
534
+ const [error, setError] = useState(null);
535
+ const [loadError, setLoadError] = useState(null);
536
+ const [app, setApp] = useState(null);
537
+ const [isFullscreen, setIsFullscreen] = useState(false);
538
+ const [isExecutingEvent, setIsExecutingEvent] = useState(false);
539
+ const [errorToast, setErrorToast] = useState(null);
540
+ const [currentStateName, setCurrentStateName] = useState(null);
541
+ const [notificationsList, setNotificationsList] = useState([]);
542
+ const [isPanelOpen, setIsPanelOpen] = useState(false);
543
+ const notifications = useMemo(() => ({
544
+ notifications: notificationsList,
545
+ isPanelOpen,
546
+ closePanel: () => setIsPanelOpen(false),
547
+ dismissNotification: (id) => {
548
+ setNotificationsList((prev) => prev.filter((n) => n.id !== id));
549
+ },
550
+ markAsRead: (id) => {
551
+ setNotificationsList(
552
+ (prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n)
553
+ );
554
+ },
555
+ clearAll: () => setNotificationsList([])
556
+ }), [notificationsList, isPanelOpen]);
557
+ useEffect(() => {
558
+ const appId = options?.appId;
559
+ if (!appId) {
560
+ setApp(null);
561
+ setIsLoading(false);
562
+ return;
563
+ }
564
+ console.log("[usePreview] Setting up preview for app:", appId);
565
+ setPreviewUrl(`/api/orbitals/${appId}`);
566
+ setIsLoading(false);
567
+ }, [options?.appId]);
568
+ const startPreview = useCallback(async () => {
569
+ console.log("[usePreview] startPreview called");
570
+ }, []);
571
+ const stopPreview = useCallback(async () => {
572
+ setIsLoading(true);
573
+ try {
574
+ console.log("[usePreview] Stopping preview server...");
575
+ setPreviewUrl(null);
576
+ setApp(null);
577
+ } finally {
578
+ setIsLoading(false);
579
+ }
580
+ }, []);
581
+ const refresh = useCallback(async () => {
582
+ if (!previewUrl) return;
583
+ console.log("[usePreview] Refreshing preview...");
584
+ setPreviewUrl(`${previewUrl.split("?")[0]}?t=${Date.now()}`);
585
+ }, [previewUrl]);
586
+ const handleRefresh = useCallback(async () => {
587
+ console.log("[usePreview] Handle refresh...");
588
+ await refresh();
589
+ }, [refresh]);
590
+ const handleReset = useCallback(async () => {
591
+ console.log("[usePreview] Resetting preview...");
592
+ setError(null);
593
+ setLoadError(null);
594
+ setErrorToast(null);
595
+ setIsExecutingEvent(false);
596
+ setCurrentStateName(null);
597
+ }, []);
598
+ const toggleFullscreen = useCallback(() => {
599
+ setIsFullscreen((prev) => !prev);
600
+ }, []);
601
+ const dismissErrorToast = useCallback(() => {
602
+ setErrorToast(null);
603
+ }, []);
604
+ return {
605
+ previewUrl,
606
+ isLoading,
607
+ error,
608
+ loadError,
609
+ app,
610
+ isFullscreen,
611
+ isExecutingEvent,
612
+ errorToast,
613
+ currentStateName,
614
+ notifications,
615
+ startPreview,
616
+ stopPreview,
617
+ refresh,
618
+ handleRefresh,
619
+ handleReset,
620
+ toggleFullscreen,
621
+ setErrorToast,
622
+ dismissErrorToast
623
+ };
624
+ }
625
+ function useAgentChat(options) {
626
+ const [messages, setMessages] = useState([]);
627
+ const [status, setStatus] = useState("idle");
628
+ const [activities, setActivities] = useState([]);
629
+ const [todos, setTodos] = useState([]);
630
+ const [schemaDiffs, setSchemaDiffs] = useState([]);
631
+ const [isLoading, setIsLoading] = useState(false);
632
+ const [error, setError] = useState(null);
633
+ const [threadId] = useState(null);
634
+ const [interrupt, setInterrupt] = useState(null);
635
+ const sendMessage = useCallback(async (content) => {
636
+ setIsLoading(true);
637
+ setStatus("running");
638
+ setError(null);
639
+ try {
640
+ const userMessage = {
641
+ id: Date.now().toString(),
642
+ role: "user",
643
+ content,
644
+ timestamp: Date.now()
645
+ };
646
+ setMessages((prev) => [...prev, userMessage]);
647
+ console.log("[useAgentChat] Sending message:", content);
648
+ const assistantMessage = {
649
+ id: (Date.now() + 1).toString(),
650
+ role: "assistant",
651
+ content: "Agent chat is not yet implemented.",
652
+ timestamp: Date.now()
653
+ };
654
+ setMessages((prev) => [...prev, assistantMessage]);
655
+ setStatus("idle");
656
+ options?.onComplete?.();
657
+ } catch (err) {
658
+ setError(err instanceof Error ? err.message : "Failed to send message");
659
+ setStatus("error");
660
+ } finally {
661
+ setIsLoading(false);
662
+ }
663
+ }, [options]);
664
+ const startGeneration = useCallback(async (skill, prompt, genOptions) => {
665
+ setStatus("running");
666
+ setIsLoading(true);
667
+ setError(null);
668
+ const skillName = Array.isArray(skill) ? skill[0] : skill;
669
+ try {
670
+ console.log("[useAgentChat] Starting generation:", skillName, prompt, genOptions);
671
+ await new Promise((resolve) => setTimeout(resolve, 100));
672
+ setStatus("complete");
673
+ options?.onComplete?.();
674
+ } catch (err) {
675
+ setError(err instanceof Error ? err.message : "Generation failed");
676
+ setStatus("error");
677
+ } finally {
678
+ setIsLoading(false);
679
+ }
680
+ }, [options]);
681
+ const continueConversation = useCallback(async (message) => {
682
+ console.log("[useAgentChat] Continue conversation", message);
683
+ }, []);
684
+ const resumeWithDecision = useCallback(async (decisions) => {
685
+ console.log("[useAgentChat] Resume with decision:", decisions);
686
+ setInterrupt(null);
687
+ }, []);
688
+ const cancel = useCallback(() => {
689
+ setStatus("idle");
690
+ setIsLoading(false);
691
+ setInterrupt(null);
692
+ }, []);
693
+ const clearMessages = useCallback(() => {
694
+ setMessages([]);
695
+ }, []);
696
+ const clearHistory = useCallback(() => {
697
+ setMessages([]);
698
+ setActivities([]);
699
+ setTodos([]);
700
+ setSchemaDiffs([]);
701
+ setError(null);
702
+ }, []);
703
+ return {
704
+ messages,
705
+ status,
706
+ activities,
707
+ todos,
708
+ schemaDiffs,
709
+ isLoading,
710
+ error,
711
+ threadId,
712
+ interrupt,
713
+ sendMessage,
714
+ startGeneration,
715
+ continueConversation,
716
+ resumeWithDecision,
717
+ cancel,
718
+ clearMessages,
719
+ clearHistory
720
+ };
721
+ }
722
+ function useValidation() {
723
+ const [result, setResult] = useState(null);
724
+ const [isValidating, setIsValidating] = useState(false);
725
+ const [error, setError] = useState(null);
726
+ const [stage, setStage] = useState("idle");
727
+ const [isFixing, setIsFixing] = useState(false);
728
+ const [progressMessage, setProgressMessage] = useState(null);
729
+ const validate = useCallback(async (appId) => {
730
+ setIsValidating(true);
731
+ setError(null);
732
+ setStage("validating");
733
+ setProgressMessage("Validating schema...");
734
+ try {
735
+ console.log("[useValidation] Validating app:", appId);
736
+ const validationResult = {
737
+ valid: true,
738
+ errors: [],
739
+ warnings: []
740
+ };
741
+ setResult(validationResult);
742
+ setStage("complete");
743
+ setProgressMessage(null);
744
+ return validationResult;
745
+ } catch (err) {
746
+ const errorMessage = err instanceof Error ? err.message : "Validation failed";
747
+ setError(errorMessage);
748
+ const failedResult = {
749
+ valid: false,
750
+ errors: [{ code: "VALIDATION_ERROR", message: errorMessage, severity: "error" }],
751
+ warnings: []
752
+ };
753
+ setResult(failedResult);
754
+ setStage("complete");
755
+ setProgressMessage(null);
756
+ return failedResult;
757
+ } finally {
758
+ setIsValidating(false);
759
+ }
760
+ }, []);
761
+ const clearResult = useCallback(() => {
762
+ setResult(null);
763
+ setError(null);
764
+ }, []);
765
+ const reset = useCallback(() => {
766
+ setResult(null);
767
+ setError(null);
768
+ setStage("idle");
769
+ setIsFixing(false);
770
+ setProgressMessage(null);
771
+ setIsValidating(false);
772
+ }, []);
773
+ return {
774
+ result,
775
+ isValidating,
776
+ error,
777
+ stage,
778
+ isFixing,
779
+ progressMessage,
780
+ errors: result?.errors ?? [],
781
+ warnings: result?.warnings ?? [],
782
+ isValid: result?.valid ?? false,
783
+ validate,
784
+ clearResult,
785
+ reset
786
+ };
787
+ }
788
+ function useDeepAgentGeneration() {
789
+ const [requests, setRequests] = useState([]);
790
+ const [currentRequest, setCurrentRequest] = useState(null);
791
+ const [isGenerating, setIsGenerating] = useState(false);
792
+ const [isLoading, setIsLoading] = useState(false);
793
+ const [isComplete, setIsComplete] = useState(false);
794
+ const [progress, setProgress] = useState({ stage: "idle", percent: 0, message: "" });
795
+ const [error, setError] = useState(null);
796
+ const [interrupt, setInterrupt] = useState(null);
797
+ const generate = useCallback(async (prompt) => {
798
+ setIsGenerating(true);
799
+ setIsLoading(true);
800
+ setIsComplete(false);
801
+ setError(null);
802
+ setProgress({ stage: "starting", percent: 0, message: "Starting generation..." });
803
+ const request = {
804
+ id: Date.now().toString(),
805
+ prompt,
806
+ status: "running"
807
+ };
808
+ setCurrentRequest(request);
809
+ setRequests((prev) => [...prev, request]);
810
+ try {
811
+ console.log("[useDeepAgentGeneration] Generating from prompt:", prompt);
812
+ await new Promise((resolve) => setTimeout(resolve, 100));
813
+ request.status = "completed";
814
+ setCurrentRequest(request);
815
+ setIsComplete(true);
816
+ setProgress({ stage: "complete", percent: 100, message: "Generation complete" });
817
+ return null;
818
+ } catch (err) {
819
+ const errorMessage = err instanceof Error ? err.message : "Generation failed";
820
+ setError(errorMessage);
821
+ request.status = "failed";
822
+ request.error = errorMessage;
823
+ setCurrentRequest(request);
824
+ return null;
825
+ } finally {
826
+ setIsGenerating(false);
827
+ setIsLoading(false);
828
+ }
829
+ }, []);
830
+ const startGeneration = useCallback(async (skill, prompt, _options) => {
831
+ console.log("[useDeepAgentGeneration] Starting generation with skill:", skill);
832
+ await generate(prompt);
833
+ }, [generate]);
834
+ const cancelGeneration = useCallback(() => {
835
+ if (currentRequest) {
836
+ currentRequest.status = "failed";
837
+ currentRequest.error = "Cancelled by user";
838
+ setCurrentRequest(null);
839
+ }
840
+ setIsGenerating(false);
841
+ setIsLoading(false);
842
+ setIsComplete(false);
843
+ setProgress({ stage: "idle", percent: 0, message: "" });
844
+ }, [currentRequest]);
845
+ const clearRequests = useCallback(() => {
846
+ setRequests([]);
847
+ setCurrentRequest(null);
848
+ setError(null);
849
+ setProgress({ stage: "idle", percent: 0, message: "" });
850
+ setIsComplete(false);
851
+ }, []);
852
+ const submitInterruptDecisions = useCallback((decisions) => {
853
+ console.log("[useDeepAgentGeneration] Submitting interrupt decisions:", decisions);
854
+ setInterrupt(null);
855
+ }, []);
856
+ return {
857
+ requests,
858
+ currentRequest,
859
+ isGenerating,
860
+ isLoading,
861
+ isComplete,
862
+ progress,
863
+ error,
864
+ interrupt,
865
+ generate,
866
+ startGeneration,
867
+ cancelGeneration,
868
+ clearRequests,
869
+ submitInterruptDecisions
870
+ };
871
+ }
872
+ var UI_EVENT_MAP = {
873
+ // Form/CRUD events
874
+ "UI:SAVE": "SAVE",
875
+ "UI:CANCEL": "CANCEL",
876
+ "UI:CLOSE": "CLOSE",
877
+ "UI:VIEW": "VIEW",
878
+ "UI:EDIT": "EDIT",
879
+ "UI:DELETE": "DELETE",
880
+ "UI:CREATE": "CREATE",
881
+ "UI:SELECT": "SELECT",
882
+ "UI:DESELECT": "DESELECT",
883
+ "UI:SUBMIT": "SAVE",
884
+ "UI:UPDATE_STATUS": "UPDATE_STATUS",
885
+ "UI:SEARCH": "SEARCH",
886
+ "UI:CLEAR_SEARCH": "CLEAR_SEARCH",
887
+ "UI:ADD": "CREATE",
888
+ // Game events (for closed circuit with GameMenu, GamePauseOverlay, GameOverScreen)
889
+ "UI:PAUSE": "PAUSE",
890
+ "UI:RESUME": "RESUME",
891
+ "UI:RESTART": "RESTART",
892
+ "UI:GAME_OVER": "GAME_OVER",
893
+ "UI:START": "START",
894
+ "UI:QUIT": "QUIT",
895
+ "UI:INIT": "INIT"
896
+ };
897
+ function useUIEvents(dispatch, validEvents, eventBusInstance) {
898
+ const defaultEventBus = useEventBus();
899
+ const eventBus = eventBusInstance ?? defaultEventBus;
900
+ const validEventsKey = validEvents ? validEvents.slice().sort().join(",") : "";
901
+ const stableValidEvents = useMemo(
902
+ () => validEvents,
903
+ // eslint-disable-next-line react-hooks/exhaustive-deps
904
+ [validEventsKey]
905
+ );
906
+ useEffect(() => {
907
+ const unsubscribes = [];
908
+ Object.entries(UI_EVENT_MAP).forEach(([uiEvent, smEvent]) => {
909
+ const handler = (event) => {
910
+ if (!stableValidEvents || stableValidEvents.includes(smEvent)) {
911
+ dispatch(smEvent, event.payload);
912
+ }
913
+ };
914
+ const unsubscribe = eventBus.on(uiEvent, handler);
915
+ unsubscribes.push(unsubscribe);
916
+ });
917
+ const genericHandler = (event) => {
918
+ const eventName = event.payload?.event;
919
+ if (eventName) {
920
+ const smEvent = eventName;
921
+ if (!stableValidEvents || stableValidEvents.includes(smEvent)) {
922
+ dispatch(smEvent, event.payload);
923
+ }
924
+ }
925
+ };
926
+ const genericUnsubscribe = eventBus.on("UI:DISPATCH", genericHandler);
927
+ unsubscribes.push(genericUnsubscribe);
928
+ if (stableValidEvents) {
929
+ stableValidEvents.forEach((smEvent) => {
930
+ const uiPrefixedEvent = `UI:${smEvent}`;
931
+ const alreadyMapped = Object.keys(UI_EVENT_MAP).includes(uiPrefixedEvent);
932
+ if (!alreadyMapped) {
933
+ const directHandler = (event) => {
934
+ dispatch(smEvent, event.payload);
935
+ };
936
+ const unsubscribePrefixed = eventBus.on(
937
+ uiPrefixedEvent,
938
+ directHandler
939
+ );
940
+ unsubscribes.push(unsubscribePrefixed);
941
+ const unsubscribeDirect = eventBus.on(smEvent, directHandler);
942
+ unsubscribes.push(unsubscribeDirect);
943
+ }
944
+ });
945
+ }
946
+ return () => {
947
+ unsubscribes.forEach((unsub) => unsub());
948
+ };
949
+ }, [eventBus, dispatch, stableValidEvents]);
950
+ }
951
+ function useSelectedEntity(eventBusInstance) {
952
+ const defaultEventBus = useEventBus();
953
+ const eventBus = eventBusInstance ?? defaultEventBus;
954
+ const selectionContext = useSelectionContext();
955
+ const [localSelected, setLocalSelected] = useState(null);
956
+ const usingContext = selectionContext !== null;
957
+ useEffect(() => {
958
+ if (usingContext) return;
959
+ const handleSelect = (event) => {
960
+ const row = event.payload?.row;
961
+ if (row) {
962
+ setLocalSelected(row);
963
+ }
964
+ };
965
+ const handleDeselect = () => {
966
+ setLocalSelected(null);
967
+ };
968
+ const unsubSelect = eventBus.on("UI:SELECT", handleSelect);
969
+ const unsubView = eventBus.on("UI:VIEW", handleSelect);
970
+ const unsubDeselect = eventBus.on("UI:DESELECT", handleDeselect);
971
+ const unsubClose = eventBus.on("UI:CLOSE", handleDeselect);
972
+ const unsubCancel = eventBus.on("UI:CANCEL", handleDeselect);
973
+ return () => {
974
+ unsubSelect();
975
+ unsubView();
976
+ unsubDeselect();
977
+ unsubClose();
978
+ unsubCancel();
979
+ };
980
+ }, [eventBus, usingContext]);
981
+ if (selectionContext) {
982
+ return [selectionContext.selected, selectionContext.setSelected];
983
+ }
984
+ return [localSelected, setLocalSelected];
985
+ }
986
+ function useSelectionContext() {
987
+ const context = useContext(SelectionContext);
988
+ return context;
989
+ }
990
+ var entityDataKeys = {
991
+ all: ["entities"],
992
+ lists: () => [...entityDataKeys.all, "list"],
993
+ list: (entity, filters) => [...entityDataKeys.lists(), entity, filters],
994
+ details: () => [...entityDataKeys.all, "detail"],
995
+ detail: (entity, id) => [...entityDataKeys.details(), entity, id]
996
+ };
997
+ function useEntityList(entity, options = {}) {
998
+ const { skip = false } = options;
999
+ const [data, setData] = useState([]);
1000
+ const [isLoading, setIsLoading] = useState(!skip && !!entity);
1001
+ const [error, setError] = useState(null);
1002
+ const refetch = () => {
1003
+ if (!entity || skip) return;
1004
+ setIsLoading(true);
1005
+ setError(null);
1006
+ setTimeout(() => {
1007
+ setData([]);
1008
+ setIsLoading(false);
1009
+ }, 100);
1010
+ };
1011
+ useEffect(() => {
1012
+ if (skip || !entity) {
1013
+ setIsLoading(false);
1014
+ return;
1015
+ }
1016
+ refetch();
1017
+ }, [entity, skip]);
1018
+ return { data, isLoading, error, refetch };
1019
+ }
1020
+ function useEntity(entity, id) {
1021
+ const [data, setData] = useState(null);
1022
+ const [isLoading, setIsLoading] = useState(!!entity && !!id);
1023
+ const [error, setError] = useState(null);
1024
+ useEffect(() => {
1025
+ if (!entity || !id) {
1026
+ setIsLoading(false);
1027
+ return;
1028
+ }
1029
+ setIsLoading(true);
1030
+ setTimeout(() => {
1031
+ setData(null);
1032
+ setIsLoading(false);
1033
+ }, 100);
1034
+ }, [entity, id]);
1035
+ return { data, isLoading, error };
1036
+ }
1037
+ function useEntityDetail(entity, id) {
1038
+ const [data, setData] = useState(null);
1039
+ const [isLoading, setIsLoading] = useState(!!entity && !!id);
1040
+ const [error, setError] = useState(null);
1041
+ const refetch = () => {
1042
+ if (!entity || !id) return;
1043
+ setIsLoading(true);
1044
+ setError(null);
1045
+ setTimeout(() => {
1046
+ setData(null);
1047
+ setIsLoading(false);
1048
+ }, 100);
1049
+ };
1050
+ useEffect(() => {
1051
+ if (!entity || !id) {
1052
+ setIsLoading(false);
1053
+ return;
1054
+ }
1055
+ refetch();
1056
+ }, [entity, id]);
1057
+ return { data, isLoading, error, refetch };
1058
+ }
1059
+ function usePaginatedEntityList(entity, params, options = {}) {
1060
+ const { skip = false } = options;
1061
+ const [data, setData] = useState([]);
1062
+ const [isLoading, setIsLoading] = useState(!skip && !!entity);
1063
+ const [error, setError] = useState(null);
1064
+ const [totalCount, setTotalCount] = useState(0);
1065
+ const refetch = () => {
1066
+ if (!entity || skip) return;
1067
+ setIsLoading(true);
1068
+ setError(null);
1069
+ setTimeout(() => {
1070
+ setData([]);
1071
+ setTotalCount(0);
1072
+ setIsLoading(false);
1073
+ }, 100);
1074
+ };
1075
+ useEffect(() => {
1076
+ if (skip || !entity) {
1077
+ setIsLoading(false);
1078
+ return;
1079
+ }
1080
+ refetch();
1081
+ }, [
1082
+ entity,
1083
+ params.page,
1084
+ params.pageSize,
1085
+ params.search,
1086
+ params.sortBy,
1087
+ params.sortDirection,
1088
+ skip
1089
+ ]);
1090
+ const totalPages = Math.ceil(totalCount / params.pageSize) || 1;
1091
+ return {
1092
+ data,
1093
+ isLoading,
1094
+ error,
1095
+ totalCount,
1096
+ totalPages,
1097
+ hasNextPage: params.page < totalPages,
1098
+ hasPreviousPage: params.page > 1,
1099
+ refetch
1100
+ };
1101
+ }
1102
+ var queryStores = /* @__PURE__ */ new Map();
1103
+ function getOrCreateStore(query) {
1104
+ if (!queryStores.has(query)) {
1105
+ queryStores.set(query, {
1106
+ search: "",
1107
+ filters: {},
1108
+ sortField: void 0,
1109
+ sortDirection: void 0,
1110
+ listeners: /* @__PURE__ */ new Set()
1111
+ });
1112
+ }
1113
+ return queryStores.get(query);
1114
+ }
1115
+ function useQuerySingleton(query) {
1116
+ const [, forceUpdate] = useState({});
1117
+ if (!query) {
1118
+ return null;
1119
+ }
1120
+ const store = useMemo(() => getOrCreateStore(query), [query]);
1121
+ useMemo(() => {
1122
+ const listener = () => forceUpdate({});
1123
+ store.listeners.add(listener);
1124
+ return () => {
1125
+ store.listeners.delete(listener);
1126
+ };
1127
+ }, [store]);
1128
+ const notifyListeners = useCallback(() => {
1129
+ store.listeners.forEach((listener) => listener());
1130
+ }, [store]);
1131
+ const setSearch = useCallback((value) => {
1132
+ store.search = value;
1133
+ notifyListeners();
1134
+ }, [store, notifyListeners]);
1135
+ const setFilter = useCallback((key, value) => {
1136
+ store.filters = { ...store.filters, [key]: value };
1137
+ notifyListeners();
1138
+ }, [store, notifyListeners]);
1139
+ const clearFilters = useCallback(() => {
1140
+ store.filters = {};
1141
+ store.search = "";
1142
+ notifyListeners();
1143
+ }, [store, notifyListeners]);
1144
+ const setSort = useCallback((field, direction) => {
1145
+ store.sortField = field;
1146
+ store.sortDirection = direction;
1147
+ notifyListeners();
1148
+ }, [store, notifyListeners]);
1149
+ return {
1150
+ search: store.search,
1151
+ setSearch,
1152
+ filters: store.filters,
1153
+ setFilter,
1154
+ clearFilters,
1155
+ sortField: store.sortField,
1156
+ sortDirection: store.sortDirection,
1157
+ setSort
1158
+ };
1159
+ }
1160
+ function parseQueryBinding(binding) {
1161
+ const cleaned = binding.startsWith("@") ? binding.slice(1) : binding;
1162
+ const parts = cleaned.split(".");
1163
+ return {
1164
+ query: parts[0],
1165
+ field: parts.length > 1 ? parts.slice(1).join(".") : void 0
1166
+ };
1167
+ }
1168
+
1169
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/subscribable.js
1170
+ var Subscribable = class {
1171
+ constructor() {
1172
+ this.listeners = /* @__PURE__ */ new Set();
1173
+ this.subscribe = this.subscribe.bind(this);
1174
+ }
1175
+ subscribe(listener) {
1176
+ this.listeners.add(listener);
1177
+ this.onSubscribe();
1178
+ return () => {
1179
+ this.listeners.delete(listener);
1180
+ this.onUnsubscribe();
1181
+ };
1182
+ }
1183
+ hasListeners() {
1184
+ return this.listeners.size > 0;
1185
+ }
1186
+ onSubscribe() {
1187
+ }
1188
+ onUnsubscribe() {
1189
+ }
1190
+ };
1191
+
1192
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/timeoutManager.js
1193
+ var defaultTimeoutProvider = {
1194
+ // We need the wrapper function syntax below instead of direct references to
1195
+ // global setTimeout etc.
1196
+ //
1197
+ // BAD: `setTimeout: setTimeout`
1198
+ // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
1199
+ //
1200
+ // If we use direct references here, then anything that wants to spy on or
1201
+ // replace the global setTimeout (like tests) won't work since we'll already
1202
+ // have a hard reference to the original implementation at the time when this
1203
+ // file was imported.
1204
+ setTimeout: (callback, delay) => setTimeout(callback, delay),
1205
+ clearTimeout: (timeoutId) => clearTimeout(timeoutId),
1206
+ setInterval: (callback, delay) => setInterval(callback, delay),
1207
+ clearInterval: (intervalId) => clearInterval(intervalId)
1208
+ };
1209
+ var _provider, _providerCalled, _a;
1210
+ var TimeoutManager = (_a = class {
1211
+ constructor() {
1212
+ // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
1213
+ // type at app boot; and if we leave that type, then any new timer provider
1214
+ // would need to support ReturnType<typeof setTimeout>, which is infeasible.
1215
+ //
1216
+ // We settle for type safety for the TimeoutProvider type, and accept that
1217
+ // this class is unsafe internally to allow for extension.
1218
+ __privateAdd(this, _provider, defaultTimeoutProvider);
1219
+ __privateAdd(this, _providerCalled, false);
1220
+ }
1221
+ setTimeoutProvider(provider) {
1222
+ if (process.env.NODE_ENV !== "production") {
1223
+ if (__privateGet(this, _providerCalled) && provider !== __privateGet(this, _provider)) {
1224
+ console.error(
1225
+ `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
1226
+ { previous: __privateGet(this, _provider), provider }
1227
+ );
1228
+ }
1229
+ }
1230
+ __privateSet(this, _provider, provider);
1231
+ if (process.env.NODE_ENV !== "production") {
1232
+ __privateSet(this, _providerCalled, false);
1233
+ }
1234
+ }
1235
+ setTimeout(callback, delay) {
1236
+ if (process.env.NODE_ENV !== "production") {
1237
+ __privateSet(this, _providerCalled, true);
1238
+ }
1239
+ return __privateGet(this, _provider).setTimeout(callback, delay);
1240
+ }
1241
+ clearTimeout(timeoutId) {
1242
+ __privateGet(this, _provider).clearTimeout(timeoutId);
1243
+ }
1244
+ setInterval(callback, delay) {
1245
+ if (process.env.NODE_ENV !== "production") {
1246
+ __privateSet(this, _providerCalled, true);
1247
+ }
1248
+ return __privateGet(this, _provider).setInterval(callback, delay);
1249
+ }
1250
+ clearInterval(intervalId) {
1251
+ __privateGet(this, _provider).clearInterval(intervalId);
1252
+ }
1253
+ }, _provider = new WeakMap(), _providerCalled = new WeakMap(), _a);
1254
+ var timeoutManager = new TimeoutManager();
1255
+ function systemSetTimeoutZero(callback) {
1256
+ setTimeout(callback, 0);
1257
+ }
1258
+
1259
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/utils.js
1260
+ var isServer = typeof window === "undefined" || "Deno" in globalThis;
1261
+ function noop() {
1262
+ }
1263
+ function isValidTimeout(value) {
1264
+ return typeof value === "number" && value >= 0 && value !== Infinity;
1265
+ }
1266
+ function timeUntilStale(updatedAt, staleTime) {
1267
+ return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
1268
+ }
1269
+ function resolveStaleTime(staleTime, query) {
1270
+ return typeof staleTime === "function" ? staleTime(query) : staleTime;
1271
+ }
1272
+ function resolveEnabled(enabled, query) {
1273
+ return typeof enabled === "function" ? enabled(query) : enabled;
1274
+ }
1275
+ function hashKey(queryKey) {
1276
+ return JSON.stringify(
1277
+ queryKey,
1278
+ (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
1279
+ result[key] = val[key];
1280
+ return result;
1281
+ }, {}) : val
1282
+ );
1283
+ }
1284
+ var hasOwn = Object.prototype.hasOwnProperty;
1285
+ function replaceEqualDeep(a, b, depth = 0) {
1286
+ if (a === b) {
1287
+ return a;
1288
+ }
1289
+ if (depth > 500) return b;
1290
+ const array = isPlainArray(a) && isPlainArray(b);
1291
+ if (!array && !(isPlainObject(a) && isPlainObject(b))) return b;
1292
+ const aItems = array ? a : Object.keys(a);
1293
+ const aSize = aItems.length;
1294
+ const bItems = array ? b : Object.keys(b);
1295
+ const bSize = bItems.length;
1296
+ const copy = array ? new Array(bSize) : {};
1297
+ let equalItems = 0;
1298
+ for (let i = 0; i < bSize; i++) {
1299
+ const key = array ? i : bItems[i];
1300
+ const aItem = a[key];
1301
+ const bItem = b[key];
1302
+ if (aItem === bItem) {
1303
+ copy[key] = aItem;
1304
+ if (array ? i < aSize : hasOwn.call(a, key)) equalItems++;
1305
+ continue;
1306
+ }
1307
+ if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
1308
+ copy[key] = bItem;
1309
+ continue;
1310
+ }
1311
+ const v = replaceEqualDeep(aItem, bItem, depth + 1);
1312
+ copy[key] = v;
1313
+ if (v === aItem) equalItems++;
1314
+ }
1315
+ return aSize === bSize && equalItems === aSize ? a : copy;
1316
+ }
1317
+ function shallowEqualObjects(a, b) {
1318
+ if (!b || Object.keys(a).length !== Object.keys(b).length) {
1319
+ return false;
1320
+ }
1321
+ for (const key in a) {
1322
+ if (a[key] !== b[key]) {
1323
+ return false;
1324
+ }
1325
+ }
1326
+ return true;
1327
+ }
1328
+ function isPlainArray(value) {
1329
+ return Array.isArray(value) && value.length === Object.keys(value).length;
1330
+ }
1331
+ function isPlainObject(o) {
1332
+ if (!hasObjectPrototype(o)) {
1333
+ return false;
1334
+ }
1335
+ const ctor = o.constructor;
1336
+ if (ctor === void 0) {
1337
+ return true;
1338
+ }
1339
+ const prot = ctor.prototype;
1340
+ if (!hasObjectPrototype(prot)) {
1341
+ return false;
1342
+ }
1343
+ if (!prot.hasOwnProperty("isPrototypeOf")) {
1344
+ return false;
1345
+ }
1346
+ if (Object.getPrototypeOf(o) !== Object.prototype) {
1347
+ return false;
1348
+ }
1349
+ return true;
1350
+ }
1351
+ function hasObjectPrototype(o) {
1352
+ return Object.prototype.toString.call(o) === "[object Object]";
1353
+ }
1354
+ function replaceData(prevData, data, options) {
1355
+ if (typeof options.structuralSharing === "function") {
1356
+ return options.structuralSharing(prevData, data);
1357
+ } else if (options.structuralSharing !== false) {
1358
+ if (process.env.NODE_ENV !== "production") {
1359
+ try {
1360
+ return replaceEqualDeep(prevData, data);
1361
+ } catch (error) {
1362
+ console.error(
1363
+ `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`
1364
+ );
1365
+ throw error;
1366
+ }
1367
+ }
1368
+ return replaceEqualDeep(prevData, data);
1369
+ }
1370
+ return data;
1371
+ }
1372
+ function shouldThrowError(throwOnError, params) {
1373
+ if (typeof throwOnError === "function") {
1374
+ return throwOnError(...params);
1375
+ }
1376
+ return !!throwOnError;
1377
+ }
1378
+
1379
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/focusManager.js
1380
+ var _focused, _cleanup, _setup, _a2;
1381
+ var FocusManager = (_a2 = class extends Subscribable {
1382
+ constructor() {
1383
+ super();
1384
+ __privateAdd(this, _focused);
1385
+ __privateAdd(this, _cleanup);
1386
+ __privateAdd(this, _setup);
1387
+ __privateSet(this, _setup, (onFocus) => {
1388
+ if (!isServer && window.addEventListener) {
1389
+ const listener = () => onFocus();
1390
+ window.addEventListener("visibilitychange", listener, false);
1391
+ return () => {
1392
+ window.removeEventListener("visibilitychange", listener);
1393
+ };
1394
+ }
1395
+ return;
1396
+ });
1397
+ }
1398
+ onSubscribe() {
1399
+ if (!__privateGet(this, _cleanup)) {
1400
+ this.setEventListener(__privateGet(this, _setup));
1401
+ }
1402
+ }
1403
+ onUnsubscribe() {
1404
+ var _a6;
1405
+ if (!this.hasListeners()) {
1406
+ (_a6 = __privateGet(this, _cleanup)) == null ? void 0 : _a6.call(this);
1407
+ __privateSet(this, _cleanup, void 0);
1408
+ }
1409
+ }
1410
+ setEventListener(setup) {
1411
+ var _a6;
1412
+ __privateSet(this, _setup, setup);
1413
+ (_a6 = __privateGet(this, _cleanup)) == null ? void 0 : _a6.call(this);
1414
+ __privateSet(this, _cleanup, setup((focused) => {
1415
+ if (typeof focused === "boolean") {
1416
+ this.setFocused(focused);
1417
+ } else {
1418
+ this.onFocus();
1419
+ }
1420
+ }));
1421
+ }
1422
+ setFocused(focused) {
1423
+ const changed = __privateGet(this, _focused) !== focused;
1424
+ if (changed) {
1425
+ __privateSet(this, _focused, focused);
1426
+ this.onFocus();
1427
+ }
1428
+ }
1429
+ onFocus() {
1430
+ const isFocused = this.isFocused();
1431
+ this.listeners.forEach((listener) => {
1432
+ listener(isFocused);
1433
+ });
1434
+ }
1435
+ isFocused() {
1436
+ if (typeof __privateGet(this, _focused) === "boolean") {
1437
+ return __privateGet(this, _focused);
1438
+ }
1439
+ return globalThis.document?.visibilityState !== "hidden";
1440
+ }
1441
+ }, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _a2);
1442
+ var focusManager = new FocusManager();
1443
+
1444
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/thenable.js
1445
+ function pendingThenable() {
1446
+ let resolve;
1447
+ let reject;
1448
+ const thenable = new Promise((_resolve, _reject) => {
1449
+ resolve = _resolve;
1450
+ reject = _reject;
1451
+ });
1452
+ thenable.status = "pending";
1453
+ thenable.catch(() => {
1454
+ });
1455
+ function finalize(data) {
1456
+ Object.assign(thenable, data);
1457
+ delete thenable.resolve;
1458
+ delete thenable.reject;
1459
+ }
1460
+ thenable.resolve = (value) => {
1461
+ finalize({
1462
+ status: "fulfilled",
1463
+ value
1464
+ });
1465
+ resolve(value);
1466
+ };
1467
+ thenable.reject = (reason) => {
1468
+ finalize({
1469
+ status: "rejected",
1470
+ reason
1471
+ });
1472
+ reject(reason);
1473
+ };
1474
+ return thenable;
1475
+ }
1476
+
1477
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/notifyManager.js
1478
+ var defaultScheduler = systemSetTimeoutZero;
1479
+ function createNotifyManager() {
1480
+ let queue = [];
1481
+ let transactions = 0;
1482
+ let notifyFn = (callback) => {
1483
+ callback();
1484
+ };
1485
+ let batchNotifyFn = (callback) => {
1486
+ callback();
1487
+ };
1488
+ let scheduleFn = defaultScheduler;
1489
+ const schedule = (callback) => {
1490
+ if (transactions) {
1491
+ queue.push(callback);
1492
+ } else {
1493
+ scheduleFn(() => {
1494
+ notifyFn(callback);
1495
+ });
1496
+ }
1497
+ };
1498
+ const flush = () => {
1499
+ const originalQueue = queue;
1500
+ queue = [];
1501
+ if (originalQueue.length) {
1502
+ scheduleFn(() => {
1503
+ batchNotifyFn(() => {
1504
+ originalQueue.forEach((callback) => {
1505
+ notifyFn(callback);
1506
+ });
1507
+ });
1508
+ });
1509
+ }
1510
+ };
1511
+ return {
1512
+ batch: (callback) => {
1513
+ let result;
1514
+ transactions++;
1515
+ try {
1516
+ result = callback();
1517
+ } finally {
1518
+ transactions--;
1519
+ if (!transactions) {
1520
+ flush();
1521
+ }
1522
+ }
1523
+ return result;
1524
+ },
1525
+ /**
1526
+ * All calls to the wrapped function will be batched.
1527
+ */
1528
+ batchCalls: (callback) => {
1529
+ return (...args) => {
1530
+ schedule(() => {
1531
+ callback(...args);
1532
+ });
1533
+ };
1534
+ },
1535
+ schedule,
1536
+ /**
1537
+ * Use this method to set a custom notify function.
1538
+ * This can be used to for example wrap notifications with `React.act` while running tests.
1539
+ */
1540
+ setNotifyFunction: (fn) => {
1541
+ notifyFn = fn;
1542
+ },
1543
+ /**
1544
+ * Use this method to set a custom function to batch notifications together into a single tick.
1545
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
1546
+ */
1547
+ setBatchNotifyFunction: (fn) => {
1548
+ batchNotifyFn = fn;
1549
+ },
1550
+ setScheduler: (fn) => {
1551
+ scheduleFn = fn;
1552
+ }
1553
+ };
1554
+ }
1555
+ var notifyManager = createNotifyManager();
1556
+
1557
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/onlineManager.js
1558
+ var _online, _cleanup2, _setup2, _a3;
1559
+ var OnlineManager = (_a3 = class extends Subscribable {
1560
+ constructor() {
1561
+ super();
1562
+ __privateAdd(this, _online, true);
1563
+ __privateAdd(this, _cleanup2);
1564
+ __privateAdd(this, _setup2);
1565
+ __privateSet(this, _setup2, (onOnline) => {
1566
+ if (!isServer && window.addEventListener) {
1567
+ const onlineListener = () => onOnline(true);
1568
+ const offlineListener = () => onOnline(false);
1569
+ window.addEventListener("online", onlineListener, false);
1570
+ window.addEventListener("offline", offlineListener, false);
1571
+ return () => {
1572
+ window.removeEventListener("online", onlineListener);
1573
+ window.removeEventListener("offline", offlineListener);
1574
+ };
1575
+ }
1576
+ return;
1577
+ });
1578
+ }
1579
+ onSubscribe() {
1580
+ if (!__privateGet(this, _cleanup2)) {
1581
+ this.setEventListener(__privateGet(this, _setup2));
1582
+ }
1583
+ }
1584
+ onUnsubscribe() {
1585
+ var _a6;
1586
+ if (!this.hasListeners()) {
1587
+ (_a6 = __privateGet(this, _cleanup2)) == null ? void 0 : _a6.call(this);
1588
+ __privateSet(this, _cleanup2, void 0);
1589
+ }
1590
+ }
1591
+ setEventListener(setup) {
1592
+ var _a6;
1593
+ __privateSet(this, _setup2, setup);
1594
+ (_a6 = __privateGet(this, _cleanup2)) == null ? void 0 : _a6.call(this);
1595
+ __privateSet(this, _cleanup2, setup(this.setOnline.bind(this)));
1596
+ }
1597
+ setOnline(online) {
1598
+ const changed = __privateGet(this, _online) !== online;
1599
+ if (changed) {
1600
+ __privateSet(this, _online, online);
1601
+ this.listeners.forEach((listener) => {
1602
+ listener(online);
1603
+ });
1604
+ }
1605
+ }
1606
+ isOnline() {
1607
+ return __privateGet(this, _online);
1608
+ }
1609
+ }, _online = new WeakMap(), _cleanup2 = new WeakMap(), _setup2 = new WeakMap(), _a3);
1610
+ var onlineManager = new OnlineManager();
1611
+
1612
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/retryer.js
1613
+ function canFetch(networkMode) {
1614
+ return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
1615
+ }
1616
+
1617
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/query.js
1618
+ function fetchState(data, options) {
1619
+ return {
1620
+ fetchFailureCount: 0,
1621
+ fetchFailureReason: null,
1622
+ fetchStatus: canFetch(options.networkMode) ? "fetching" : "paused",
1623
+ ...data === void 0 && {
1624
+ error: null,
1625
+ status: "pending"
1626
+ }
1627
+ };
1628
+ }
1629
+
1630
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/queryObserver.js
1631
+ var _client, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _currentThenable, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn, _a4;
1632
+ var QueryObserver = (_a4 = class extends Subscribable {
1633
+ constructor(client, options) {
1634
+ super();
1635
+ __privateAdd(this, _QueryObserver_instances);
1636
+ __privateAdd(this, _client);
1637
+ __privateAdd(this, _currentQuery);
1638
+ __privateAdd(this, _currentQueryInitialState);
1639
+ __privateAdd(this, _currentResult);
1640
+ __privateAdd(this, _currentResultState);
1641
+ __privateAdd(this, _currentResultOptions);
1642
+ __privateAdd(this, _currentThenable);
1643
+ __privateAdd(this, _selectError);
1644
+ __privateAdd(this, _selectFn);
1645
+ __privateAdd(this, _selectResult);
1646
+ // This property keeps track of the last query with defined data.
1647
+ // It will be used to pass the previous data and query to the placeholder function between renders.
1648
+ __privateAdd(this, _lastQueryWithDefinedData);
1649
+ __privateAdd(this, _staleTimeoutId);
1650
+ __privateAdd(this, _refetchIntervalId);
1651
+ __privateAdd(this, _currentRefetchInterval);
1652
+ __privateAdd(this, _trackedProps, /* @__PURE__ */ new Set());
1653
+ this.options = options;
1654
+ __privateSet(this, _client, client);
1655
+ __privateSet(this, _selectError, null);
1656
+ __privateSet(this, _currentThenable, pendingThenable());
1657
+ this.bindMethods();
1658
+ this.setOptions(options);
1659
+ }
1660
+ bindMethods() {
1661
+ this.refetch = this.refetch.bind(this);
1662
+ }
1663
+ onSubscribe() {
1664
+ if (this.listeners.size === 1) {
1665
+ __privateGet(this, _currentQuery).addObserver(this);
1666
+ if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) {
1667
+ __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
1668
+ } else {
1669
+ this.updateResult();
1670
+ }
1671
+ __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
1672
+ }
1673
+ }
1674
+ onUnsubscribe() {
1675
+ if (!this.hasListeners()) {
1676
+ this.destroy();
1677
+ }
1678
+ }
1679
+ shouldFetchOnReconnect() {
1680
+ return shouldFetchOn(
1681
+ __privateGet(this, _currentQuery),
1682
+ this.options,
1683
+ this.options.refetchOnReconnect
1684
+ );
1685
+ }
1686
+ shouldFetchOnWindowFocus() {
1687
+ return shouldFetchOn(
1688
+ __privateGet(this, _currentQuery),
1689
+ this.options,
1690
+ this.options.refetchOnWindowFocus
1691
+ );
1692
+ }
1693
+ destroy() {
1694
+ this.listeners = /* @__PURE__ */ new Set();
1695
+ __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
1696
+ __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
1697
+ __privateGet(this, _currentQuery).removeObserver(this);
1698
+ }
1699
+ setOptions(options) {
1700
+ const prevOptions = this.options;
1701
+ const prevQuery = __privateGet(this, _currentQuery);
1702
+ this.options = __privateGet(this, _client).defaultQueryOptions(options);
1703
+ if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") {
1704
+ throw new Error(
1705
+ "Expected enabled to be a boolean or a callback that returns a boolean"
1706
+ );
1707
+ }
1708
+ __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
1709
+ __privateGet(this, _currentQuery).setOptions(this.options);
1710
+ if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
1711
+ __privateGet(this, _client).getQueryCache().notify({
1712
+ type: "observerOptionsUpdated",
1713
+ query: __privateGet(this, _currentQuery),
1714
+ observer: this
1715
+ });
1716
+ }
1717
+ const mounted = this.hasListeners();
1718
+ if (mounted && shouldFetchOptionally(
1719
+ __privateGet(this, _currentQuery),
1720
+ prevQuery,
1721
+ this.options,
1722
+ prevOptions
1723
+ )) {
1724
+ __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
1725
+ }
1726
+ this.updateResult();
1727
+ if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveStaleTime(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveStaleTime(prevOptions.staleTime, __privateGet(this, _currentQuery)))) {
1728
+ __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
1729
+ }
1730
+ const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this);
1731
+ if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) {
1732
+ __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval);
1733
+ }
1734
+ }
1735
+ getOptimisticResult(options) {
1736
+ const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), options);
1737
+ const result = this.createResult(query, options);
1738
+ if (shouldAssignObserverCurrentProperties(this, result)) {
1739
+ __privateSet(this, _currentResult, result);
1740
+ __privateSet(this, _currentResultOptions, this.options);
1741
+ __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
1742
+ }
1743
+ return result;
1744
+ }
1745
+ getCurrentResult() {
1746
+ return __privateGet(this, _currentResult);
1747
+ }
1748
+ trackResult(result, onPropTracked) {
1749
+ return new Proxy(result, {
1750
+ get: (target, key) => {
1751
+ this.trackProp(key);
1752
+ onPropTracked?.(key);
1753
+ if (key === "promise") {
1754
+ this.trackProp("data");
1755
+ if (!this.options.experimental_prefetchInRender && __privateGet(this, _currentThenable).status === "pending") {
1756
+ __privateGet(this, _currentThenable).reject(
1757
+ new Error(
1758
+ "experimental_prefetchInRender feature flag is not enabled"
1759
+ )
1760
+ );
1761
+ }
1762
+ }
1763
+ return Reflect.get(target, key);
1764
+ }
1765
+ });
1766
+ }
1767
+ trackProp(key) {
1768
+ __privateGet(this, _trackedProps).add(key);
1769
+ }
1770
+ getCurrentQuery() {
1771
+ return __privateGet(this, _currentQuery);
1772
+ }
1773
+ refetch({ ...options } = {}) {
1774
+ return this.fetch({
1775
+ ...options
1776
+ });
1777
+ }
1778
+ fetchOptimistic(options) {
1779
+ const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
1780
+ const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), defaultedOptions);
1781
+ return query.fetch().then(() => this.createResult(query, defaultedOptions));
1782
+ }
1783
+ fetch(fetchOptions) {
1784
+ return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, {
1785
+ ...fetchOptions,
1786
+ cancelRefetch: fetchOptions.cancelRefetch ?? true
1787
+ }).then(() => {
1788
+ this.updateResult();
1789
+ return __privateGet(this, _currentResult);
1790
+ });
1791
+ }
1792
+ createResult(query, options) {
1793
+ const prevQuery = __privateGet(this, _currentQuery);
1794
+ const prevOptions = this.options;
1795
+ const prevResult = __privateGet(this, _currentResult);
1796
+ const prevResultState = __privateGet(this, _currentResultState);
1797
+ const prevResultOptions = __privateGet(this, _currentResultOptions);
1798
+ const queryChange = query !== prevQuery;
1799
+ const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
1800
+ const { state } = query;
1801
+ let newState = { ...state };
1802
+ let isPlaceholderData = false;
1803
+ let data;
1804
+ if (options._optimisticResults) {
1805
+ const mounted = this.hasListeners();
1806
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
1807
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
1808
+ if (fetchOnMount || fetchOptionally) {
1809
+ newState = {
1810
+ ...newState,
1811
+ ...fetchState(state.data, query.options)
1812
+ };
1813
+ }
1814
+ if (options._optimisticResults === "isRestoring") {
1815
+ newState.fetchStatus = "idle";
1816
+ }
1817
+ }
1818
+ let { error, errorUpdatedAt, status } = newState;
1819
+ data = newState.data;
1820
+ let skipSelect = false;
1821
+ if (options.placeholderData !== void 0 && data === void 0 && status === "pending") {
1822
+ let placeholderData;
1823
+ if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
1824
+ placeholderData = prevResult.data;
1825
+ skipSelect = true;
1826
+ } else {
1827
+ placeholderData = typeof options.placeholderData === "function" ? options.placeholderData(
1828
+ __privateGet(this, _lastQueryWithDefinedData)?.state.data,
1829
+ __privateGet(this, _lastQueryWithDefinedData)
1830
+ ) : options.placeholderData;
1831
+ }
1832
+ if (placeholderData !== void 0) {
1833
+ status = "success";
1834
+ data = replaceData(
1835
+ prevResult?.data,
1836
+ placeholderData,
1837
+ options
1838
+ );
1839
+ isPlaceholderData = true;
1840
+ }
1841
+ }
1842
+ if (options.select && data !== void 0 && !skipSelect) {
1843
+ if (prevResult && data === prevResultState?.data && options.select === __privateGet(this, _selectFn)) {
1844
+ data = __privateGet(this, _selectResult);
1845
+ } else {
1846
+ try {
1847
+ __privateSet(this, _selectFn, options.select);
1848
+ data = options.select(data);
1849
+ data = replaceData(prevResult?.data, data, options);
1850
+ __privateSet(this, _selectResult, data);
1851
+ __privateSet(this, _selectError, null);
1852
+ } catch (selectError) {
1853
+ __privateSet(this, _selectError, selectError);
1854
+ }
1855
+ }
1856
+ }
1857
+ if (__privateGet(this, _selectError)) {
1858
+ error = __privateGet(this, _selectError);
1859
+ data = __privateGet(this, _selectResult);
1860
+ errorUpdatedAt = Date.now();
1861
+ status = "error";
1862
+ }
1863
+ const isFetching = newState.fetchStatus === "fetching";
1864
+ const isPending = status === "pending";
1865
+ const isError = status === "error";
1866
+ const isLoading = isPending && isFetching;
1867
+ const hasData = data !== void 0;
1868
+ const result = {
1869
+ status,
1870
+ fetchStatus: newState.fetchStatus,
1871
+ isPending,
1872
+ isSuccess: status === "success",
1873
+ isError,
1874
+ isInitialLoading: isLoading,
1875
+ isLoading,
1876
+ data,
1877
+ dataUpdatedAt: newState.dataUpdatedAt,
1878
+ error,
1879
+ errorUpdatedAt,
1880
+ failureCount: newState.fetchFailureCount,
1881
+ failureReason: newState.fetchFailureReason,
1882
+ errorUpdateCount: newState.errorUpdateCount,
1883
+ isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,
1884
+ isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
1885
+ isFetching,
1886
+ isRefetching: isFetching && !isPending,
1887
+ isLoadingError: isError && !hasData,
1888
+ isPaused: newState.fetchStatus === "paused",
1889
+ isPlaceholderData,
1890
+ isRefetchError: isError && hasData,
1891
+ isStale: isStale(query, options),
1892
+ refetch: this.refetch,
1893
+ promise: __privateGet(this, _currentThenable),
1894
+ isEnabled: resolveEnabled(options.enabled, query) !== false
1895
+ };
1896
+ const nextResult = result;
1897
+ if (this.options.experimental_prefetchInRender) {
1898
+ const hasResultData = nextResult.data !== void 0;
1899
+ const isErrorWithoutData = nextResult.status === "error" && !hasResultData;
1900
+ const finalizeThenableIfPossible = (thenable) => {
1901
+ if (isErrorWithoutData) {
1902
+ thenable.reject(nextResult.error);
1903
+ } else if (hasResultData) {
1904
+ thenable.resolve(nextResult.data);
1905
+ }
1906
+ };
1907
+ const recreateThenable = () => {
1908
+ const pending = __privateSet(this, _currentThenable, nextResult.promise = pendingThenable());
1909
+ finalizeThenableIfPossible(pending);
1910
+ };
1911
+ const prevThenable = __privateGet(this, _currentThenable);
1912
+ switch (prevThenable.status) {
1913
+ case "pending":
1914
+ if (query.queryHash === prevQuery.queryHash) {
1915
+ finalizeThenableIfPossible(prevThenable);
1916
+ }
1917
+ break;
1918
+ case "fulfilled":
1919
+ if (isErrorWithoutData || nextResult.data !== prevThenable.value) {
1920
+ recreateThenable();
1921
+ }
1922
+ break;
1923
+ case "rejected":
1924
+ if (!isErrorWithoutData || nextResult.error !== prevThenable.reason) {
1925
+ recreateThenable();
1926
+ }
1927
+ break;
1928
+ }
1929
+ }
1930
+ return nextResult;
1931
+ }
1932
+ updateResult() {
1933
+ const prevResult = __privateGet(this, _currentResult);
1934
+ const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options);
1935
+ __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
1936
+ __privateSet(this, _currentResultOptions, this.options);
1937
+ if (__privateGet(this, _currentResultState).data !== void 0) {
1938
+ __privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery));
1939
+ }
1940
+ if (shallowEqualObjects(nextResult, prevResult)) {
1941
+ return;
1942
+ }
1943
+ __privateSet(this, _currentResult, nextResult);
1944
+ const shouldNotifyListeners = () => {
1945
+ if (!prevResult) {
1946
+ return true;
1947
+ }
1948
+ const { notifyOnChangeProps } = this.options;
1949
+ const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
1950
+ if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) {
1951
+ return true;
1952
+ }
1953
+ const includedProps = new Set(
1954
+ notifyOnChangePropsValue ?? __privateGet(this, _trackedProps)
1955
+ );
1956
+ if (this.options.throwOnError) {
1957
+ includedProps.add("error");
1958
+ }
1959
+ return Object.keys(__privateGet(this, _currentResult)).some((key) => {
1960
+ const typedKey = key;
1961
+ const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey];
1962
+ return changed && includedProps.has(typedKey);
1963
+ });
1964
+ };
1965
+ __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { listeners: shouldNotifyListeners() });
1966
+ }
1967
+ onQueryUpdate() {
1968
+ this.updateResult();
1969
+ if (this.hasListeners()) {
1970
+ __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
1971
+ }
1972
+ }
1973
+ }, _client = new WeakMap(), _currentQuery = new WeakMap(), _currentQueryInitialState = new WeakMap(), _currentResult = new WeakMap(), _currentResultState = new WeakMap(), _currentResultOptions = new WeakMap(), _currentThenable = new WeakMap(), _selectError = new WeakMap(), _selectFn = new WeakMap(), _selectResult = new WeakMap(), _lastQueryWithDefinedData = new WeakMap(), _staleTimeoutId = new WeakMap(), _refetchIntervalId = new WeakMap(), _currentRefetchInterval = new WeakMap(), _trackedProps = new WeakMap(), _QueryObserver_instances = new WeakSet(), executeFetch_fn = function(fetchOptions) {
1974
+ __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
1975
+ let promise = __privateGet(this, _currentQuery).fetch(
1976
+ this.options,
1977
+ fetchOptions
1978
+ );
1979
+ if (!fetchOptions?.throwOnError) {
1980
+ promise = promise.catch(noop);
1981
+ }
1982
+ return promise;
1983
+ }, updateStaleTimeout_fn = function() {
1984
+ __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
1985
+ const staleTime = resolveStaleTime(
1986
+ this.options.staleTime,
1987
+ __privateGet(this, _currentQuery)
1988
+ );
1989
+ if (isServer || __privateGet(this, _currentResult).isStale || !isValidTimeout(staleTime)) {
1990
+ return;
1991
+ }
1992
+ const time = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime);
1993
+ const timeout = time + 1;
1994
+ __privateSet(this, _staleTimeoutId, timeoutManager.setTimeout(() => {
1995
+ if (!__privateGet(this, _currentResult).isStale) {
1996
+ this.updateResult();
1997
+ }
1998
+ }, timeout));
1999
+ }, computeRefetchInterval_fn = function() {
2000
+ return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval) ?? false;
2001
+ }, updateRefetchInterval_fn = function(nextInterval) {
2002
+ __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
2003
+ __privateSet(this, _currentRefetchInterval, nextInterval);
2004
+ if (isServer || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) === false || !isValidTimeout(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) {
2005
+ return;
2006
+ }
2007
+ __privateSet(this, _refetchIntervalId, timeoutManager.setInterval(() => {
2008
+ if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2009
+ __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
2010
+ }
2011
+ }, __privateGet(this, _currentRefetchInterval)));
2012
+ }, updateTimers_fn = function() {
2013
+ __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
2014
+ __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this));
2015
+ }, clearStaleTimeout_fn = function() {
2016
+ if (__privateGet(this, _staleTimeoutId)) {
2017
+ timeoutManager.clearTimeout(__privateGet(this, _staleTimeoutId));
2018
+ __privateSet(this, _staleTimeoutId, void 0);
2019
+ }
2020
+ }, clearRefetchInterval_fn = function() {
2021
+ if (__privateGet(this, _refetchIntervalId)) {
2022
+ timeoutManager.clearInterval(__privateGet(this, _refetchIntervalId));
2023
+ __privateSet(this, _refetchIntervalId, void 0);
2024
+ }
2025
+ }, updateQuery_fn = function() {
2026
+ const query = __privateGet(this, _client).getQueryCache().build(__privateGet(this, _client), this.options);
2027
+ if (query === __privateGet(this, _currentQuery)) {
2028
+ return;
2029
+ }
2030
+ const prevQuery = __privateGet(this, _currentQuery);
2031
+ __privateSet(this, _currentQuery, query);
2032
+ __privateSet(this, _currentQueryInitialState, query.state);
2033
+ if (this.hasListeners()) {
2034
+ prevQuery?.removeObserver(this);
2035
+ query.addObserver(this);
2036
+ }
2037
+ }, notify_fn = function(notifyOptions) {
2038
+ notifyManager.batch(() => {
2039
+ if (notifyOptions.listeners) {
2040
+ this.listeners.forEach((listener) => {
2041
+ listener(__privateGet(this, _currentResult));
2042
+ });
2043
+ }
2044
+ __privateGet(this, _client).getQueryCache().notify({
2045
+ query: __privateGet(this, _currentQuery),
2046
+ type: "observerResultsUpdated"
2047
+ });
2048
+ });
2049
+ }, _a4);
2050
+ function shouldLoadOnMount(query, options) {
2051
+ return resolveEnabled(options.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options.retryOnMount === false);
2052
+ }
2053
+ function shouldFetchOnMount(query, options) {
2054
+ return shouldLoadOnMount(query, options) || query.state.data !== void 0 && shouldFetchOn(query, options, options.refetchOnMount);
2055
+ }
2056
+ function shouldFetchOn(query, options, field) {
2057
+ if (resolveEnabled(options.enabled, query) !== false && resolveStaleTime(options.staleTime, query) !== "static") {
2058
+ const value = typeof field === "function" ? field(query) : field;
2059
+ return value === "always" || value !== false && isStale(query, options);
2060
+ }
2061
+ return false;
2062
+ }
2063
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2064
+ return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options.suspense || query.state.status !== "error") && isStale(query, options);
2065
+ }
2066
+ function isStale(query, options) {
2067
+ return resolveEnabled(options.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options.staleTime, query));
2068
+ }
2069
+ function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
2070
+ if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
2071
+ return true;
2072
+ }
2073
+ return false;
2074
+ }
2075
+
2076
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/mutation.js
2077
+ function getDefaultState() {
2078
+ return {
2079
+ context: void 0,
2080
+ data: void 0,
2081
+ error: null,
2082
+ failureCount: 0,
2083
+ failureReason: null,
2084
+ isPaused: false,
2085
+ status: "idle",
2086
+ variables: void 0,
2087
+ submittedAt: 0
2088
+ };
2089
+ }
2090
+
2091
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/mutationObserver.js
2092
+ var _client2, _currentResult2, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn2, _a5;
2093
+ var MutationObserver = (_a5 = class extends Subscribable {
2094
+ constructor(client, options) {
2095
+ super();
2096
+ __privateAdd(this, _MutationObserver_instances);
2097
+ __privateAdd(this, _client2);
2098
+ __privateAdd(this, _currentResult2);
2099
+ __privateAdd(this, _currentMutation);
2100
+ __privateAdd(this, _mutateOptions);
2101
+ __privateSet(this, _client2, client);
2102
+ this.setOptions(options);
2103
+ this.bindMethods();
2104
+ __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
2105
+ }
2106
+ bindMethods() {
2107
+ this.mutate = this.mutate.bind(this);
2108
+ this.reset = this.reset.bind(this);
2109
+ }
2110
+ setOptions(options) {
2111
+ const prevOptions = this.options;
2112
+ this.options = __privateGet(this, _client2).defaultMutationOptions(options);
2113
+ if (!shallowEqualObjects(this.options, prevOptions)) {
2114
+ __privateGet(this, _client2).getMutationCache().notify({
2115
+ type: "observerOptionsUpdated",
2116
+ mutation: __privateGet(this, _currentMutation),
2117
+ observer: this
2118
+ });
2119
+ }
2120
+ if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
2121
+ this.reset();
2122
+ } else if (__privateGet(this, _currentMutation)?.state.status === "pending") {
2123
+ __privateGet(this, _currentMutation).setOptions(this.options);
2124
+ }
2125
+ }
2126
+ onUnsubscribe() {
2127
+ if (!this.hasListeners()) {
2128
+ __privateGet(this, _currentMutation)?.removeObserver(this);
2129
+ }
2130
+ }
2131
+ onMutationUpdate(action) {
2132
+ __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
2133
+ __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this, action);
2134
+ }
2135
+ getCurrentResult() {
2136
+ return __privateGet(this, _currentResult2);
2137
+ }
2138
+ reset() {
2139
+ __privateGet(this, _currentMutation)?.removeObserver(this);
2140
+ __privateSet(this, _currentMutation, void 0);
2141
+ __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
2142
+ __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this);
2143
+ }
2144
+ mutate(variables, options) {
2145
+ __privateSet(this, _mutateOptions, options);
2146
+ __privateGet(this, _currentMutation)?.removeObserver(this);
2147
+ __privateSet(this, _currentMutation, __privateGet(this, _client2).getMutationCache().build(__privateGet(this, _client2), this.options));
2148
+ __privateGet(this, _currentMutation).addObserver(this);
2149
+ return __privateGet(this, _currentMutation).execute(variables);
2150
+ }
2151
+ }, _client2 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() {
2152
+ const state = __privateGet(this, _currentMutation)?.state ?? getDefaultState();
2153
+ __privateSet(this, _currentResult2, {
2154
+ ...state,
2155
+ isPending: state.status === "pending",
2156
+ isSuccess: state.status === "success",
2157
+ isError: state.status === "error",
2158
+ isIdle: state.status === "idle",
2159
+ mutate: this.mutate,
2160
+ reset: this.reset
2161
+ });
2162
+ }, notify_fn2 = function(action) {
2163
+ notifyManager.batch(() => {
2164
+ if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
2165
+ const variables = __privateGet(this, _currentResult2).variables;
2166
+ const onMutateResult = __privateGet(this, _currentResult2).context;
2167
+ const context = {
2168
+ client: __privateGet(this, _client2),
2169
+ meta: this.options.meta,
2170
+ mutationKey: this.options.mutationKey
2171
+ };
2172
+ if (action?.type === "success") {
2173
+ try {
2174
+ __privateGet(this, _mutateOptions).onSuccess?.(
2175
+ action.data,
2176
+ variables,
2177
+ onMutateResult,
2178
+ context
2179
+ );
2180
+ } catch (e) {
2181
+ void Promise.reject(e);
2182
+ }
2183
+ try {
2184
+ __privateGet(this, _mutateOptions).onSettled?.(
2185
+ action.data,
2186
+ null,
2187
+ variables,
2188
+ onMutateResult,
2189
+ context
2190
+ );
2191
+ } catch (e) {
2192
+ void Promise.reject(e);
2193
+ }
2194
+ } else if (action?.type === "error") {
2195
+ try {
2196
+ __privateGet(this, _mutateOptions).onError?.(
2197
+ action.error,
2198
+ variables,
2199
+ onMutateResult,
2200
+ context
2201
+ );
2202
+ } catch (e) {
2203
+ void Promise.reject(e);
2204
+ }
2205
+ try {
2206
+ __privateGet(this, _mutateOptions).onSettled?.(
2207
+ void 0,
2208
+ action.error,
2209
+ variables,
2210
+ onMutateResult,
2211
+ context
2212
+ );
2213
+ } catch (e) {
2214
+ void Promise.reject(e);
2215
+ }
2216
+ }
2217
+ }
2218
+ this.listeners.forEach((listener) => {
2219
+ listener(__privateGet(this, _currentResult2));
2220
+ });
2221
+ });
2222
+ }, _a5);
2223
+ var QueryClientContext = React6.createContext(
2224
+ void 0
2225
+ );
2226
+ var useQueryClient = (queryClient) => {
2227
+ const client = React6.useContext(QueryClientContext);
2228
+ if (!client) {
2229
+ throw new Error("No QueryClient set, use QueryClientProvider to set one");
2230
+ }
2231
+ return client;
2232
+ };
2233
+ var IsRestoringContext = React6.createContext(false);
2234
+ var useIsRestoring = () => React6.useContext(IsRestoringContext);
2235
+ IsRestoringContext.Provider;
2236
+ function createValue() {
2237
+ let isReset = false;
2238
+ return {
2239
+ clearReset: () => {
2240
+ isReset = false;
2241
+ },
2242
+ reset: () => {
2243
+ isReset = true;
2244
+ },
2245
+ isReset: () => {
2246
+ return isReset;
2247
+ }
2248
+ };
2249
+ }
2250
+ var QueryErrorResetBoundaryContext = React6.createContext(createValue());
2251
+ var useQueryErrorResetBoundary = () => React6.useContext(QueryErrorResetBoundaryContext);
2252
+ var ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
2253
+ const throwOnError = query?.state.error && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
2254
+ if (options.suspense || options.experimental_prefetchInRender || throwOnError) {
2255
+ if (!errorResetBoundary.isReset()) {
2256
+ options.retryOnMount = false;
2257
+ }
2258
+ }
2259
+ };
2260
+ var useClearResetErrorBoundary = (errorResetBoundary) => {
2261
+ React6.useEffect(() => {
2262
+ errorResetBoundary.clearReset();
2263
+ }, [errorResetBoundary]);
2264
+ };
2265
+ var getHasError = ({
2266
+ result,
2267
+ errorResetBoundary,
2268
+ throwOnError,
2269
+ query,
2270
+ suspense
2271
+ }) => {
2272
+ return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));
2273
+ };
2274
+
2275
+ // ../../node_modules/.pnpm/@tanstack+react-query@5.90.20_react@18.3.1/node_modules/@tanstack/react-query/build/modern/suspense.js
2276
+ var ensureSuspenseTimers = (defaultedOptions) => {
2277
+ if (defaultedOptions.suspense) {
2278
+ const MIN_SUSPENSE_TIME_MS = 1e3;
2279
+ const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
2280
+ const originalStaleTime = defaultedOptions.staleTime;
2281
+ defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
2282
+ if (typeof defaultedOptions.gcTime === "number") {
2283
+ defaultedOptions.gcTime = Math.max(
2284
+ defaultedOptions.gcTime,
2285
+ MIN_SUSPENSE_TIME_MS
2286
+ );
2287
+ }
2288
+ }
2289
+ };
2290
+ var willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;
2291
+ var shouldSuspend = (defaultedOptions, result) => defaultedOptions?.suspense && result.isPending;
2292
+ var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
2293
+ errorResetBoundary.clearReset();
2294
+ });
2295
+ function useBaseQuery(options, Observer, queryClient) {
2296
+ if (process.env.NODE_ENV !== "production") {
2297
+ if (typeof options !== "object" || Array.isArray(options)) {
2298
+ throw new Error(
2299
+ 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'
2300
+ );
2301
+ }
2302
+ }
2303
+ const isRestoring = useIsRestoring();
2304
+ const errorResetBoundary = useQueryErrorResetBoundary();
2305
+ const client = useQueryClient();
2306
+ const defaultedOptions = client.defaultQueryOptions(options);
2307
+ client.getDefaultOptions().queries?._experimental_beforeQuery?.(
2308
+ defaultedOptions
2309
+ );
2310
+ const query = client.getQueryCache().get(defaultedOptions.queryHash);
2311
+ if (process.env.NODE_ENV !== "production") {
2312
+ if (!defaultedOptions.queryFn) {
2313
+ console.error(
2314
+ `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`
2315
+ );
2316
+ }
2317
+ }
2318
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
2319
+ ensureSuspenseTimers(defaultedOptions);
2320
+ ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query);
2321
+ useClearResetErrorBoundary(errorResetBoundary);
2322
+ const isNewCacheEntry = !client.getQueryCache().get(defaultedOptions.queryHash);
2323
+ const [observer] = React6.useState(
2324
+ () => new Observer(
2325
+ client,
2326
+ defaultedOptions
2327
+ )
2328
+ );
2329
+ const result = observer.getOptimisticResult(defaultedOptions);
2330
+ const shouldSubscribe = !isRestoring && options.subscribed !== false;
2331
+ React6.useSyncExternalStore(
2332
+ React6.useCallback(
2333
+ (onStoreChange) => {
2334
+ const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;
2335
+ observer.updateResult();
2336
+ return unsubscribe;
2337
+ },
2338
+ [observer, shouldSubscribe]
2339
+ ),
2340
+ () => observer.getCurrentResult(),
2341
+ () => observer.getCurrentResult()
2342
+ );
2343
+ React6.useEffect(() => {
2344
+ observer.setOptions(defaultedOptions);
2345
+ }, [defaultedOptions, observer]);
2346
+ if (shouldSuspend(defaultedOptions, result)) {
2347
+ throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
2348
+ }
2349
+ if (getHasError({
2350
+ result,
2351
+ errorResetBoundary,
2352
+ throwOnError: defaultedOptions.throwOnError,
2353
+ query,
2354
+ suspense: defaultedOptions.suspense
2355
+ })) {
2356
+ throw result.error;
2357
+ }
2358
+ client.getDefaultOptions().queries?._experimental_afterQuery?.(
2359
+ defaultedOptions,
2360
+ result
2361
+ );
2362
+ if (defaultedOptions.experimental_prefetchInRender && !isServer && willFetch(result, isRestoring)) {
2363
+ const promise = isNewCacheEntry ? (
2364
+ // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
2365
+ fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
2366
+ ) : (
2367
+ // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
2368
+ query?.promise
2369
+ );
2370
+ promise?.catch(noop).finally(() => {
2371
+ observer.updateResult();
2372
+ });
2373
+ }
2374
+ return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
2375
+ }
2376
+
2377
+ // ../../node_modules/.pnpm/@tanstack+react-query@5.90.20_react@18.3.1/node_modules/@tanstack/react-query/build/modern/useQuery.js
2378
+ function useQuery(options, queryClient) {
2379
+ return useBaseQuery(options, QueryObserver);
2380
+ }
2381
+ function useMutation(options, queryClient) {
2382
+ const client = useQueryClient();
2383
+ const [observer] = React6.useState(
2384
+ () => new MutationObserver(
2385
+ client,
2386
+ options
2387
+ )
2388
+ );
2389
+ React6.useEffect(() => {
2390
+ observer.setOptions(options);
2391
+ }, [observer, options]);
2392
+ const result = React6.useSyncExternalStore(
2393
+ React6.useCallback(
2394
+ (onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)),
2395
+ [observer]
2396
+ ),
2397
+ () => observer.getCurrentResult(),
2398
+ () => observer.getCurrentResult()
2399
+ );
2400
+ const mutate = React6.useCallback(
2401
+ (variables, mutateOptions) => {
2402
+ observer.mutate(variables, mutateOptions).catch(noop);
2403
+ },
2404
+ [observer]
2405
+ );
2406
+ if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) {
2407
+ throw result.error;
2408
+ }
2409
+ return { ...result, mutate, mutateAsync: result.mutate };
2410
+ }
2411
+
2412
+ // hooks/useOrbitalMutations.ts
2413
+ var ENTITY_EVENTS = {
2414
+ CREATE: "ENTITY_CREATE",
2415
+ UPDATE: "ENTITY_UPDATE",
2416
+ DELETE: "ENTITY_DELETE"
2417
+ };
2418
+ async function sendOrbitalEvent(orbitalName, eventPayload) {
2419
+ const response = await apiClient.post(
2420
+ `/orbitals/${orbitalName}/events`,
2421
+ eventPayload
2422
+ );
2423
+ return response;
2424
+ }
2425
+ function useOrbitalMutations(entityName, orbitalName, options) {
2426
+ const queryClient = useQueryClient();
2427
+ const events = {
2428
+ create: options?.events?.create || ENTITY_EVENTS.CREATE,
2429
+ update: options?.events?.update || ENTITY_EVENTS.UPDATE,
2430
+ delete: options?.events?.delete || ENTITY_EVENTS.DELETE
2431
+ };
2432
+ const log = (message, data) => {
2433
+ if (options?.debug) {
2434
+ console.log(`[useOrbitalMutations:${orbitalName}] ${message}`, data ?? "");
2435
+ }
2436
+ };
2437
+ const createMutation = useMutation({
2438
+ mutationFn: async (data) => {
2439
+ log("Creating entity", data);
2440
+ return sendOrbitalEvent(orbitalName, {
2441
+ event: events.create,
2442
+ payload: { data, entityType: entityName }
2443
+ });
2444
+ },
2445
+ onSuccess: (response) => {
2446
+ log("Create succeeded", response);
2447
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2448
+ },
2449
+ onError: (error) => {
2450
+ console.error(`[useOrbitalMutations] Create failed:`, error);
2451
+ }
2452
+ });
2453
+ const updateMutation = useMutation({
2454
+ mutationFn: async ({
2455
+ id,
2456
+ data
2457
+ }) => {
2458
+ log(`Updating entity ${id}`, data);
2459
+ return sendOrbitalEvent(orbitalName, {
2460
+ event: events.update,
2461
+ entityId: id,
2462
+ payload: { data, entityType: entityName }
2463
+ });
2464
+ },
2465
+ onSuccess: (response, variables) => {
2466
+ log("Update succeeded", response);
2467
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2468
+ queryClient.invalidateQueries({
2469
+ queryKey: entityDataKeys.detail(entityName, variables.id)
2470
+ });
2471
+ },
2472
+ onError: (error) => {
2473
+ console.error(`[useOrbitalMutations] Update failed:`, error);
2474
+ }
2475
+ });
2476
+ const deleteMutation = useMutation({
2477
+ mutationFn: async (id) => {
2478
+ log(`Deleting entity ${id}`);
2479
+ return sendOrbitalEvent(orbitalName, {
2480
+ event: events.delete,
2481
+ entityId: id,
2482
+ payload: { entityType: entityName }
2483
+ });
2484
+ },
2485
+ onSuccess: (response, id) => {
2486
+ log("Delete succeeded", response);
2487
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2488
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
2489
+ },
2490
+ onError: (error) => {
2491
+ console.error(`[useOrbitalMutations] Delete failed:`, error);
2492
+ }
2493
+ });
2494
+ return {
2495
+ // Async functions
2496
+ createEntity: async (data) => {
2497
+ return createMutation.mutateAsync(data);
2498
+ },
2499
+ updateEntity: async (id, data) => {
2500
+ if (!id) {
2501
+ console.warn("[useOrbitalMutations] Cannot update without ID");
2502
+ return;
2503
+ }
2504
+ return updateMutation.mutateAsync({ id, data });
2505
+ },
2506
+ deleteEntity: async (id) => {
2507
+ if (!id) {
2508
+ console.warn("[useOrbitalMutations] Cannot delete without ID");
2509
+ return;
2510
+ }
2511
+ return deleteMutation.mutateAsync(id);
2512
+ },
2513
+ // Mutation objects for fine-grained control
2514
+ createMutation,
2515
+ updateMutation,
2516
+ deleteMutation,
2517
+ // Aggregate states
2518
+ isCreating: createMutation.isPending,
2519
+ isUpdating: updateMutation.isPending,
2520
+ isDeleting: deleteMutation.isPending,
2521
+ isMutating: createMutation.isPending || updateMutation.isPending || deleteMutation.isPending,
2522
+ // Errors
2523
+ createError: createMutation.error,
2524
+ updateError: updateMutation.error,
2525
+ deleteError: deleteMutation.error
2526
+ };
2527
+ }
2528
+ function useSendOrbitalEvent(orbitalName) {
2529
+ const mutation = useMutation({
2530
+ mutationFn: async (payload) => {
2531
+ return sendOrbitalEvent(orbitalName, payload);
2532
+ }
2533
+ });
2534
+ return {
2535
+ sendEvent: async (event, payload, entityId) => {
2536
+ return mutation.mutateAsync({ event, payload, entityId });
2537
+ },
2538
+ isPending: mutation.isPending,
2539
+ error: mutation.error,
2540
+ data: mutation.data
2541
+ };
2542
+ }
2543
+
2544
+ // hooks/useEntityMutations.ts
2545
+ function entityToCollection(entityName) {
2546
+ return entityName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase() + "-list";
2547
+ }
2548
+ function useCreateEntity(entityName) {
2549
+ const queryClient = useQueryClient();
2550
+ const collection = entityToCollection(entityName);
2551
+ return useMutation({
2552
+ mutationFn: async (data) => {
2553
+ console.log(`[useCreateEntity] Creating ${entityName}:`, data);
2554
+ const response = await apiClient.post(
2555
+ `/${collection}`,
2556
+ data
2557
+ );
2558
+ return response.data;
2559
+ },
2560
+ onSuccess: () => {
2561
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2562
+ },
2563
+ onError: (error) => {
2564
+ console.error(`[useCreateEntity] Failed to create ${entityName}:`, error);
2565
+ }
2566
+ });
2567
+ }
2568
+ function useUpdateEntity(entityName) {
2569
+ const queryClient = useQueryClient();
2570
+ const collection = entityToCollection(entityName);
2571
+ return useMutation({
2572
+ mutationFn: async ({ id, data }) => {
2573
+ console.log(`[useUpdateEntity] Updating ${entityName} ${id}:`, data);
2574
+ const response = await apiClient.patch(
2575
+ `/${collection}/${id}`,
2576
+ data
2577
+ );
2578
+ return response.data;
2579
+ },
2580
+ onSuccess: (_, variables) => {
2581
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2582
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.detail(entityName, variables.id) });
2583
+ },
2584
+ onError: (error) => {
2585
+ console.error(`[useUpdateEntity] Failed to update ${entityName}:`, error);
2586
+ }
2587
+ });
2588
+ }
2589
+ function useDeleteEntity(entityName) {
2590
+ const queryClient = useQueryClient();
2591
+ const collection = entityToCollection(entityName);
2592
+ return useMutation({
2593
+ mutationFn: async (id) => {
2594
+ console.log(`[useDeleteEntity] Deleting ${entityName} ${id}`);
2595
+ await apiClient.delete(`/${collection}/${id}`);
2596
+ return { id };
2597
+ },
2598
+ onSuccess: (_, id) => {
2599
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2600
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
2601
+ },
2602
+ onError: (error) => {
2603
+ console.error(`[useDeleteEntity] Failed to delete ${entityName}:`, error);
2604
+ }
2605
+ });
2606
+ }
2607
+ async function sendOrbitalMutation(orbitalName, event, entityId, payload) {
2608
+ const response = await apiClient.post(
2609
+ `/orbitals/${orbitalName}/events`,
2610
+ { event, entityId, payload }
2611
+ );
2612
+ return response;
2613
+ }
2614
+ function useEntityMutations(entityName, options) {
2615
+ const queryClient = useQueryClient();
2616
+ const useOrbitalRoute = !!options?.orbitalName;
2617
+ const events = {
2618
+ create: options?.events?.create || ENTITY_EVENTS.CREATE,
2619
+ update: options?.events?.update || ENTITY_EVENTS.UPDATE,
2620
+ delete: options?.events?.delete || ENTITY_EVENTS.DELETE
2621
+ };
2622
+ const createMutation = useCreateEntity(entityName);
2623
+ const updateMutation = useUpdateEntity(entityName);
2624
+ const deleteMutation = useDeleteEntity(entityName);
2625
+ const orbitalCreateMutation = useMutation({
2626
+ mutationFn: async (data) => {
2627
+ return sendOrbitalMutation(options.orbitalName, events.create, void 0, {
2628
+ data,
2629
+ entityType: entityName
2630
+ });
2631
+ },
2632
+ onSuccess: () => {
2633
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2634
+ }
2635
+ });
2636
+ const orbitalUpdateMutation = useMutation({
2637
+ mutationFn: async ({ id, data }) => {
2638
+ return sendOrbitalMutation(options.orbitalName, events.update, id, {
2639
+ data,
2640
+ entityType: entityName
2641
+ });
2642
+ },
2643
+ onSuccess: (_, variables) => {
2644
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2645
+ queryClient.invalidateQueries({
2646
+ queryKey: entityDataKeys.detail(entityName, variables.id)
2647
+ });
2648
+ }
2649
+ });
2650
+ const orbitalDeleteMutation = useMutation({
2651
+ mutationFn: async (id) => {
2652
+ return sendOrbitalMutation(options.orbitalName, events.delete, id, {
2653
+ entityType: entityName
2654
+ });
2655
+ },
2656
+ onSuccess: (_, id) => {
2657
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2658
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
2659
+ }
2660
+ });
2661
+ const activeMutations = {
2662
+ create: useOrbitalRoute ? orbitalCreateMutation : createMutation,
2663
+ update: useOrbitalRoute ? orbitalUpdateMutation : updateMutation,
2664
+ delete: useOrbitalRoute ? orbitalDeleteMutation : deleteMutation
2665
+ };
2666
+ return {
2667
+ // Async functions that can be called directly
2668
+ // Accepts either (data) or (entityName, data) for compiler compatibility
2669
+ createEntity: async (entityOrData, data) => {
2670
+ const actualData = typeof entityOrData === "string" ? data : entityOrData;
2671
+ if (!actualData) {
2672
+ console.warn("[useEntityMutations] Cannot create entity without data");
2673
+ return;
2674
+ }
2675
+ return activeMutations.create.mutateAsync(actualData);
2676
+ },
2677
+ updateEntity: async (id, data) => {
2678
+ if (!id) {
2679
+ console.warn("[useEntityMutations] Cannot update entity without ID");
2680
+ return;
2681
+ }
2682
+ return activeMutations.update.mutateAsync({ id, data });
2683
+ },
2684
+ deleteEntity: async (id) => {
2685
+ if (!id) {
2686
+ console.warn("[useEntityMutations] Cannot delete entity without ID");
2687
+ return;
2688
+ }
2689
+ return activeMutations.delete.mutateAsync(id);
2690
+ },
2691
+ // Mutation states for UI feedback
2692
+ isCreating: activeMutations.create.isPending,
2693
+ isUpdating: activeMutations.update.isPending,
2694
+ isDeleting: activeMutations.delete.isPending,
2695
+ createError: activeMutations.create.error,
2696
+ updateError: activeMutations.update.error,
2697
+ deleteError: activeMutations.delete.error
2698
+ };
2699
+ }
2700
+ function useEntities() {
2701
+ const entities = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2702
+ return {
2703
+ entities,
2704
+ getEntity,
2705
+ getByType,
2706
+ getAllEntities,
2707
+ getSingleton,
2708
+ spawnEntity,
2709
+ updateEntity,
2710
+ updateSingleton,
2711
+ removeEntity,
2712
+ clearEntities
2713
+ };
2714
+ }
2715
+ function useEntity2(id) {
2716
+ const entities = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2717
+ return entities.get(id);
2718
+ }
2719
+ function useEntitiesByType(type) {
2720
+ const entities = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2721
+ return [...entities.values()].filter((e) => e.type === type);
2722
+ }
2723
+ function useSingletonEntity(type) {
2724
+ const entities = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2725
+ return [...entities.values()].find((e) => e.type === type);
2726
+ }
2727
+ function usePlayer() {
2728
+ const player = useSingletonEntity("Player");
2729
+ const update = useCallback((updates) => {
2730
+ if (player) updateEntity(player.id, updates);
2731
+ }, [player?.id]);
2732
+ return { player, updatePlayer: update };
2733
+ }
2734
+ function usePhysics() {
2735
+ const physics = useSingletonEntity("Physics");
2736
+ const update = useCallback((updates) => {
2737
+ if (physics) updateEntity(physics.id, updates);
2738
+ }, [physics?.id]);
2739
+ return { physics, updatePhysics: update };
2740
+ }
2741
+ function useInput() {
2742
+ const input = useSingletonEntity("Input");
2743
+ const update = useCallback((updates) => {
2744
+ if (input) updateEntity(input.id, updates);
2745
+ }, [input?.id]);
2746
+ return { input, updateInput: update };
2747
+ }
2748
+
2749
+ // hooks/useAuthContext.ts
2750
+ function useAuthContext() {
2751
+ return {
2752
+ user: null,
2753
+ loading: false,
2754
+ signIn: void 0,
2755
+ signOut: void 0
2756
+ };
2757
+ }
2758
+ var API_BASE = import.meta.env.VITE_API_URL || "http://localhost:3000";
2759
+ function getUserId() {
2760
+ return localStorage.getItem("userId") || "anonymous";
2761
+ }
2762
+ async function fetchWithAuth(endpoint, options) {
2763
+ const userId = getUserId();
2764
+ const response = await fetch(`${API_BASE}${endpoint}`, {
2765
+ ...options,
2766
+ headers: {
2767
+ "Content-Type": "application/json",
2768
+ "x-user-id": userId,
2769
+ ...options?.headers
2770
+ }
2771
+ });
2772
+ if (!response.ok) {
2773
+ const error = await response.json().catch(() => ({ error: response.statusText }));
2774
+ throw new Error(error.error || error.message || "Request failed");
2775
+ }
2776
+ return response.json();
2777
+ }
2778
+ function useGitHubStatus() {
2779
+ return useQuery({
2780
+ queryKey: ["github", "status"],
2781
+ queryFn: () => fetchWithAuth("/api/github/status"),
2782
+ staleTime: 6e4,
2783
+ // 1 minute
2784
+ retry: false
2785
+ });
2786
+ }
2787
+ function useConnectGitHub() {
2788
+ const connectGitHub = useCallback(() => {
2789
+ const userId = getUserId();
2790
+ const state = btoa(JSON.stringify({ userId, returnUrl: window.location.href }));
2791
+ window.location.href = `${API_BASE}/api/github/oauth/authorize?state=${state}`;
2792
+ }, []);
2793
+ return { connectGitHub };
2794
+ }
2795
+ function useDisconnectGitHub() {
2796
+ const queryClient = useQueryClient();
2797
+ return useMutation({
2798
+ mutationFn: () => fetchWithAuth("/api/github/disconnect", { method: "POST" }),
2799
+ onSuccess: () => {
2800
+ queryClient.invalidateQueries({ queryKey: ["github", "status"] });
2801
+ queryClient.removeQueries({ queryKey: ["github", "repos"] });
2802
+ }
2803
+ });
2804
+ }
2805
+ function useGitHubRepos(page = 1, perPage = 30) {
2806
+ return useQuery({
2807
+ queryKey: ["github", "repos", page, perPage],
2808
+ queryFn: () => fetchWithAuth(`/api/github/repos?page=${page}&per_page=${perPage}`),
2809
+ enabled: true,
2810
+ // Only fetch if user is connected
2811
+ staleTime: 3e5
2812
+ // 5 minutes
2813
+ });
2814
+ }
2815
+ function useGitHubRepo(owner, repo, enabled = true) {
2816
+ return useQuery({
2817
+ queryKey: ["github", "repo", owner, repo],
2818
+ queryFn: () => fetchWithAuth(`/api/github/repos/${owner}/${repo}`),
2819
+ enabled: enabled && !!owner && !!repo,
2820
+ staleTime: 3e5
2821
+ // 5 minutes
2822
+ });
2823
+ }
2824
+ function useGitHubBranches(owner, repo, enabled = true) {
2825
+ return useQuery({
2826
+ queryKey: ["github", "branches", owner, repo],
2827
+ queryFn: () => fetchWithAuth(`/api/github/repos/${owner}/${repo}/branches`),
2828
+ enabled: enabled && !!owner && !!repo,
2829
+ staleTime: 6e4
2830
+ // 1 minute
2831
+ });
2832
+ }
2833
+
2834
+ export { ENTITY_EVENTS, entityDataKeys, parseQueryBinding, useAgentChat, useAuthContext, useCompile, useConnectGitHub, useCreateEntity, useDeepAgentGeneration, useDeleteEntity, useDisconnectGitHub, useEntities, useEntitiesByType, useEntity, useEntity2, useEntityDetail, useEntityList, useEntityMutations, useExtensions, useFileEditor, useFileSystem, useGitHubBranches, useGitHubRepo, useGitHubRepos, useGitHubStatus, useInput, useOrbitalHistory, useOrbitalMutations, usePaginatedEntityList, usePhysics, usePlayer, usePreview, useQuerySingleton, useSelectedEntity, useSendOrbitalEvent, useSingletonEntity, useUIEvents, useUpdateEntity, useValidation };