@almadar/ui 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2262 @@
1
+ import * as React4 from 'react';
2
+ import { createContext, useCallback, useState, useEffect, useMemo, useContext, useRef, useSyncExternalStore } from 'react';
3
+ import 'react/jsx-runtime';
4
+
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
9
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
10
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
11
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
12
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
13
+ function useOrbitalHistory(options) {
14
+ const { appId, authToken, userId, onHistoryChange, onRevertSuccess } = options;
15
+ const getHeaders2 = useCallback(() => {
16
+ const headers = {
17
+ "Content-Type": "application/json"
18
+ };
19
+ if (authToken) {
20
+ headers["Authorization"] = `Bearer ${authToken}`;
21
+ }
22
+ if (userId) {
23
+ headers["x-user-id"] = userId;
24
+ }
25
+ return headers;
26
+ }, [authToken, userId]);
27
+ const [timeline, setTimeline] = useState([]);
28
+ const [currentVersion, setCurrentVersion] = useState(1);
29
+ const [isLoading, setIsLoading] = useState(false);
30
+ const [error, setError] = useState(null);
31
+ const refresh = useCallback(async () => {
32
+ if (!appId) return;
33
+ setIsLoading(true);
34
+ setError(null);
35
+ try {
36
+ const headers = getHeaders2();
37
+ const [changesetsRes, snapshotsRes] = await Promise.all([
38
+ fetch(`/api/graphs/${appId}/history/changesets`, { headers }),
39
+ fetch(`/api/graphs/${appId}/history/snapshots`, { headers })
40
+ ]);
41
+ if (!changesetsRes.ok) {
42
+ throw new Error(`Failed to fetch changesets: ${changesetsRes.status}`);
43
+ }
44
+ if (!snapshotsRes.ok) {
45
+ throw new Error(`Failed to fetch snapshots: ${snapshotsRes.status}`);
46
+ }
47
+ const changesetsData = await changesetsRes.json();
48
+ const snapshotsData = await snapshotsRes.json();
49
+ const changesetItems = (changesetsData.changesets || []).map((cs) => ({
50
+ id: cs.id,
51
+ type: "changeset",
52
+ version: cs.version,
53
+ timestamp: cs.timestamp,
54
+ description: `Version ${cs.version}`,
55
+ source: cs.source,
56
+ summary: cs.summary
57
+ }));
58
+ const snapshotItems = (snapshotsData.snapshots || []).map((snap) => ({
59
+ id: snap.id,
60
+ type: "snapshot",
61
+ version: snap.version,
62
+ timestamp: snap.timestamp,
63
+ description: snap.reason || `Snapshot v${snap.version}`,
64
+ reason: snap.reason
65
+ }));
66
+ const mergedTimeline = [...changesetItems, ...snapshotItems].sort(
67
+ (a, b) => b.timestamp - a.timestamp
68
+ );
69
+ setTimeline(mergedTimeline);
70
+ if (mergedTimeline.length > 0) {
71
+ setCurrentVersion(mergedTimeline[0].version);
72
+ }
73
+ } catch (err) {
74
+ console.error("[useOrbitalHistory] Failed to load history:", err);
75
+ setError(err instanceof Error ? err.message : "Failed to load history");
76
+ } finally {
77
+ setIsLoading(false);
78
+ }
79
+ }, [appId, getHeaders2]);
80
+ const revertToSnapshot = useCallback(async (snapshotId) => {
81
+ if (!appId) {
82
+ return { success: false, error: "No app ID provided" };
83
+ }
84
+ try {
85
+ const response = await fetch(`/api/graphs/${appId}/history/revert/${snapshotId}`, {
86
+ method: "POST",
87
+ headers: getHeaders2()
88
+ });
89
+ if (!response.ok) {
90
+ const errorData = await response.json().catch(() => ({}));
91
+ throw new Error(errorData.error || `Failed to revert: ${response.status}`);
92
+ }
93
+ const data = await response.json();
94
+ if (data.success && data.schema) {
95
+ await refresh();
96
+ onRevertSuccess?.(data.schema);
97
+ return {
98
+ success: true,
99
+ restoredSchema: data.schema
100
+ };
101
+ }
102
+ return {
103
+ success: false,
104
+ error: data.error || "Unknown error during revert"
105
+ };
106
+ } catch (err) {
107
+ console.error("[useOrbitalHistory] Failed to revert:", err);
108
+ return {
109
+ success: false,
110
+ error: err instanceof Error ? err.message : "Failed to revert"
111
+ };
112
+ }
113
+ }, [appId, getHeaders2, refresh, onRevertSuccess]);
114
+ useEffect(() => {
115
+ if (appId && authToken && userId) {
116
+ refresh();
117
+ }
118
+ }, [appId, authToken, userId]);
119
+ useEffect(() => {
120
+ onHistoryChange?.(timeline);
121
+ }, [timeline]);
122
+ return {
123
+ timeline,
124
+ currentVersion,
125
+ isLoading,
126
+ error,
127
+ revertToSnapshot,
128
+ refresh
129
+ };
130
+ }
131
+ function useFileSystem() {
132
+ const [status, setStatus] = useState("idle");
133
+ const [error, setError] = useState(null);
134
+ const [isLoading, setIsLoading] = useState(false);
135
+ const [files, setFiles] = useState([]);
136
+ const [selectedFile, setSelectedFile] = useState(null);
137
+ const [selectedPath, setSelectedPath] = useState(null);
138
+ const [previewUrl, setPreviewUrl] = useState(null);
139
+ const [fileContents, setFileContents] = useState(/* @__PURE__ */ new Map());
140
+ const boot = useCallback(async () => {
141
+ setStatus("booting");
142
+ setError(null);
143
+ setIsLoading(true);
144
+ try {
145
+ console.log("[useFileSystem] Booting WebContainer...");
146
+ await new Promise((resolve) => setTimeout(resolve, 100));
147
+ setStatus("ready");
148
+ } catch (err) {
149
+ setError(err instanceof Error ? err.message : "Failed to boot");
150
+ setStatus("error");
151
+ } finally {
152
+ setIsLoading(false);
153
+ }
154
+ }, []);
155
+ const mountFiles = useCallback(async (filesToMount) => {
156
+ setIsLoading(true);
157
+ try {
158
+ let filesArray;
159
+ if (Array.isArray(filesToMount)) {
160
+ filesArray = filesToMount;
161
+ } else {
162
+ filesArray = [];
163
+ const flattenTree = (obj, basePath = "") => {
164
+ for (const [key, value] of Object.entries(obj)) {
165
+ const path = basePath ? `${basePath}/${key}` : key;
166
+ if (value && typeof value === "object" && "file" in value) {
167
+ const fileObj = value;
168
+ filesArray.push({ path, content: fileObj.file.contents || "" });
169
+ } else if (value && typeof value === "object" && "directory" in value) {
170
+ const dirObj = value;
171
+ flattenTree(dirObj.directory, path);
172
+ }
173
+ }
174
+ };
175
+ flattenTree(filesToMount);
176
+ }
177
+ const newContents = /* @__PURE__ */ new Map();
178
+ for (const file of filesArray) {
179
+ newContents.set(file.path, file.content);
180
+ }
181
+ setFileContents(newContents);
182
+ const newTree = [];
183
+ for (const file of filesArray) {
184
+ const parts = file.path.split("/").filter(Boolean);
185
+ let current = newTree;
186
+ for (let i = 0; i < parts.length; i++) {
187
+ const part = parts[i];
188
+ const isFile = i === parts.length - 1;
189
+ const currentPath = "/" + parts.slice(0, i + 1).join("/");
190
+ let node = current.find((n) => n.name === part);
191
+ if (!node) {
192
+ node = {
193
+ path: currentPath,
194
+ name: part,
195
+ type: isFile ? "file" : "directory",
196
+ children: isFile ? void 0 : []
197
+ };
198
+ current.push(node);
199
+ }
200
+ if (!isFile && node && node.children) {
201
+ current = node.children;
202
+ }
203
+ }
204
+ }
205
+ setFiles(newTree);
206
+ setStatus("running");
207
+ } catch (err) {
208
+ console.error("[useFileSystem] Failed to mount files:", err);
209
+ } finally {
210
+ setIsLoading(false);
211
+ }
212
+ }, []);
213
+ const readFile = useCallback(async (path) => {
214
+ return fileContents.get(path) || "";
215
+ }, [fileContents]);
216
+ const writeFile = useCallback(async (path, content) => {
217
+ setFileContents((prev) => {
218
+ const next = new Map(prev);
219
+ next.set(path, content);
220
+ return next;
221
+ });
222
+ }, []);
223
+ const selectFile = useCallback(async (path) => {
224
+ const content = fileContents.get(path) || "";
225
+ const ext = path.split(".").pop()?.toLowerCase() || "";
226
+ const languageMap = {
227
+ ts: "typescript",
228
+ tsx: "typescript",
229
+ js: "javascript",
230
+ jsx: "javascript",
231
+ json: "json",
232
+ md: "markdown",
233
+ css: "css",
234
+ html: "html",
235
+ orb: "json"
236
+ };
237
+ setSelectedPath(path);
238
+ setSelectedFile({
239
+ path,
240
+ content,
241
+ language: languageMap[ext] || "plaintext",
242
+ isDirty: false
243
+ });
244
+ }, [fileContents]);
245
+ const updateContent = useCallback((pathOrContent, contentArg) => {
246
+ const path = contentArg !== void 0 ? pathOrContent : selectedPath;
247
+ const content = contentArg !== void 0 ? contentArg : pathOrContent;
248
+ if (!path) {
249
+ console.warn("[useFileSystem] updateContent called without path and no file selected");
250
+ return;
251
+ }
252
+ setFileContents((prev) => {
253
+ const next = new Map(prev);
254
+ next.set(path, content);
255
+ return next;
256
+ });
257
+ if (selectedPath === path) {
258
+ setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
259
+ }
260
+ }, [selectedPath]);
261
+ const updateSelectedContent = useCallback((content) => {
262
+ setSelectedFile((prev) => prev ? { ...prev, content, isDirty: true } : null);
263
+ }, []);
264
+ const refreshTree = useCallback(async () => {
265
+ console.log("[useFileSystem] Refreshing tree");
266
+ }, []);
267
+ const runCommand = useCallback(async (command) => {
268
+ console.log("[useFileSystem] Running command:", command);
269
+ return { exitCode: 0, output: "" };
270
+ }, []);
271
+ const startDevServer = useCallback(async () => {
272
+ console.log("[useFileSystem] Starting dev server");
273
+ setPreviewUrl("http://localhost:5173");
274
+ }, []);
275
+ return {
276
+ status,
277
+ error,
278
+ isLoading,
279
+ files,
280
+ selectedFile,
281
+ selectedPath,
282
+ previewUrl,
283
+ boot,
284
+ mountFiles,
285
+ readFile,
286
+ writeFile,
287
+ selectFile,
288
+ updateContent,
289
+ updateSelectedContent,
290
+ refreshTree,
291
+ runCommand,
292
+ startDevServer
293
+ };
294
+ }
295
+ var defaultManifest = {
296
+ languages: {
297
+ typescript: { extensions: [".ts", ".tsx"], icon: "ts", color: "#3178c6" },
298
+ javascript: { extensions: [".js", ".jsx"], icon: "js", color: "#f7df1e" },
299
+ json: { extensions: [".json", ".orb"], icon: "json", color: "#000000" },
300
+ css: { extensions: [".css"], icon: "css", color: "#264de4" },
301
+ html: { extensions: [".html"], icon: "html", color: "#e34c26" },
302
+ markdown: { extensions: [".md", ".mdx"], icon: "md", color: "#083fa1" }
303
+ },
304
+ extensions: []
305
+ };
306
+ function useExtensions(options) {
307
+ const { appId, loadOnMount = true } = options;
308
+ const [extensions, setExtensions] = useState([]);
309
+ const [manifest] = useState(defaultManifest);
310
+ const [isLoading, setIsLoading] = useState(false);
311
+ const [error, setError] = useState(null);
312
+ const loadExtension = useCallback(async (extensionId) => {
313
+ console.log("[useExtensions] Loading extension:", extensionId);
314
+ }, []);
315
+ const loadExtensions = useCallback(async () => {
316
+ setIsLoading(true);
317
+ setError(null);
318
+ try {
319
+ const defaultExtensions = [
320
+ { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
321
+ { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
322
+ { id: "json", name: "JSON", language: "json", loaded: true },
323
+ { id: "css", name: "CSS", language: "css", loaded: true },
324
+ { id: "html", name: "HTML", language: "html", loaded: true },
325
+ { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
326
+ ];
327
+ setExtensions(defaultExtensions);
328
+ } catch (err) {
329
+ setError(err instanceof Error ? err.message : "Failed to load extensions");
330
+ } finally {
331
+ setIsLoading(false);
332
+ }
333
+ }, []);
334
+ const getExtensionForFile = useCallback((filename) => {
335
+ const ext = filename.split(".").pop()?.toLowerCase();
336
+ if (!ext) return null;
337
+ const languageMap = {
338
+ ts: "typescript",
339
+ tsx: "typescript",
340
+ js: "javascript",
341
+ jsx: "javascript",
342
+ json: "json",
343
+ md: "markdown",
344
+ css: "css",
345
+ html: "html",
346
+ orb: "json"
347
+ };
348
+ const language = languageMap[ext];
349
+ if (!language) return null;
350
+ return extensions.find((e) => e.language === language) || null;
351
+ }, [extensions]);
352
+ useEffect(() => {
353
+ if (!appId || !loadOnMount) return;
354
+ const loadExtensions2 = async () => {
355
+ setIsLoading(true);
356
+ setError(null);
357
+ try {
358
+ const defaultExtensions = [
359
+ { id: "typescript", name: "TypeScript", language: "typescript", loaded: true },
360
+ { id: "javascript", name: "JavaScript", language: "javascript", loaded: true },
361
+ { id: "json", name: "JSON", language: "json", loaded: true },
362
+ { id: "css", name: "CSS", language: "css", loaded: true },
363
+ { id: "html", name: "HTML", language: "html", loaded: true },
364
+ { id: "markdown", name: "Markdown", language: "markdown", loaded: true }
365
+ ];
366
+ setExtensions(defaultExtensions);
367
+ } catch (err) {
368
+ setError(err instanceof Error ? err.message : "Failed to load extensions");
369
+ } finally {
370
+ setIsLoading(false);
371
+ }
372
+ };
373
+ loadExtensions2();
374
+ }, [appId, loadOnMount]);
375
+ return {
376
+ extensions,
377
+ manifest,
378
+ isLoading,
379
+ error,
380
+ loadExtension,
381
+ loadExtensions,
382
+ getExtensionForFile
383
+ };
384
+ }
385
+ function useFileEditor(options) {
386
+ const { extensions, fileSystem, onSchemaUpdate } = options;
387
+ const [openFiles, setOpenFiles] = useState([]);
388
+ const [activeFilePath, setActiveFilePath] = useState(null);
389
+ const [isSaving, setIsSaving] = useState(false);
390
+ const activeFile = openFiles.find((f) => f.path === activeFilePath) || null;
391
+ const openFile = useCallback(async (path) => {
392
+ const existing = openFiles.find((f) => f.path === path);
393
+ if (existing) {
394
+ setActiveFilePath(path);
395
+ return;
396
+ }
397
+ try {
398
+ const content = await fileSystem.readFile(path);
399
+ const ext = extensions.getExtensionForFile(path);
400
+ const newFile = {
401
+ path,
402
+ content,
403
+ isDirty: false,
404
+ language: ext?.language
405
+ };
406
+ setOpenFiles((prev) => [...prev, newFile]);
407
+ setActiveFilePath(path);
408
+ } catch (err) {
409
+ console.error("[useFileEditor] Failed to open file:", err);
410
+ }
411
+ }, [openFiles, fileSystem, extensions]);
412
+ const closeFile = useCallback((path) => {
413
+ setOpenFiles((prev) => prev.filter((f) => f.path !== path));
414
+ if (activeFilePath === path) {
415
+ const remaining = openFiles.filter((f) => f.path !== path);
416
+ setActiveFilePath(remaining.length > 0 ? remaining[0].path : null);
417
+ }
418
+ }, [activeFilePath, openFiles]);
419
+ const setActiveFile = useCallback((path) => {
420
+ setActiveFilePath(path);
421
+ }, []);
422
+ const updateFileContent = useCallback((path, content) => {
423
+ setOpenFiles(
424
+ (prev) => prev.map(
425
+ (f) => f.path === path ? { ...f, content, isDirty: true } : f
426
+ )
427
+ );
428
+ }, []);
429
+ const handleFileEdit = useCallback(async (path, content) => {
430
+ try {
431
+ await fileSystem.writeFile(path, content);
432
+ let action = "saved";
433
+ if (path.endsWith(".orb") || path.endsWith("schema.json")) {
434
+ try {
435
+ const schema = JSON.parse(content);
436
+ await onSchemaUpdate?.(schema);
437
+ action = "updated_schema";
438
+ } catch {
439
+ }
440
+ } else if (path.includes("/extensions/")) {
441
+ action = path.endsWith(".new") ? "converted_extension" : "saved_extension";
442
+ }
443
+ return { success: true, action };
444
+ } catch (err) {
445
+ return {
446
+ success: false,
447
+ error: err instanceof Error ? err.message : "Failed to save file"
448
+ };
449
+ }
450
+ }, [fileSystem, onSchemaUpdate]);
451
+ const saveFile = useCallback(async (path) => {
452
+ const file = openFiles.find((f) => f.path === path);
453
+ if (!file) return;
454
+ setIsSaving(true);
455
+ try {
456
+ await fileSystem.writeFile(path, file.content);
457
+ setOpenFiles(
458
+ (prev) => prev.map(
459
+ (f) => f.path === path ? { ...f, isDirty: false } : f
460
+ )
461
+ );
462
+ if (path.endsWith(".orb") || path.endsWith("schema.json")) {
463
+ try {
464
+ const schema = JSON.parse(file.content);
465
+ await onSchemaUpdate?.(schema);
466
+ } catch {
467
+ }
468
+ }
469
+ } catch (err) {
470
+ console.error("[useFileEditor] Failed to save file:", err);
471
+ } finally {
472
+ setIsSaving(false);
473
+ }
474
+ }, [openFiles, fileSystem, onSchemaUpdate]);
475
+ const saveAllFiles = useCallback(async () => {
476
+ setIsSaving(true);
477
+ try {
478
+ const dirtyFiles = openFiles.filter((f) => f.isDirty);
479
+ for (const file of dirtyFiles) {
480
+ await saveFile(file.path);
481
+ }
482
+ } finally {
483
+ setIsSaving(false);
484
+ }
485
+ }, [openFiles, saveFile]);
486
+ return {
487
+ openFiles,
488
+ activeFile,
489
+ isSaving,
490
+ openFile,
491
+ closeFile,
492
+ setActiveFile,
493
+ updateFileContent,
494
+ handleFileEdit,
495
+ saveFile,
496
+ saveAllFiles
497
+ };
498
+ }
499
+ function useCompile() {
500
+ const [isCompiling, setIsCompiling] = useState(false);
501
+ const [stage, setStage] = useState("idle");
502
+ const [lastResult, setLastResult] = useState(null);
503
+ const [error, setError] = useState(null);
504
+ const compileSchema = useCallback(async (schema) => {
505
+ setIsCompiling(true);
506
+ setStage("compiling");
507
+ setError(null);
508
+ try {
509
+ console.log("[useCompile] Compiling schema:", schema.name);
510
+ const result = {
511
+ success: true,
512
+ files: []
513
+ };
514
+ setLastResult(result);
515
+ setStage("done");
516
+ return result;
517
+ } catch (err) {
518
+ const errorMessage = err instanceof Error ? err.message : "Compilation failed";
519
+ setError(errorMessage);
520
+ setStage("error");
521
+ setLastResult({ success: false, errors: [errorMessage] });
522
+ return null;
523
+ } finally {
524
+ setIsCompiling(false);
525
+ }
526
+ }, []);
527
+ return {
528
+ isCompiling,
529
+ stage,
530
+ lastResult,
531
+ error,
532
+ compileSchema
533
+ };
534
+ }
535
+ function usePreview(options) {
536
+ const [previewUrl, setPreviewUrl] = useState(null);
537
+ const [isLoading, setIsLoading] = useState(!!options?.appId);
538
+ const [error, setError] = useState(null);
539
+ const [loadError, setLoadError] = useState(null);
540
+ const [app, setApp] = useState(null);
541
+ const [isFullscreen, setIsFullscreen] = useState(false);
542
+ const [isExecutingEvent, setIsExecutingEvent] = useState(false);
543
+ const [errorToast, setErrorToast] = useState(null);
544
+ const [currentStateName, setCurrentStateName] = useState(null);
545
+ const [notificationsList, setNotificationsList] = useState([]);
546
+ const [isPanelOpen, setIsPanelOpen] = useState(false);
547
+ const notifications = useMemo(() => ({
548
+ notifications: notificationsList,
549
+ isPanelOpen,
550
+ closePanel: () => setIsPanelOpen(false),
551
+ dismissNotification: (id) => {
552
+ setNotificationsList((prev) => prev.filter((n) => n.id !== id));
553
+ },
554
+ markAsRead: (id) => {
555
+ setNotificationsList(
556
+ (prev) => prev.map((n) => n.id === id ? { ...n, read: true } : n)
557
+ );
558
+ },
559
+ clearAll: () => setNotificationsList([])
560
+ }), [notificationsList, isPanelOpen]);
561
+ useEffect(() => {
562
+ const appId = options?.appId;
563
+ if (!appId) {
564
+ setApp(null);
565
+ setIsLoading(false);
566
+ return;
567
+ }
568
+ console.log("[usePreview] Setting up preview for app:", appId);
569
+ setPreviewUrl(`/api/orbitals/${appId}`);
570
+ setIsLoading(false);
571
+ }, [options?.appId]);
572
+ const startPreview = useCallback(async () => {
573
+ console.log("[usePreview] startPreview called");
574
+ }, []);
575
+ const stopPreview = useCallback(async () => {
576
+ setIsLoading(true);
577
+ try {
578
+ console.log("[usePreview] Stopping preview server...");
579
+ setPreviewUrl(null);
580
+ setApp(null);
581
+ } finally {
582
+ setIsLoading(false);
583
+ }
584
+ }, []);
585
+ const refresh = useCallback(async () => {
586
+ if (!previewUrl) return;
587
+ console.log("[usePreview] Refreshing preview...");
588
+ setPreviewUrl(`${previewUrl.split("?")[0]}?t=${Date.now()}`);
589
+ }, [previewUrl]);
590
+ const handleRefresh = useCallback(async () => {
591
+ console.log("[usePreview] Handle refresh...");
592
+ await refresh();
593
+ }, [refresh]);
594
+ const handleReset = useCallback(async () => {
595
+ console.log("[usePreview] Resetting preview...");
596
+ setError(null);
597
+ setLoadError(null);
598
+ setErrorToast(null);
599
+ setIsExecutingEvent(false);
600
+ setCurrentStateName(null);
601
+ }, []);
602
+ const toggleFullscreen = useCallback(() => {
603
+ setIsFullscreen((prev) => !prev);
604
+ }, []);
605
+ const dismissErrorToast = useCallback(() => {
606
+ setErrorToast(null);
607
+ }, []);
608
+ return {
609
+ previewUrl,
610
+ isLoading,
611
+ error,
612
+ loadError,
613
+ app,
614
+ isFullscreen,
615
+ isExecutingEvent,
616
+ errorToast,
617
+ currentStateName,
618
+ notifications,
619
+ startPreview,
620
+ stopPreview,
621
+ refresh,
622
+ handleRefresh,
623
+ handleReset,
624
+ toggleFullscreen,
625
+ setErrorToast,
626
+ dismissErrorToast
627
+ };
628
+ }
629
+ function useAgentChat(options) {
630
+ const [messages, setMessages] = useState([]);
631
+ const [status, setStatus] = useState("idle");
632
+ const [activities, setActivities] = useState([]);
633
+ const [todos, setTodos] = useState([]);
634
+ const [schemaDiffs, setSchemaDiffs] = useState([]);
635
+ const [isLoading, setIsLoading] = useState(false);
636
+ const [error, setError] = useState(null);
637
+ const [threadId] = useState(null);
638
+ const [interrupt, setInterrupt] = useState(null);
639
+ const sendMessage = useCallback(async (content) => {
640
+ setIsLoading(true);
641
+ setStatus("running");
642
+ setError(null);
643
+ try {
644
+ const userMessage = {
645
+ id: Date.now().toString(),
646
+ role: "user",
647
+ content,
648
+ timestamp: Date.now()
649
+ };
650
+ setMessages((prev) => [...prev, userMessage]);
651
+ console.log("[useAgentChat] Sending message:", content);
652
+ const assistantMessage = {
653
+ id: (Date.now() + 1).toString(),
654
+ role: "assistant",
655
+ content: "Agent chat is not yet implemented.",
656
+ timestamp: Date.now()
657
+ };
658
+ setMessages((prev) => [...prev, assistantMessage]);
659
+ setStatus("idle");
660
+ options?.onComplete?.();
661
+ } catch (err) {
662
+ setError(err instanceof Error ? err.message : "Failed to send message");
663
+ setStatus("error");
664
+ } finally {
665
+ setIsLoading(false);
666
+ }
667
+ }, [options]);
668
+ const startGeneration = useCallback(async (skill, prompt, genOptions) => {
669
+ setStatus("running");
670
+ setIsLoading(true);
671
+ setError(null);
672
+ const skillName = Array.isArray(skill) ? skill[0] : skill;
673
+ try {
674
+ console.log("[useAgentChat] Starting generation:", skillName, prompt, genOptions);
675
+ await new Promise((resolve) => setTimeout(resolve, 100));
676
+ setStatus("complete");
677
+ options?.onComplete?.();
678
+ } catch (err) {
679
+ setError(err instanceof Error ? err.message : "Generation failed");
680
+ setStatus("error");
681
+ } finally {
682
+ setIsLoading(false);
683
+ }
684
+ }, [options]);
685
+ const continueConversation = useCallback(async (message) => {
686
+ console.log("[useAgentChat] Continue conversation", message);
687
+ }, []);
688
+ const resumeWithDecision = useCallback(async (decisions) => {
689
+ console.log("[useAgentChat] Resume with decision:", decisions);
690
+ setInterrupt(null);
691
+ }, []);
692
+ const cancel = useCallback(() => {
693
+ setStatus("idle");
694
+ setIsLoading(false);
695
+ setInterrupt(null);
696
+ }, []);
697
+ const clearMessages = useCallback(() => {
698
+ setMessages([]);
699
+ }, []);
700
+ const clearHistory = useCallback(() => {
701
+ setMessages([]);
702
+ setActivities([]);
703
+ setTodos([]);
704
+ setSchemaDiffs([]);
705
+ setError(null);
706
+ }, []);
707
+ return {
708
+ messages,
709
+ status,
710
+ activities,
711
+ todos,
712
+ schemaDiffs,
713
+ isLoading,
714
+ error,
715
+ threadId,
716
+ interrupt,
717
+ sendMessage,
718
+ startGeneration,
719
+ continueConversation,
720
+ resumeWithDecision,
721
+ cancel,
722
+ clearMessages,
723
+ clearHistory
724
+ };
725
+ }
726
+ function useValidation() {
727
+ const [result, setResult] = useState(null);
728
+ const [isValidating, setIsValidating] = useState(false);
729
+ const [error, setError] = useState(null);
730
+ const [stage, setStage] = useState("idle");
731
+ const [isFixing, setIsFixing] = useState(false);
732
+ const [progressMessage, setProgressMessage] = useState(null);
733
+ const validate = useCallback(async (appId) => {
734
+ setIsValidating(true);
735
+ setError(null);
736
+ setStage("validating");
737
+ setProgressMessage("Validating schema...");
738
+ try {
739
+ console.log("[useValidation] Validating app:", appId);
740
+ const validationResult = {
741
+ valid: true,
742
+ errors: [],
743
+ warnings: []
744
+ };
745
+ setResult(validationResult);
746
+ setStage("complete");
747
+ setProgressMessage(null);
748
+ return validationResult;
749
+ } catch (err) {
750
+ const errorMessage = err instanceof Error ? err.message : "Validation failed";
751
+ setError(errorMessage);
752
+ const failedResult = {
753
+ valid: false,
754
+ errors: [{ code: "VALIDATION_ERROR", message: errorMessage, severity: "error" }],
755
+ warnings: []
756
+ };
757
+ setResult(failedResult);
758
+ setStage("complete");
759
+ setProgressMessage(null);
760
+ return failedResult;
761
+ } finally {
762
+ setIsValidating(false);
763
+ }
764
+ }, []);
765
+ const clearResult = useCallback(() => {
766
+ setResult(null);
767
+ setError(null);
768
+ }, []);
769
+ const reset = useCallback(() => {
770
+ setResult(null);
771
+ setError(null);
772
+ setStage("idle");
773
+ setIsFixing(false);
774
+ setProgressMessage(null);
775
+ setIsValidating(false);
776
+ }, []);
777
+ return {
778
+ result,
779
+ isValidating,
780
+ error,
781
+ stage,
782
+ isFixing,
783
+ progressMessage,
784
+ errors: result?.errors ?? [],
785
+ warnings: result?.warnings ?? [],
786
+ isValid: result?.valid ?? false,
787
+ validate,
788
+ clearResult,
789
+ reset
790
+ };
791
+ }
792
+ function useDeepAgentGeneration() {
793
+ const [requests, setRequests] = useState([]);
794
+ const [currentRequest, setCurrentRequest] = useState(null);
795
+ const [isGenerating, setIsGenerating] = useState(false);
796
+ const [isLoading, setIsLoading] = useState(false);
797
+ const [isComplete, setIsComplete] = useState(false);
798
+ const [progress, setProgress] = useState({ stage: "idle", percent: 0, message: "" });
799
+ const [error, setError] = useState(null);
800
+ const [interrupt, setInterrupt] = useState(null);
801
+ const generate = useCallback(async (prompt) => {
802
+ setIsGenerating(true);
803
+ setIsLoading(true);
804
+ setIsComplete(false);
805
+ setError(null);
806
+ setProgress({ stage: "starting", percent: 0, message: "Starting generation..." });
807
+ const request = {
808
+ id: Date.now().toString(),
809
+ prompt,
810
+ status: "running"
811
+ };
812
+ setCurrentRequest(request);
813
+ setRequests((prev) => [...prev, request]);
814
+ try {
815
+ console.log("[useDeepAgentGeneration] Generating from prompt:", prompt);
816
+ await new Promise((resolve) => setTimeout(resolve, 100));
817
+ request.status = "completed";
818
+ setCurrentRequest(request);
819
+ setIsComplete(true);
820
+ setProgress({ stage: "complete", percent: 100, message: "Generation complete" });
821
+ return null;
822
+ } catch (err) {
823
+ const errorMessage = err instanceof Error ? err.message : "Generation failed";
824
+ setError(errorMessage);
825
+ request.status = "failed";
826
+ request.error = errorMessage;
827
+ setCurrentRequest(request);
828
+ return null;
829
+ } finally {
830
+ setIsGenerating(false);
831
+ setIsLoading(false);
832
+ }
833
+ }, []);
834
+ const startGeneration = useCallback(async (skill, prompt, _options) => {
835
+ console.log("[useDeepAgentGeneration] Starting generation with skill:", skill);
836
+ await generate(prompt);
837
+ }, [generate]);
838
+ const cancelGeneration = useCallback(() => {
839
+ if (currentRequest) {
840
+ currentRequest.status = "failed";
841
+ currentRequest.error = "Cancelled by user";
842
+ setCurrentRequest(null);
843
+ }
844
+ setIsGenerating(false);
845
+ setIsLoading(false);
846
+ setIsComplete(false);
847
+ setProgress({ stage: "idle", percent: 0, message: "" });
848
+ }, [currentRequest]);
849
+ const clearRequests = useCallback(() => {
850
+ setRequests([]);
851
+ setCurrentRequest(null);
852
+ setError(null);
853
+ setProgress({ stage: "idle", percent: 0, message: "" });
854
+ setIsComplete(false);
855
+ }, []);
856
+ const submitInterruptDecisions = useCallback((decisions) => {
857
+ console.log("[useDeepAgentGeneration] Submitting interrupt decisions:", decisions);
858
+ setInterrupt(null);
859
+ }, []);
860
+ return {
861
+ requests,
862
+ currentRequest,
863
+ isGenerating,
864
+ isLoading,
865
+ isComplete,
866
+ progress,
867
+ error,
868
+ interrupt,
869
+ generate,
870
+ startGeneration,
871
+ cancelGeneration,
872
+ clearRequests,
873
+ submitInterruptDecisions
874
+ };
875
+ }
876
+ var EventBusContext = createContext(null);
877
+
878
+ // hooks/useEventBus.ts
879
+ var globalEventBus = null;
880
+ var fallbackListeners = /* @__PURE__ */ new Map();
881
+ var fallbackEventBus = {
882
+ emit: (type, payload) => {
883
+ const event = {
884
+ type,
885
+ payload,
886
+ timestamp: Date.now()
887
+ };
888
+ const handlers = fallbackListeners.get(type);
889
+ if (handlers) {
890
+ handlers.forEach((handler) => {
891
+ try {
892
+ handler(event);
893
+ } catch (error) {
894
+ console.error(`[EventBus] Error in listener for '${type}':`, error);
895
+ }
896
+ });
897
+ }
898
+ },
899
+ on: (type, listener) => {
900
+ if (!fallbackListeners.has(type)) {
901
+ fallbackListeners.set(type, /* @__PURE__ */ new Set());
902
+ }
903
+ fallbackListeners.get(type).add(listener);
904
+ return () => {
905
+ const handlers = fallbackListeners.get(type);
906
+ if (handlers) {
907
+ handlers.delete(listener);
908
+ if (handlers.size === 0) {
909
+ fallbackListeners.delete(type);
910
+ }
911
+ }
912
+ };
913
+ },
914
+ once: (type, listener) => {
915
+ const wrappedListener = (event) => {
916
+ fallbackListeners.get(type)?.delete(wrappedListener);
917
+ listener(event);
918
+ };
919
+ return fallbackEventBus.on(type, wrappedListener);
920
+ },
921
+ hasListeners: (type) => {
922
+ const handlers = fallbackListeners.get(type);
923
+ return handlers !== void 0 && handlers.size > 0;
924
+ }
925
+ };
926
+ function useEventBus() {
927
+ const context = useContext(EventBusContext);
928
+ return context ?? globalEventBus ?? fallbackEventBus;
929
+ }
930
+ function useEventListener(event, handler) {
931
+ const eventBus = useEventBus();
932
+ const handlerRef = useRef(handler);
933
+ handlerRef.current = handler;
934
+ useEffect(() => {
935
+ const wrappedHandler = (evt) => {
936
+ handlerRef.current(evt);
937
+ };
938
+ return eventBus.on(event, wrappedHandler);
939
+ }, [event, eventBus]);
940
+ }
941
+ function useEmitEvent() {
942
+ const eventBus = useEventBus();
943
+ return useCallback(
944
+ (type, payload) => {
945
+ eventBus.emit(type, payload);
946
+ },
947
+ [eventBus]
948
+ );
949
+ }
950
+ var DEFAULT_SLOTS = {
951
+ main: null,
952
+ sidebar: null,
953
+ modal: null,
954
+ drawer: null,
955
+ overlay: null,
956
+ center: null,
957
+ toast: null,
958
+ "hud-top": null,
959
+ "hud-bottom": null,
960
+ floating: null
961
+ };
962
+ var idCounter = 0;
963
+ function generateId() {
964
+ return `slot-content-${++idCounter}-${Date.now()}`;
965
+ }
966
+ function useUISlotManager() {
967
+ const [slots, setSlots] = useState(DEFAULT_SLOTS);
968
+ const subscribersRef = useRef(/* @__PURE__ */ new Set());
969
+ const timersRef = useRef(/* @__PURE__ */ new Map());
970
+ useEffect(() => {
971
+ return () => {
972
+ timersRef.current.forEach((timer) => clearTimeout(timer));
973
+ timersRef.current.clear();
974
+ };
975
+ }, []);
976
+ const notifySubscribers = useCallback((slot, content) => {
977
+ subscribersRef.current.forEach((callback) => {
978
+ try {
979
+ callback(slot, content);
980
+ } catch (error) {
981
+ console.error("[UISlots] Subscriber error:", error);
982
+ }
983
+ });
984
+ }, []);
985
+ const render = useCallback((config) => {
986
+ const id = generateId();
987
+ const content = {
988
+ id,
989
+ pattern: config.pattern,
990
+ props: config.props ?? {},
991
+ priority: config.priority ?? 0,
992
+ animation: config.animation ?? "fade",
993
+ onDismiss: config.onDismiss,
994
+ sourceTrait: config.sourceTrait
995
+ };
996
+ if (config.autoDismissMs && config.autoDismissMs > 0) {
997
+ content.autoDismissAt = Date.now() + config.autoDismissMs;
998
+ const timer = setTimeout(() => {
999
+ setSlots((prev) => {
1000
+ if (prev[config.target]?.id === id) {
1001
+ content.onDismiss?.();
1002
+ notifySubscribers(config.target, null);
1003
+ return { ...prev, [config.target]: null };
1004
+ }
1005
+ return prev;
1006
+ });
1007
+ timersRef.current.delete(id);
1008
+ }, config.autoDismissMs);
1009
+ timersRef.current.set(id, timer);
1010
+ }
1011
+ setSlots((prev) => {
1012
+ const existing = prev[config.target];
1013
+ if (existing && existing.priority > content.priority) {
1014
+ console.warn(
1015
+ `[UISlots] Slot "${config.target}" already has higher priority content (${existing.priority} > ${content.priority})`
1016
+ );
1017
+ return prev;
1018
+ }
1019
+ notifySubscribers(config.target, content);
1020
+ return { ...prev, [config.target]: content };
1021
+ });
1022
+ return id;
1023
+ }, [notifySubscribers]);
1024
+ const clear = useCallback((slot) => {
1025
+ setSlots((prev) => {
1026
+ const content = prev[slot];
1027
+ if (content) {
1028
+ const timer = timersRef.current.get(content.id);
1029
+ if (timer) {
1030
+ clearTimeout(timer);
1031
+ timersRef.current.delete(content.id);
1032
+ }
1033
+ content.onDismiss?.();
1034
+ notifySubscribers(slot, null);
1035
+ }
1036
+ return { ...prev, [slot]: null };
1037
+ });
1038
+ }, [notifySubscribers]);
1039
+ const clearById = useCallback((id) => {
1040
+ setSlots((prev) => {
1041
+ const entry = Object.entries(prev).find(([, content]) => content?.id === id);
1042
+ if (entry) {
1043
+ const [slot, content] = entry;
1044
+ const timer = timersRef.current.get(id);
1045
+ if (timer) {
1046
+ clearTimeout(timer);
1047
+ timersRef.current.delete(id);
1048
+ }
1049
+ content.onDismiss?.();
1050
+ notifySubscribers(slot, null);
1051
+ return { ...prev, [slot]: null };
1052
+ }
1053
+ return prev;
1054
+ });
1055
+ }, [notifySubscribers]);
1056
+ const clearAll = useCallback(() => {
1057
+ timersRef.current.forEach((timer) => clearTimeout(timer));
1058
+ timersRef.current.clear();
1059
+ setSlots((prev) => {
1060
+ Object.entries(prev).forEach(([slot, content]) => {
1061
+ if (content) {
1062
+ content.onDismiss?.();
1063
+ notifySubscribers(slot, null);
1064
+ }
1065
+ });
1066
+ return DEFAULT_SLOTS;
1067
+ });
1068
+ }, [notifySubscribers]);
1069
+ const subscribe2 = useCallback((callback) => {
1070
+ subscribersRef.current.add(callback);
1071
+ return () => {
1072
+ subscribersRef.current.delete(callback);
1073
+ };
1074
+ }, []);
1075
+ const hasContent = useCallback((slot) => {
1076
+ return slots[slot] !== null;
1077
+ }, [slots]);
1078
+ const getContent = useCallback((slot) => {
1079
+ return slots[slot];
1080
+ }, [slots]);
1081
+ return {
1082
+ slots,
1083
+ render,
1084
+ clear,
1085
+ clearById,
1086
+ clearAll,
1087
+ subscribe: subscribe2,
1088
+ hasContent,
1089
+ getContent
1090
+ };
1091
+ }
1092
+ var SelectionContext = createContext(null);
1093
+
1094
+ // hooks/useUIEvents.ts
1095
+ var UI_EVENT_MAP = {
1096
+ // Form/CRUD events
1097
+ "UI:SAVE": "SAVE",
1098
+ "UI:CANCEL": "CANCEL",
1099
+ "UI:CLOSE": "CLOSE",
1100
+ "UI:VIEW": "VIEW",
1101
+ "UI:EDIT": "EDIT",
1102
+ "UI:DELETE": "DELETE",
1103
+ "UI:CREATE": "CREATE",
1104
+ "UI:SELECT": "SELECT",
1105
+ "UI:DESELECT": "DESELECT",
1106
+ "UI:SUBMIT": "SAVE",
1107
+ "UI:UPDATE_STATUS": "UPDATE_STATUS",
1108
+ "UI:SEARCH": "SEARCH",
1109
+ "UI:CLEAR_SEARCH": "CLEAR_SEARCH",
1110
+ "UI:ADD": "CREATE",
1111
+ // Game events (for closed circuit with GameMenu, GamePauseOverlay, GameOverScreen)
1112
+ "UI:PAUSE": "PAUSE",
1113
+ "UI:RESUME": "RESUME",
1114
+ "UI:RESTART": "RESTART",
1115
+ "UI:GAME_OVER": "GAME_OVER",
1116
+ "UI:START": "START",
1117
+ "UI:QUIT": "QUIT",
1118
+ "UI:INIT": "INIT"
1119
+ };
1120
+ function useUIEvents(dispatch, validEvents, eventBusInstance) {
1121
+ const defaultEventBus = useEventBus();
1122
+ const eventBus = eventBusInstance ?? defaultEventBus;
1123
+ const validEventsKey = validEvents ? validEvents.slice().sort().join(",") : "";
1124
+ const stableValidEvents = useMemo(
1125
+ () => validEvents,
1126
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1127
+ [validEventsKey]
1128
+ );
1129
+ useEffect(() => {
1130
+ const unsubscribes = [];
1131
+ Object.entries(UI_EVENT_MAP).forEach(([uiEvent, smEvent]) => {
1132
+ const handler = (event) => {
1133
+ if (!stableValidEvents || stableValidEvents.includes(smEvent)) {
1134
+ dispatch(smEvent, event.payload);
1135
+ }
1136
+ };
1137
+ const unsubscribe = eventBus.on(uiEvent, handler);
1138
+ unsubscribes.push(unsubscribe);
1139
+ });
1140
+ const genericHandler = (event) => {
1141
+ const eventName = event.payload?.event;
1142
+ if (eventName) {
1143
+ const smEvent = eventName;
1144
+ if (!stableValidEvents || stableValidEvents.includes(smEvent)) {
1145
+ dispatch(smEvent, event.payload);
1146
+ }
1147
+ }
1148
+ };
1149
+ const genericUnsubscribe = eventBus.on("UI:DISPATCH", genericHandler);
1150
+ unsubscribes.push(genericUnsubscribe);
1151
+ if (stableValidEvents) {
1152
+ stableValidEvents.forEach((smEvent) => {
1153
+ const uiPrefixedEvent = `UI:${smEvent}`;
1154
+ const alreadyMapped = Object.keys(UI_EVENT_MAP).includes(uiPrefixedEvent);
1155
+ if (!alreadyMapped) {
1156
+ const directHandler = (event) => {
1157
+ dispatch(smEvent, event.payload);
1158
+ };
1159
+ const unsubscribePrefixed = eventBus.on(
1160
+ uiPrefixedEvent,
1161
+ directHandler
1162
+ );
1163
+ unsubscribes.push(unsubscribePrefixed);
1164
+ const unsubscribeDirect = eventBus.on(smEvent, directHandler);
1165
+ unsubscribes.push(unsubscribeDirect);
1166
+ }
1167
+ });
1168
+ }
1169
+ return () => {
1170
+ unsubscribes.forEach((unsub) => unsub());
1171
+ };
1172
+ }, [eventBus, dispatch, stableValidEvents]);
1173
+ }
1174
+ function useSelectedEntity(eventBusInstance) {
1175
+ const defaultEventBus = useEventBus();
1176
+ const eventBus = eventBusInstance ?? defaultEventBus;
1177
+ const selectionContext = useSelectionContext();
1178
+ const [localSelected, setLocalSelected] = useState(null);
1179
+ const usingContext = selectionContext !== null;
1180
+ useEffect(() => {
1181
+ if (usingContext) return;
1182
+ const handleSelect = (event) => {
1183
+ const row = event.payload?.row;
1184
+ if (row) {
1185
+ setLocalSelected(row);
1186
+ }
1187
+ };
1188
+ const handleDeselect = () => {
1189
+ setLocalSelected(null);
1190
+ };
1191
+ const unsubSelect = eventBus.on("UI:SELECT", handleSelect);
1192
+ const unsubView = eventBus.on("UI:VIEW", handleSelect);
1193
+ const unsubDeselect = eventBus.on("UI:DESELECT", handleDeselect);
1194
+ const unsubClose = eventBus.on("UI:CLOSE", handleDeselect);
1195
+ const unsubCancel = eventBus.on("UI:CANCEL", handleDeselect);
1196
+ return () => {
1197
+ unsubSelect();
1198
+ unsubView();
1199
+ unsubDeselect();
1200
+ unsubClose();
1201
+ unsubCancel();
1202
+ };
1203
+ }, [eventBus, usingContext]);
1204
+ if (selectionContext) {
1205
+ return [selectionContext.selected, selectionContext.setSelected];
1206
+ }
1207
+ return [localSelected, setLocalSelected];
1208
+ }
1209
+ function useSelectionContext() {
1210
+ const context = useContext(SelectionContext);
1211
+ return context;
1212
+ }
1213
+ var entityDataKeys = {
1214
+ all: ["entities"],
1215
+ lists: () => [...entityDataKeys.all, "list"],
1216
+ list: (entity, filters) => [...entityDataKeys.lists(), entity, filters],
1217
+ details: () => [...entityDataKeys.all, "detail"],
1218
+ detail: (entity, id) => [...entityDataKeys.details(), entity, id]
1219
+ };
1220
+ function useEntityList(entity, options = {}) {
1221
+ const { skip = false } = options;
1222
+ const [data, setData] = useState([]);
1223
+ const [isLoading, setIsLoading] = useState(!skip && !!entity);
1224
+ const [error, setError] = useState(null);
1225
+ const refetch = () => {
1226
+ if (!entity || skip) return;
1227
+ setIsLoading(true);
1228
+ setError(null);
1229
+ setTimeout(() => {
1230
+ setData([]);
1231
+ setIsLoading(false);
1232
+ }, 100);
1233
+ };
1234
+ useEffect(() => {
1235
+ if (skip || !entity) {
1236
+ setIsLoading(false);
1237
+ return;
1238
+ }
1239
+ refetch();
1240
+ }, [entity, skip]);
1241
+ return { data, isLoading, error, refetch };
1242
+ }
1243
+ function useEntity(entity, id) {
1244
+ const [data, setData] = useState(null);
1245
+ const [isLoading, setIsLoading] = useState(!!entity && !!id);
1246
+ const [error, setError] = useState(null);
1247
+ useEffect(() => {
1248
+ if (!entity || !id) {
1249
+ setIsLoading(false);
1250
+ return;
1251
+ }
1252
+ setIsLoading(true);
1253
+ setTimeout(() => {
1254
+ setData(null);
1255
+ setIsLoading(false);
1256
+ }, 100);
1257
+ }, [entity, id]);
1258
+ return { data, isLoading, error };
1259
+ }
1260
+ function useEntityDetail(entity, id) {
1261
+ const [data, setData] = useState(null);
1262
+ const [isLoading, setIsLoading] = useState(!!entity && !!id);
1263
+ const [error, setError] = useState(null);
1264
+ const refetch = () => {
1265
+ if (!entity || !id) return;
1266
+ setIsLoading(true);
1267
+ setError(null);
1268
+ setTimeout(() => {
1269
+ setData(null);
1270
+ setIsLoading(false);
1271
+ }, 100);
1272
+ };
1273
+ useEffect(() => {
1274
+ if (!entity || !id) {
1275
+ setIsLoading(false);
1276
+ return;
1277
+ }
1278
+ refetch();
1279
+ }, [entity, id]);
1280
+ return { data, isLoading, error, refetch };
1281
+ }
1282
+ var queryStores = /* @__PURE__ */ new Map();
1283
+ function getOrCreateStore(query) {
1284
+ if (!queryStores.has(query)) {
1285
+ queryStores.set(query, {
1286
+ search: "",
1287
+ filters: {},
1288
+ sortField: void 0,
1289
+ sortDirection: void 0,
1290
+ listeners: /* @__PURE__ */ new Set()
1291
+ });
1292
+ }
1293
+ return queryStores.get(query);
1294
+ }
1295
+ function useQuerySingleton(query) {
1296
+ const [, forceUpdate] = useState({});
1297
+ if (!query) {
1298
+ return null;
1299
+ }
1300
+ const store = useMemo(() => getOrCreateStore(query), [query]);
1301
+ useMemo(() => {
1302
+ const listener = () => forceUpdate({});
1303
+ store.listeners.add(listener);
1304
+ return () => {
1305
+ store.listeners.delete(listener);
1306
+ };
1307
+ }, [store]);
1308
+ const notifyListeners = useCallback(() => {
1309
+ store.listeners.forEach((listener) => listener());
1310
+ }, [store]);
1311
+ const setSearch = useCallback((value) => {
1312
+ store.search = value;
1313
+ notifyListeners();
1314
+ }, [store, notifyListeners]);
1315
+ const setFilter = useCallback((key, value) => {
1316
+ store.filters = { ...store.filters, [key]: value };
1317
+ notifyListeners();
1318
+ }, [store, notifyListeners]);
1319
+ const clearFilters = useCallback(() => {
1320
+ store.filters = {};
1321
+ store.search = "";
1322
+ notifyListeners();
1323
+ }, [store, notifyListeners]);
1324
+ const setSort = useCallback((field, direction) => {
1325
+ store.sortField = field;
1326
+ store.sortDirection = direction;
1327
+ notifyListeners();
1328
+ }, [store, notifyListeners]);
1329
+ return {
1330
+ search: store.search,
1331
+ setSearch,
1332
+ filters: store.filters,
1333
+ setFilter,
1334
+ clearFilters,
1335
+ sortField: store.sortField,
1336
+ sortDirection: store.sortDirection,
1337
+ setSort
1338
+ };
1339
+ }
1340
+ function parseQueryBinding(binding) {
1341
+ const cleaned = binding.startsWith("@") ? binding.slice(1) : binding;
1342
+ const parts = cleaned.split(".");
1343
+ return {
1344
+ query: parts[0],
1345
+ field: parts.length > 1 ? parts.slice(1).join(".") : void 0
1346
+ };
1347
+ }
1348
+
1349
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/subscribable.js
1350
+ var Subscribable = class {
1351
+ constructor() {
1352
+ this.listeners = /* @__PURE__ */ new Set();
1353
+ this.subscribe = this.subscribe.bind(this);
1354
+ }
1355
+ subscribe(listener) {
1356
+ this.listeners.add(listener);
1357
+ this.onSubscribe();
1358
+ return () => {
1359
+ this.listeners.delete(listener);
1360
+ this.onUnsubscribe();
1361
+ };
1362
+ }
1363
+ hasListeners() {
1364
+ return this.listeners.size > 0;
1365
+ }
1366
+ onSubscribe() {
1367
+ }
1368
+ onUnsubscribe() {
1369
+ }
1370
+ };
1371
+
1372
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/timeoutManager.js
1373
+ var defaultTimeoutProvider = {
1374
+ // We need the wrapper function syntax below instead of direct references to
1375
+ // global setTimeout etc.
1376
+ //
1377
+ // BAD: `setTimeout: setTimeout`
1378
+ // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
1379
+ //
1380
+ // If we use direct references here, then anything that wants to spy on or
1381
+ // replace the global setTimeout (like tests) won't work since we'll already
1382
+ // have a hard reference to the original implementation at the time when this
1383
+ // file was imported.
1384
+ setTimeout: (callback, delay) => setTimeout(callback, delay),
1385
+ clearTimeout: (timeoutId) => clearTimeout(timeoutId),
1386
+ setInterval: (callback, delay) => setInterval(callback, delay),
1387
+ clearInterval: (intervalId) => clearInterval(intervalId)
1388
+ };
1389
+ var _provider, _providerCalled, _a;
1390
+ var TimeoutManager = (_a = class {
1391
+ constructor() {
1392
+ // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
1393
+ // type at app boot; and if we leave that type, then any new timer provider
1394
+ // would need to support ReturnType<typeof setTimeout>, which is infeasible.
1395
+ //
1396
+ // We settle for type safety for the TimeoutProvider type, and accept that
1397
+ // this class is unsafe internally to allow for extension.
1398
+ __privateAdd(this, _provider, defaultTimeoutProvider);
1399
+ __privateAdd(this, _providerCalled, false);
1400
+ }
1401
+ setTimeoutProvider(provider) {
1402
+ if (process.env.NODE_ENV !== "production") {
1403
+ if (__privateGet(this, _providerCalled) && provider !== __privateGet(this, _provider)) {
1404
+ console.error(
1405
+ `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
1406
+ { previous: __privateGet(this, _provider), provider }
1407
+ );
1408
+ }
1409
+ }
1410
+ __privateSet(this, _provider, provider);
1411
+ if (process.env.NODE_ENV !== "production") {
1412
+ __privateSet(this, _providerCalled, false);
1413
+ }
1414
+ }
1415
+ setTimeout(callback, delay) {
1416
+ if (process.env.NODE_ENV !== "production") {
1417
+ __privateSet(this, _providerCalled, true);
1418
+ }
1419
+ return __privateGet(this, _provider).setTimeout(callback, delay);
1420
+ }
1421
+ clearTimeout(timeoutId) {
1422
+ __privateGet(this, _provider).clearTimeout(timeoutId);
1423
+ }
1424
+ setInterval(callback, delay) {
1425
+ if (process.env.NODE_ENV !== "production") {
1426
+ __privateSet(this, _providerCalled, true);
1427
+ }
1428
+ return __privateGet(this, _provider).setInterval(callback, delay);
1429
+ }
1430
+ clearInterval(intervalId) {
1431
+ __privateGet(this, _provider).clearInterval(intervalId);
1432
+ }
1433
+ }, _provider = new WeakMap(), _providerCalled = new WeakMap(), _a);
1434
+ new TimeoutManager();
1435
+ function systemSetTimeoutZero(callback) {
1436
+ setTimeout(callback, 0);
1437
+ }
1438
+ function noop() {
1439
+ }
1440
+ function hashKey(queryKey) {
1441
+ return JSON.stringify(
1442
+ queryKey,
1443
+ (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
1444
+ result[key] = val[key];
1445
+ return result;
1446
+ }, {}) : val
1447
+ );
1448
+ }
1449
+ function shallowEqualObjects(a, b) {
1450
+ if (!b || Object.keys(a).length !== Object.keys(b).length) {
1451
+ return false;
1452
+ }
1453
+ for (const key in a) {
1454
+ if (a[key] !== b[key]) {
1455
+ return false;
1456
+ }
1457
+ }
1458
+ return true;
1459
+ }
1460
+ function isPlainObject(o) {
1461
+ if (!hasObjectPrototype(o)) {
1462
+ return false;
1463
+ }
1464
+ const ctor = o.constructor;
1465
+ if (ctor === void 0) {
1466
+ return true;
1467
+ }
1468
+ const prot = ctor.prototype;
1469
+ if (!hasObjectPrototype(prot)) {
1470
+ return false;
1471
+ }
1472
+ if (!prot.hasOwnProperty("isPrototypeOf")) {
1473
+ return false;
1474
+ }
1475
+ if (Object.getPrototypeOf(o) !== Object.prototype) {
1476
+ return false;
1477
+ }
1478
+ return true;
1479
+ }
1480
+ function hasObjectPrototype(o) {
1481
+ return Object.prototype.toString.call(o) === "[object Object]";
1482
+ }
1483
+ function shouldThrowError(throwOnError, params) {
1484
+ if (typeof throwOnError === "function") {
1485
+ return throwOnError(...params);
1486
+ }
1487
+ return !!throwOnError;
1488
+ }
1489
+
1490
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/notifyManager.js
1491
+ var defaultScheduler = systemSetTimeoutZero;
1492
+ function createNotifyManager() {
1493
+ let queue = [];
1494
+ let transactions = 0;
1495
+ let notifyFn = (callback) => {
1496
+ callback();
1497
+ };
1498
+ let batchNotifyFn = (callback) => {
1499
+ callback();
1500
+ };
1501
+ let scheduleFn = defaultScheduler;
1502
+ const schedule = (callback) => {
1503
+ if (transactions) {
1504
+ queue.push(callback);
1505
+ } else {
1506
+ scheduleFn(() => {
1507
+ notifyFn(callback);
1508
+ });
1509
+ }
1510
+ };
1511
+ const flush = () => {
1512
+ const originalQueue = queue;
1513
+ queue = [];
1514
+ if (originalQueue.length) {
1515
+ scheduleFn(() => {
1516
+ batchNotifyFn(() => {
1517
+ originalQueue.forEach((callback) => {
1518
+ notifyFn(callback);
1519
+ });
1520
+ });
1521
+ });
1522
+ }
1523
+ };
1524
+ return {
1525
+ batch: (callback) => {
1526
+ let result;
1527
+ transactions++;
1528
+ try {
1529
+ result = callback();
1530
+ } finally {
1531
+ transactions--;
1532
+ if (!transactions) {
1533
+ flush();
1534
+ }
1535
+ }
1536
+ return result;
1537
+ },
1538
+ /**
1539
+ * All calls to the wrapped function will be batched.
1540
+ */
1541
+ batchCalls: (callback) => {
1542
+ return (...args) => {
1543
+ schedule(() => {
1544
+ callback(...args);
1545
+ });
1546
+ };
1547
+ },
1548
+ schedule,
1549
+ /**
1550
+ * Use this method to set a custom notify function.
1551
+ * This can be used to for example wrap notifications with `React.act` while running tests.
1552
+ */
1553
+ setNotifyFunction: (fn) => {
1554
+ notifyFn = fn;
1555
+ },
1556
+ /**
1557
+ * Use this method to set a custom function to batch notifications together into a single tick.
1558
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
1559
+ */
1560
+ setBatchNotifyFunction: (fn) => {
1561
+ batchNotifyFn = fn;
1562
+ },
1563
+ setScheduler: (fn) => {
1564
+ scheduleFn = fn;
1565
+ }
1566
+ };
1567
+ }
1568
+ var notifyManager = createNotifyManager();
1569
+
1570
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/mutation.js
1571
+ function getDefaultState() {
1572
+ return {
1573
+ context: void 0,
1574
+ data: void 0,
1575
+ error: null,
1576
+ failureCount: 0,
1577
+ failureReason: null,
1578
+ isPaused: false,
1579
+ status: "idle",
1580
+ variables: void 0,
1581
+ submittedAt: 0
1582
+ };
1583
+ }
1584
+
1585
+ // ../../node_modules/.pnpm/@tanstack+query-core@5.90.20/node_modules/@tanstack/query-core/build/modern/mutationObserver.js
1586
+ var _client, _currentResult, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn, _a2;
1587
+ var MutationObserver = (_a2 = class extends Subscribable {
1588
+ constructor(client, options) {
1589
+ super();
1590
+ __privateAdd(this, _MutationObserver_instances);
1591
+ __privateAdd(this, _client);
1592
+ __privateAdd(this, _currentResult);
1593
+ __privateAdd(this, _currentMutation);
1594
+ __privateAdd(this, _mutateOptions);
1595
+ __privateSet(this, _client, client);
1596
+ this.setOptions(options);
1597
+ this.bindMethods();
1598
+ __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
1599
+ }
1600
+ bindMethods() {
1601
+ this.mutate = this.mutate.bind(this);
1602
+ this.reset = this.reset.bind(this);
1603
+ }
1604
+ setOptions(options) {
1605
+ const prevOptions = this.options;
1606
+ this.options = __privateGet(this, _client).defaultMutationOptions(options);
1607
+ if (!shallowEqualObjects(this.options, prevOptions)) {
1608
+ __privateGet(this, _client).getMutationCache().notify({
1609
+ type: "observerOptionsUpdated",
1610
+ mutation: __privateGet(this, _currentMutation),
1611
+ observer: this
1612
+ });
1613
+ }
1614
+ if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
1615
+ this.reset();
1616
+ } else if (__privateGet(this, _currentMutation)?.state.status === "pending") {
1617
+ __privateGet(this, _currentMutation).setOptions(this.options);
1618
+ }
1619
+ }
1620
+ onUnsubscribe() {
1621
+ if (!this.hasListeners()) {
1622
+ __privateGet(this, _currentMutation)?.removeObserver(this);
1623
+ }
1624
+ }
1625
+ onMutationUpdate(action) {
1626
+ __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
1627
+ __privateMethod(this, _MutationObserver_instances, notify_fn).call(this, action);
1628
+ }
1629
+ getCurrentResult() {
1630
+ return __privateGet(this, _currentResult);
1631
+ }
1632
+ reset() {
1633
+ __privateGet(this, _currentMutation)?.removeObserver(this);
1634
+ __privateSet(this, _currentMutation, void 0);
1635
+ __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
1636
+ __privateMethod(this, _MutationObserver_instances, notify_fn).call(this);
1637
+ }
1638
+ mutate(variables, options) {
1639
+ __privateSet(this, _mutateOptions, options);
1640
+ __privateGet(this, _currentMutation)?.removeObserver(this);
1641
+ __privateSet(this, _currentMutation, __privateGet(this, _client).getMutationCache().build(__privateGet(this, _client), this.options));
1642
+ __privateGet(this, _currentMutation).addObserver(this);
1643
+ return __privateGet(this, _currentMutation).execute(variables);
1644
+ }
1645
+ }, _client = new WeakMap(), _currentResult = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() {
1646
+ const state = __privateGet(this, _currentMutation)?.state ?? getDefaultState();
1647
+ __privateSet(this, _currentResult, {
1648
+ ...state,
1649
+ isPending: state.status === "pending",
1650
+ isSuccess: state.status === "success",
1651
+ isError: state.status === "error",
1652
+ isIdle: state.status === "idle",
1653
+ mutate: this.mutate,
1654
+ reset: this.reset
1655
+ });
1656
+ }, notify_fn = function(action) {
1657
+ notifyManager.batch(() => {
1658
+ if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
1659
+ const variables = __privateGet(this, _currentResult).variables;
1660
+ const onMutateResult = __privateGet(this, _currentResult).context;
1661
+ const context = {
1662
+ client: __privateGet(this, _client),
1663
+ meta: this.options.meta,
1664
+ mutationKey: this.options.mutationKey
1665
+ };
1666
+ if (action?.type === "success") {
1667
+ try {
1668
+ __privateGet(this, _mutateOptions).onSuccess?.(
1669
+ action.data,
1670
+ variables,
1671
+ onMutateResult,
1672
+ context
1673
+ );
1674
+ } catch (e) {
1675
+ void Promise.reject(e);
1676
+ }
1677
+ try {
1678
+ __privateGet(this, _mutateOptions).onSettled?.(
1679
+ action.data,
1680
+ null,
1681
+ variables,
1682
+ onMutateResult,
1683
+ context
1684
+ );
1685
+ } catch (e) {
1686
+ void Promise.reject(e);
1687
+ }
1688
+ } else if (action?.type === "error") {
1689
+ try {
1690
+ __privateGet(this, _mutateOptions).onError?.(
1691
+ action.error,
1692
+ variables,
1693
+ onMutateResult,
1694
+ context
1695
+ );
1696
+ } catch (e) {
1697
+ void Promise.reject(e);
1698
+ }
1699
+ try {
1700
+ __privateGet(this, _mutateOptions).onSettled?.(
1701
+ void 0,
1702
+ action.error,
1703
+ variables,
1704
+ onMutateResult,
1705
+ context
1706
+ );
1707
+ } catch (e) {
1708
+ void Promise.reject(e);
1709
+ }
1710
+ }
1711
+ }
1712
+ this.listeners.forEach((listener) => {
1713
+ listener(__privateGet(this, _currentResult));
1714
+ });
1715
+ });
1716
+ }, _a2);
1717
+ var QueryClientContext = React4.createContext(
1718
+ void 0
1719
+ );
1720
+ var useQueryClient = (queryClient) => {
1721
+ const client = React4.useContext(QueryClientContext);
1722
+ if (!client) {
1723
+ throw new Error("No QueryClient set, use QueryClientProvider to set one");
1724
+ }
1725
+ return client;
1726
+ };
1727
+ function useMutation(options, queryClient) {
1728
+ const client = useQueryClient();
1729
+ const [observer] = React4.useState(
1730
+ () => new MutationObserver(
1731
+ client,
1732
+ options
1733
+ )
1734
+ );
1735
+ React4.useEffect(() => {
1736
+ observer.setOptions(options);
1737
+ }, [observer, options]);
1738
+ const result = React4.useSyncExternalStore(
1739
+ React4.useCallback(
1740
+ (onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)),
1741
+ [observer]
1742
+ ),
1743
+ () => observer.getCurrentResult(),
1744
+ () => observer.getCurrentResult()
1745
+ );
1746
+ const mutate = React4.useCallback(
1747
+ (variables, mutateOptions) => {
1748
+ observer.mutate(variables, mutateOptions).catch(noop);
1749
+ },
1750
+ [observer]
1751
+ );
1752
+ if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) {
1753
+ throw result.error;
1754
+ }
1755
+ return { ...result, mutate, mutateAsync: result.mutate };
1756
+ }
1757
+
1758
+ // lib/api-client.ts
1759
+ var API_BASE_URL = typeof import.meta !== "undefined" && import.meta.env?.VITE_API_URL ? import.meta.env.VITE_API_URL : "/api";
1760
+ var ApiError = class extends Error {
1761
+ constructor(status, statusText, message) {
1762
+ super(message || `API Error: ${status} ${statusText}`);
1763
+ this.status = status;
1764
+ this.statusText = statusText;
1765
+ this.name = "ApiError";
1766
+ }
1767
+ };
1768
+ async function handleResponse(response) {
1769
+ if (!response.ok) {
1770
+ let message;
1771
+ try {
1772
+ const errorData = await response.json();
1773
+ message = errorData.message || errorData.error;
1774
+ } catch {
1775
+ }
1776
+ throw new ApiError(response.status, response.statusText, message);
1777
+ }
1778
+ const text = await response.text();
1779
+ if (!text) {
1780
+ return void 0;
1781
+ }
1782
+ return JSON.parse(text);
1783
+ }
1784
+ function getHeaders() {
1785
+ const headers = {
1786
+ "Content-Type": "application/json"
1787
+ };
1788
+ const token = typeof localStorage !== "undefined" ? localStorage.getItem("authToken") : null;
1789
+ if (token) {
1790
+ headers["Authorization"] = `Bearer ${token}`;
1791
+ }
1792
+ return headers;
1793
+ }
1794
+ var apiClient = {
1795
+ /**
1796
+ * GET request
1797
+ */
1798
+ async get(endpoint) {
1799
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1800
+ method: "GET",
1801
+ headers: getHeaders()
1802
+ });
1803
+ return handleResponse(response);
1804
+ },
1805
+ /**
1806
+ * POST request
1807
+ */
1808
+ async post(endpoint, data) {
1809
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1810
+ method: "POST",
1811
+ headers: getHeaders(),
1812
+ body: data ? JSON.stringify(data) : void 0
1813
+ });
1814
+ return handleResponse(response);
1815
+ },
1816
+ /**
1817
+ * PUT request
1818
+ */
1819
+ async put(endpoint, data) {
1820
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1821
+ method: "PUT",
1822
+ headers: getHeaders(),
1823
+ body: data ? JSON.stringify(data) : void 0
1824
+ });
1825
+ return handleResponse(response);
1826
+ },
1827
+ /**
1828
+ * PATCH request
1829
+ */
1830
+ async patch(endpoint, data) {
1831
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1832
+ method: "PATCH",
1833
+ headers: getHeaders(),
1834
+ body: data ? JSON.stringify(data) : void 0
1835
+ });
1836
+ return handleResponse(response);
1837
+ },
1838
+ /**
1839
+ * DELETE request
1840
+ */
1841
+ async delete(endpoint) {
1842
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
1843
+ method: "DELETE",
1844
+ headers: getHeaders()
1845
+ });
1846
+ return handleResponse(response);
1847
+ }
1848
+ };
1849
+
1850
+ // hooks/useOrbitalMutations.ts
1851
+ var ENTITY_EVENTS = {
1852
+ CREATE: "ENTITY_CREATE",
1853
+ UPDATE: "ENTITY_UPDATE",
1854
+ DELETE: "ENTITY_DELETE"
1855
+ };
1856
+ async function sendOrbitalEvent(orbitalName, eventPayload) {
1857
+ const response = await apiClient.post(
1858
+ `/orbitals/${orbitalName}/events`,
1859
+ eventPayload
1860
+ );
1861
+ return response;
1862
+ }
1863
+ function useOrbitalMutations(entityName, orbitalName, options) {
1864
+ const queryClient = useQueryClient();
1865
+ const events = {
1866
+ create: options?.events?.create || ENTITY_EVENTS.CREATE,
1867
+ update: options?.events?.update || ENTITY_EVENTS.UPDATE,
1868
+ delete: options?.events?.delete || ENTITY_EVENTS.DELETE
1869
+ };
1870
+ const log = (message, data) => {
1871
+ if (options?.debug) {
1872
+ console.log(`[useOrbitalMutations:${orbitalName}] ${message}`, data ?? "");
1873
+ }
1874
+ };
1875
+ const createMutation = useMutation({
1876
+ mutationFn: async (data) => {
1877
+ log("Creating entity", data);
1878
+ return sendOrbitalEvent(orbitalName, {
1879
+ event: events.create,
1880
+ payload: { data, entityType: entityName }
1881
+ });
1882
+ },
1883
+ onSuccess: (response) => {
1884
+ log("Create succeeded", response);
1885
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1886
+ },
1887
+ onError: (error) => {
1888
+ console.error(`[useOrbitalMutations] Create failed:`, error);
1889
+ }
1890
+ });
1891
+ const updateMutation = useMutation({
1892
+ mutationFn: async ({
1893
+ id,
1894
+ data
1895
+ }) => {
1896
+ log(`Updating entity ${id}`, data);
1897
+ return sendOrbitalEvent(orbitalName, {
1898
+ event: events.update,
1899
+ entityId: id,
1900
+ payload: { data, entityType: entityName }
1901
+ });
1902
+ },
1903
+ onSuccess: (response, variables) => {
1904
+ log("Update succeeded", response);
1905
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1906
+ queryClient.invalidateQueries({
1907
+ queryKey: entityDataKeys.detail(entityName, variables.id)
1908
+ });
1909
+ },
1910
+ onError: (error) => {
1911
+ console.error(`[useOrbitalMutations] Update failed:`, error);
1912
+ }
1913
+ });
1914
+ const deleteMutation = useMutation({
1915
+ mutationFn: async (id) => {
1916
+ log(`Deleting entity ${id}`);
1917
+ return sendOrbitalEvent(orbitalName, {
1918
+ event: events.delete,
1919
+ entityId: id,
1920
+ payload: { entityType: entityName }
1921
+ });
1922
+ },
1923
+ onSuccess: (response, id) => {
1924
+ log("Delete succeeded", response);
1925
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
1926
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
1927
+ },
1928
+ onError: (error) => {
1929
+ console.error(`[useOrbitalMutations] Delete failed:`, error);
1930
+ }
1931
+ });
1932
+ return {
1933
+ // Async functions
1934
+ createEntity: async (data) => {
1935
+ return createMutation.mutateAsync(data);
1936
+ },
1937
+ updateEntity: async (id, data) => {
1938
+ if (!id) {
1939
+ console.warn("[useOrbitalMutations] Cannot update without ID");
1940
+ return;
1941
+ }
1942
+ return updateMutation.mutateAsync({ id, data });
1943
+ },
1944
+ deleteEntity: async (id) => {
1945
+ if (!id) {
1946
+ console.warn("[useOrbitalMutations] Cannot delete without ID");
1947
+ return;
1948
+ }
1949
+ return deleteMutation.mutateAsync(id);
1950
+ },
1951
+ // Mutation objects for fine-grained control
1952
+ createMutation,
1953
+ updateMutation,
1954
+ deleteMutation,
1955
+ // Aggregate states
1956
+ isCreating: createMutation.isPending,
1957
+ isUpdating: updateMutation.isPending,
1958
+ isDeleting: deleteMutation.isPending,
1959
+ isMutating: createMutation.isPending || updateMutation.isPending || deleteMutation.isPending,
1960
+ // Errors
1961
+ createError: createMutation.error,
1962
+ updateError: updateMutation.error,
1963
+ deleteError: deleteMutation.error
1964
+ };
1965
+ }
1966
+ function useSendOrbitalEvent(orbitalName) {
1967
+ const mutation = useMutation({
1968
+ mutationFn: async (payload) => {
1969
+ return sendOrbitalEvent(orbitalName, payload);
1970
+ }
1971
+ });
1972
+ return {
1973
+ sendEvent: async (event, payload, entityId) => {
1974
+ return mutation.mutateAsync({ event, payload, entityId });
1975
+ },
1976
+ isPending: mutation.isPending,
1977
+ error: mutation.error,
1978
+ data: mutation.data
1979
+ };
1980
+ }
1981
+
1982
+ // hooks/useEntityMutations.ts
1983
+ function entityToCollection(entityName) {
1984
+ return entityName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase() + "-list";
1985
+ }
1986
+ function useCreateEntity(entityName) {
1987
+ const queryClient = useQueryClient();
1988
+ const collection = entityToCollection(entityName);
1989
+ return useMutation({
1990
+ mutationFn: async (data) => {
1991
+ console.log(`[useCreateEntity] Creating ${entityName}:`, data);
1992
+ const response = await apiClient.post(
1993
+ `/${collection}`,
1994
+ data
1995
+ );
1996
+ return response.data;
1997
+ },
1998
+ onSuccess: () => {
1999
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2000
+ },
2001
+ onError: (error) => {
2002
+ console.error(`[useCreateEntity] Failed to create ${entityName}:`, error);
2003
+ }
2004
+ });
2005
+ }
2006
+ function useUpdateEntity(entityName) {
2007
+ const queryClient = useQueryClient();
2008
+ const collection = entityToCollection(entityName);
2009
+ return useMutation({
2010
+ mutationFn: async ({ id, data }) => {
2011
+ console.log(`[useUpdateEntity] Updating ${entityName} ${id}:`, data);
2012
+ const response = await apiClient.patch(
2013
+ `/${collection}/${id}`,
2014
+ data
2015
+ );
2016
+ return response.data;
2017
+ },
2018
+ onSuccess: (_, variables) => {
2019
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2020
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.detail(entityName, variables.id) });
2021
+ },
2022
+ onError: (error) => {
2023
+ console.error(`[useUpdateEntity] Failed to update ${entityName}:`, error);
2024
+ }
2025
+ });
2026
+ }
2027
+ function useDeleteEntity(entityName) {
2028
+ const queryClient = useQueryClient();
2029
+ const collection = entityToCollection(entityName);
2030
+ return useMutation({
2031
+ mutationFn: async (id) => {
2032
+ console.log(`[useDeleteEntity] Deleting ${entityName} ${id}`);
2033
+ await apiClient.delete(`/${collection}/${id}`);
2034
+ return { id };
2035
+ },
2036
+ onSuccess: (_, id) => {
2037
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2038
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
2039
+ },
2040
+ onError: (error) => {
2041
+ console.error(`[useDeleteEntity] Failed to delete ${entityName}:`, error);
2042
+ }
2043
+ });
2044
+ }
2045
+ async function sendOrbitalMutation(orbitalName, event, entityId, payload) {
2046
+ const response = await apiClient.post(
2047
+ `/orbitals/${orbitalName}/events`,
2048
+ { event, entityId, payload }
2049
+ );
2050
+ return response;
2051
+ }
2052
+ function useEntityMutations(entityName, options) {
2053
+ const queryClient = useQueryClient();
2054
+ const useOrbitalRoute = !!options?.orbitalName;
2055
+ const events = {
2056
+ create: options?.events?.create || ENTITY_EVENTS.CREATE,
2057
+ update: options?.events?.update || ENTITY_EVENTS.UPDATE,
2058
+ delete: options?.events?.delete || ENTITY_EVENTS.DELETE
2059
+ };
2060
+ const createMutation = useCreateEntity(entityName);
2061
+ const updateMutation = useUpdateEntity(entityName);
2062
+ const deleteMutation = useDeleteEntity(entityName);
2063
+ const orbitalCreateMutation = useMutation({
2064
+ mutationFn: async (data) => {
2065
+ return sendOrbitalMutation(options.orbitalName, events.create, void 0, {
2066
+ data,
2067
+ entityType: entityName
2068
+ });
2069
+ },
2070
+ onSuccess: () => {
2071
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2072
+ }
2073
+ });
2074
+ const orbitalUpdateMutation = useMutation({
2075
+ mutationFn: async ({ id, data }) => {
2076
+ return sendOrbitalMutation(options.orbitalName, events.update, id, {
2077
+ data,
2078
+ entityType: entityName
2079
+ });
2080
+ },
2081
+ onSuccess: (_, variables) => {
2082
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2083
+ queryClient.invalidateQueries({
2084
+ queryKey: entityDataKeys.detail(entityName, variables.id)
2085
+ });
2086
+ }
2087
+ });
2088
+ const orbitalDeleteMutation = useMutation({
2089
+ mutationFn: async (id) => {
2090
+ return sendOrbitalMutation(options.orbitalName, events.delete, id, {
2091
+ entityType: entityName
2092
+ });
2093
+ },
2094
+ onSuccess: (_, id) => {
2095
+ queryClient.invalidateQueries({ queryKey: entityDataKeys.list(entityName) });
2096
+ queryClient.removeQueries({ queryKey: entityDataKeys.detail(entityName, id) });
2097
+ }
2098
+ });
2099
+ const activeMutations = {
2100
+ create: useOrbitalRoute ? orbitalCreateMutation : createMutation,
2101
+ update: useOrbitalRoute ? orbitalUpdateMutation : updateMutation,
2102
+ delete: useOrbitalRoute ? orbitalDeleteMutation : deleteMutation
2103
+ };
2104
+ return {
2105
+ // Async functions that can be called directly
2106
+ // Accepts either (data) or (entityName, data) for compiler compatibility
2107
+ createEntity: async (entityOrData, data) => {
2108
+ const actualData = typeof entityOrData === "string" ? data : entityOrData;
2109
+ if (!actualData) {
2110
+ console.warn("[useEntityMutations] Cannot create entity without data");
2111
+ return;
2112
+ }
2113
+ return activeMutations.create.mutateAsync(actualData);
2114
+ },
2115
+ updateEntity: async (id, data) => {
2116
+ if (!id) {
2117
+ console.warn("[useEntityMutations] Cannot update entity without ID");
2118
+ return;
2119
+ }
2120
+ return activeMutations.update.mutateAsync({ id, data });
2121
+ },
2122
+ deleteEntity: async (id) => {
2123
+ if (!id) {
2124
+ console.warn("[useEntityMutations] Cannot delete entity without ID");
2125
+ return;
2126
+ }
2127
+ return activeMutations.delete.mutateAsync(id);
2128
+ },
2129
+ // Mutation states for UI feedback
2130
+ isCreating: activeMutations.create.isPending,
2131
+ isUpdating: activeMutations.update.isPending,
2132
+ isDeleting: activeMutations.delete.isPending,
2133
+ createError: activeMutations.create.error,
2134
+ updateError: activeMutations.update.error,
2135
+ deleteError: activeMutations.delete.error
2136
+ };
2137
+ }
2138
+
2139
+ // stores/entityStore.ts
2140
+ var entities = /* @__PURE__ */ new Map();
2141
+ var listeners = /* @__PURE__ */ new Set();
2142
+ var idCounter2 = 0;
2143
+ function subscribe(listener) {
2144
+ listeners.add(listener);
2145
+ return () => listeners.delete(listener);
2146
+ }
2147
+ function notify() {
2148
+ listeners.forEach((listener) => listener());
2149
+ }
2150
+ function getEntity(id) {
2151
+ return entities.get(id);
2152
+ }
2153
+ function getByType(type) {
2154
+ const types = Array.isArray(type) ? type : [type];
2155
+ return [...entities.values()].filter((e) => types.includes(e.type));
2156
+ }
2157
+ function getAllEntities() {
2158
+ return [...entities.values()];
2159
+ }
2160
+ function getSingleton(type) {
2161
+ return [...entities.values()].find((e) => e.type === type);
2162
+ }
2163
+ function spawnEntity(config) {
2164
+ const id = config.id ?? `entity_${++idCounter2}`;
2165
+ const entity = { ...config, id };
2166
+ entities = new Map(entities);
2167
+ entities.set(id, entity);
2168
+ notify();
2169
+ return id;
2170
+ }
2171
+ function updateEntity(id, updates) {
2172
+ const entity = entities.get(id);
2173
+ if (entity) {
2174
+ entities = new Map(entities);
2175
+ entities.set(id, { ...entity, ...updates });
2176
+ notify();
2177
+ }
2178
+ }
2179
+ function updateSingleton(type, updates) {
2180
+ const entity = getSingleton(type);
2181
+ if (entity) {
2182
+ updateEntity(entity.id, updates);
2183
+ }
2184
+ }
2185
+ function removeEntity(id) {
2186
+ if (entities.has(id)) {
2187
+ entities = new Map(entities);
2188
+ entities.delete(id);
2189
+ notify();
2190
+ }
2191
+ }
2192
+ function clearEntities() {
2193
+ entities = /* @__PURE__ */ new Map();
2194
+ notify();
2195
+ }
2196
+ function getSnapshot() {
2197
+ return entities;
2198
+ }
2199
+
2200
+ // hooks/useEntities.ts
2201
+ function useEntities() {
2202
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2203
+ return {
2204
+ entities: entities2,
2205
+ getEntity,
2206
+ getByType,
2207
+ getAllEntities,
2208
+ getSingleton,
2209
+ spawnEntity,
2210
+ updateEntity,
2211
+ updateSingleton,
2212
+ removeEntity,
2213
+ clearEntities
2214
+ };
2215
+ }
2216
+ function useEntity2(id) {
2217
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2218
+ return entities2.get(id);
2219
+ }
2220
+ function useEntitiesByType(type) {
2221
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2222
+ return [...entities2.values()].filter((e) => e.type === type);
2223
+ }
2224
+ function useSingletonEntity(type) {
2225
+ const entities2 = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
2226
+ return [...entities2.values()].find((e) => e.type === type);
2227
+ }
2228
+ function usePlayer() {
2229
+ const player = useSingletonEntity("Player");
2230
+ const update = useCallback((updates) => {
2231
+ if (player) updateEntity(player.id, updates);
2232
+ }, [player?.id]);
2233
+ return { player, updatePlayer: update };
2234
+ }
2235
+ function usePhysics() {
2236
+ const physics = useSingletonEntity("Physics");
2237
+ const update = useCallback((updates) => {
2238
+ if (physics) updateEntity(physics.id, updates);
2239
+ }, [physics?.id]);
2240
+ return { physics, updatePhysics: update };
2241
+ }
2242
+ function useInput() {
2243
+ const input = useSingletonEntity("Input");
2244
+ const update = useCallback((updates) => {
2245
+ if (input) updateEntity(input.id, updates);
2246
+ }, [input?.id]);
2247
+ return { input, updateInput: update };
2248
+ }
2249
+
2250
+ // hooks/useAuthContext.ts
2251
+ function useAuthContext() {
2252
+ return {
2253
+ user: null,
2254
+ loading: false,
2255
+ signIn: void 0,
2256
+ signOut: void 0
2257
+ };
2258
+ }
2259
+
2260
+ export { DEFAULT_SLOTS, ENTITY_EVENTS, clearEntities, entityDataKeys, getAllEntities, getByType, getEntity, getSingleton, parseQueryBinding, removeEntity, spawnEntity, updateEntity, updateSingleton, useAgentChat, useAuthContext, useCompile, useCreateEntity, useDeepAgentGeneration, useDeleteEntity, useEmitEvent, useEntities, useEntitiesByType, useEntity, useEntity2 as useEntityById, useEntityDetail, useEntityList, useEntityMutations, useEventBus, useEventListener, useExtensions, useFileEditor, useFileSystem, useInput, useOrbitalHistory, useOrbitalMutations, usePhysics, usePlayer, usePreview, useQuerySingleton, useSelectedEntity, useSendOrbitalEvent, useSingletonEntity, useUIEvents, useUISlotManager, useUpdateEntity, useValidation };
2261
+ //# sourceMappingURL=index.js.map
2262
+ //# sourceMappingURL=index.js.map