@xmachines/json-render-react 0.19.0-xm.1

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1832 @@
1
+ import {
2
+ elementTreeSchema,
3
+ schema
4
+ } from "./chunk-WYDS23XB.mjs";
5
+
6
+ // ../react-state/dist/index.mjs
7
+ import {
8
+ createContext,
9
+ useContext,
10
+ useCallback,
11
+ useEffect,
12
+ useMemo,
13
+ useRef,
14
+ useSyncExternalStore
15
+ } from "react";
16
+ import {
17
+ getByPath,
18
+ createStateStore
19
+ } from "@xmachines/json-render-core";
20
+ import { flattenToPointers } from "@xmachines/json-render-core/store-utils";
21
+ import { jsx } from "react/jsx-runtime";
22
+ var StateContext = createContext(null);
23
+ function computeInitialFlat(isControlled, initialState) {
24
+ if (isControlled) return null;
25
+ if (Object.keys(initialState).length === 0) return {};
26
+ return flattenToPointers(initialState);
27
+ }
28
+ function StateProvider({
29
+ store: externalStore,
30
+ initialState = {},
31
+ onStateChange,
32
+ children
33
+ }) {
34
+ const internalStoreRef = useRef(void 0);
35
+ if (!externalStore && !internalStoreRef.current) {
36
+ internalStoreRef.current = createStateStore(initialState);
37
+ }
38
+ const store = externalStore ?? internalStoreRef.current;
39
+ const storeRef = useRef(store);
40
+ storeRef.current = store;
41
+ const isControlledRef = useRef(!!externalStore);
42
+ isControlledRef.current = !!externalStore;
43
+ const initialModeRef = useRef(externalStore ? "controlled" : "uncontrolled");
44
+ const modeWarnedRef = useRef(false);
45
+ if (process.env.NODE_ENV !== "production") {
46
+ const currentMode = externalStore ? "controlled" : "uncontrolled";
47
+ if (currentMode !== initialModeRef.current && !modeWarnedRef.current) {
48
+ modeWarnedRef.current = true;
49
+ console.warn(
50
+ `StateProvider: switching from ${initialModeRef.current} to ${currentMode} mode is not supported.`
51
+ );
52
+ }
53
+ }
54
+ const prevInitialStateRef = useRef(initialState);
55
+ const prevFlatRef = useRef(
56
+ computeInitialFlat(!!externalStore, initialState)
57
+ );
58
+ useEffect(() => {
59
+ if (externalStore) return;
60
+ if (initialState === prevInitialStateRef.current) return;
61
+ prevInitialStateRef.current = initialState;
62
+ const nextFlat = initialState && Object.keys(initialState).length > 0 ? flattenToPointers(initialState) : {};
63
+ const prevFlat = prevFlatRef.current ?? {};
64
+ const allKeys = /* @__PURE__ */ new Set([
65
+ ...Object.keys(prevFlat),
66
+ ...Object.keys(nextFlat)
67
+ ]);
68
+ const updates = {};
69
+ for (const key of allKeys) {
70
+ if (prevFlat[key] !== nextFlat[key]) {
71
+ updates[key] = key in nextFlat ? nextFlat[key] : void 0;
72
+ }
73
+ }
74
+ prevFlatRef.current = nextFlat;
75
+ if (Object.keys(updates).length > 0) {
76
+ store.update(updates);
77
+ }
78
+ }, [externalStore, initialState, store]);
79
+ const state = useSyncExternalStore(
80
+ store.subscribe,
81
+ store.getSnapshot,
82
+ store.getServerSnapshot ?? store.getSnapshot
83
+ );
84
+ const onStateChangeRef = useRef(onStateChange);
85
+ onStateChangeRef.current = onStateChange;
86
+ const set = useCallback((path, value2) => {
87
+ const s = storeRef.current;
88
+ const prev = s.getSnapshot();
89
+ s.set(path, value2);
90
+ if (!isControlledRef.current && s.getSnapshot() !== prev) {
91
+ onStateChangeRef.current?.([{ path, value: value2 }]);
92
+ }
93
+ }, []);
94
+ const update = useCallback((updates) => {
95
+ const s = storeRef.current;
96
+ const prev = s.getSnapshot();
97
+ s.update(updates);
98
+ if (!isControlledRef.current && s.getSnapshot() !== prev) {
99
+ const changes = [];
100
+ for (const [path, value2] of Object.entries(updates)) {
101
+ if (getByPath(prev, path) !== value2) {
102
+ changes.push({ path, value: value2 });
103
+ }
104
+ }
105
+ if (changes.length > 0) {
106
+ onStateChangeRef.current?.(changes);
107
+ }
108
+ }
109
+ }, []);
110
+ const get = useCallback((path) => storeRef.current.get(path), []);
111
+ const getSnapshot = useCallback(() => storeRef.current.getSnapshot(), []);
112
+ const value = useMemo(
113
+ () => ({ state, get, set, update, getSnapshot }),
114
+ [state, get, set, update, getSnapshot]
115
+ );
116
+ return /* @__PURE__ */ jsx(StateContext.Provider, { value, children });
117
+ }
118
+ function useStateStore() {
119
+ const ctx = useContext(StateContext);
120
+ if (!ctx) {
121
+ throw new Error("useStateStore must be used within a StateProvider");
122
+ }
123
+ return ctx;
124
+ }
125
+ function useStateValue(path) {
126
+ const { state } = useStateStore();
127
+ return getByPath(state, path);
128
+ }
129
+ function useStateBinding(path) {
130
+ const { state, set } = useStateStore();
131
+ const value = getByPath(state, path);
132
+ const setValue = useCallback(
133
+ (newValue) => set(path, newValue),
134
+ [path, set]
135
+ );
136
+ return [value, setValue];
137
+ }
138
+
139
+ // src/contexts/visibility.tsx
140
+ import {
141
+ createContext as createContext2,
142
+ useContext as useContext2,
143
+ useMemo as useMemo2
144
+ } from "react";
145
+ import {
146
+ evaluateVisibility
147
+ } from "@xmachines/json-render-core";
148
+ import { jsx as jsx2 } from "react/jsx-runtime";
149
+ var VisibilityContext = createContext2(null);
150
+ function VisibilityProvider({ children }) {
151
+ const { state } = useStateStore();
152
+ const ctx = useMemo2(
153
+ () => ({
154
+ stateModel: state
155
+ }),
156
+ [state]
157
+ );
158
+ const isVisible = useMemo2(
159
+ () => (condition) => evaluateVisibility(condition, ctx),
160
+ [ctx]
161
+ );
162
+ const value = useMemo2(
163
+ () => ({ isVisible, ctx }),
164
+ [isVisible, ctx]
165
+ );
166
+ return /* @__PURE__ */ jsx2(VisibilityContext.Provider, { value, children });
167
+ }
168
+ function useVisibility() {
169
+ const ctx = useContext2(VisibilityContext);
170
+ if (!ctx) {
171
+ throw new Error("useVisibility must be used within a VisibilityProvider");
172
+ }
173
+ return ctx;
174
+ }
175
+ function useIsVisible(condition) {
176
+ const { isVisible } = useVisibility();
177
+ return isVisible(condition);
178
+ }
179
+
180
+ // src/contexts/actions.tsx
181
+ import {
182
+ createContext as createContext4,
183
+ useContext as useContext4,
184
+ useState as useState2,
185
+ useCallback as useCallback3,
186
+ useMemo as useMemo4
187
+ } from "react";
188
+ import {
189
+ resolveAction,
190
+ executeAction,
191
+ nextActionDispatchId,
192
+ notifyActionDispatch,
193
+ notifyActionSettle
194
+ } from "@xmachines/json-render-core";
195
+
196
+ // src/contexts/validation.tsx
197
+ import React2, {
198
+ createContext as createContext3,
199
+ useContext as useContext3,
200
+ useRef as useRef2,
201
+ useState,
202
+ useCallback as useCallback2,
203
+ useMemo as useMemo3
204
+ } from "react";
205
+ import {
206
+ runValidation
207
+ } from "@xmachines/json-render-core";
208
+ import { jsx as jsx3 } from "react/jsx-runtime";
209
+ var ValidationContext = createContext3(null);
210
+ function dynamicArgsEqual(a, b) {
211
+ if (a === b) return true;
212
+ if (!a || !b) return false;
213
+ const keysA = Object.keys(a);
214
+ const keysB = Object.keys(b);
215
+ if (keysA.length !== keysB.length) return false;
216
+ for (const key of keysA) {
217
+ const va = a[key];
218
+ const vb = b[key];
219
+ if (va === vb) continue;
220
+ if (typeof va === "object" && va !== null && typeof vb === "object" && vb !== null) {
221
+ const sa = va.$state;
222
+ const sb = vb.$state;
223
+ if (typeof sa === "string" && sa === sb) continue;
224
+ }
225
+ return false;
226
+ }
227
+ return true;
228
+ }
229
+ function validationConfigEqual(a, b) {
230
+ if (a === b) return true;
231
+ if (a.validateOn !== b.validateOn) return false;
232
+ const ac = a.checks ?? [];
233
+ const bc = b.checks ?? [];
234
+ if (ac.length !== bc.length) return false;
235
+ for (let i = 0; i < ac.length; i++) {
236
+ const ca = ac[i];
237
+ const cb = bc[i];
238
+ if (ca.type !== cb.type) return false;
239
+ if (ca.message !== cb.message) return false;
240
+ if (!dynamicArgsEqual(ca.args, cb.args)) return false;
241
+ }
242
+ return true;
243
+ }
244
+ function ValidationProvider({
245
+ customFunctions = {},
246
+ children
247
+ }) {
248
+ const { state, getSnapshot } = useStateStore();
249
+ const [fieldStates, setFieldStates] = useState({});
250
+ const fieldStatesRef = useRef2({});
251
+ const [fieldConfigs, setFieldConfigs] = useState({});
252
+ const registerField = useCallback2(
253
+ (path, config) => {
254
+ setFieldConfigs((prev) => {
255
+ const existing = prev[path];
256
+ if (existing && validationConfigEqual(existing, config)) {
257
+ return prev;
258
+ }
259
+ return { ...prev, [path]: config };
260
+ });
261
+ },
262
+ []
263
+ );
264
+ const validate = useCallback2(
265
+ (path, config) => {
266
+ const currentState = getSnapshot();
267
+ const segments = path.split("/").filter(Boolean);
268
+ let value2 = currentState;
269
+ for (const seg of segments) {
270
+ if (value2 != null && typeof value2 === "object") {
271
+ value2 = value2[seg];
272
+ } else {
273
+ value2 = void 0;
274
+ break;
275
+ }
276
+ }
277
+ const result = runValidation(config, {
278
+ value: value2,
279
+ stateModel: currentState,
280
+ customFunctions
281
+ });
282
+ const newFieldState = {
283
+ touched: fieldStatesRef.current[path]?.touched ?? true,
284
+ validated: true,
285
+ result
286
+ };
287
+ fieldStatesRef.current = {
288
+ ...fieldStatesRef.current,
289
+ [path]: newFieldState
290
+ };
291
+ setFieldStates(fieldStatesRef.current);
292
+ return result;
293
+ },
294
+ [customFunctions, getSnapshot]
295
+ );
296
+ const touch = useCallback2((path) => {
297
+ fieldStatesRef.current = {
298
+ ...fieldStatesRef.current,
299
+ [path]: {
300
+ ...fieldStatesRef.current[path],
301
+ touched: true,
302
+ validated: fieldStatesRef.current[path]?.validated ?? false,
303
+ result: fieldStatesRef.current[path]?.result ?? null
304
+ }
305
+ };
306
+ setFieldStates(fieldStatesRef.current);
307
+ }, []);
308
+ const clear = useCallback2((path) => {
309
+ const { [path]: _, ...rest } = fieldStatesRef.current;
310
+ fieldStatesRef.current = rest;
311
+ setFieldStates(rest);
312
+ }, []);
313
+ const validateAll = useCallback2(() => {
314
+ let allValid = true;
315
+ for (const [path, config] of Object.entries(fieldConfigs)) {
316
+ const result = validate(path, config);
317
+ if (!result.valid) {
318
+ allValid = false;
319
+ }
320
+ }
321
+ return allValid;
322
+ }, [fieldConfigs, validate]);
323
+ const value = useMemo3(
324
+ () => ({
325
+ customFunctions,
326
+ // Getter returns the mutable ref so callers that read fieldStates
327
+ // synchronously after validateAll() see the latest values.
328
+ get fieldStates() {
329
+ return fieldStatesRef.current;
330
+ },
331
+ validate,
332
+ touch,
333
+ clear,
334
+ validateAll,
335
+ registerField
336
+ }),
337
+ [
338
+ customFunctions,
339
+ // fieldStates (React state) stays in deps so the context value object
340
+ // is recreated on re-render, triggering downstream consumers.
341
+ fieldStates,
342
+ validate,
343
+ touch,
344
+ clear,
345
+ validateAll,
346
+ registerField
347
+ ]
348
+ );
349
+ return /* @__PURE__ */ jsx3(ValidationContext.Provider, { value, children });
350
+ }
351
+ function useValidation() {
352
+ const ctx = useContext3(ValidationContext);
353
+ if (!ctx) {
354
+ throw new Error("useValidation must be used within a ValidationProvider");
355
+ }
356
+ return ctx;
357
+ }
358
+ function useOptionalValidation() {
359
+ return useContext3(ValidationContext);
360
+ }
361
+ function useFieldValidation(path, config) {
362
+ const {
363
+ fieldStates,
364
+ validate: validateField,
365
+ touch: touchField,
366
+ clear: clearField,
367
+ registerField
368
+ } = useValidation();
369
+ React2.useEffect(() => {
370
+ if (path && config) {
371
+ registerField(path, config);
372
+ }
373
+ }, [path, config, registerField]);
374
+ const state = fieldStates[path] ?? {
375
+ touched: false,
376
+ validated: false,
377
+ result: null
378
+ };
379
+ const validate = useCallback2(
380
+ () => validateField(path, config ?? { checks: [] }),
381
+ [path, config, validateField]
382
+ );
383
+ const touch = useCallback2(() => touchField(path), [path, touchField]);
384
+ const clear = useCallback2(() => clearField(path), [path, clearField]);
385
+ return {
386
+ state,
387
+ validate,
388
+ touch,
389
+ clear,
390
+ errors: state.result?.errors ?? [],
391
+ isValid: state.result?.valid ?? true
392
+ };
393
+ }
394
+
395
+ // src/contexts/actions.tsx
396
+ import { jsx as jsx4, jsxs } from "react/jsx-runtime";
397
+ var idCounter = 0;
398
+ function generateUniqueId() {
399
+ idCounter += 1;
400
+ return `${Date.now()}-${idCounter}`;
401
+ }
402
+ function deepResolveValue(value, get) {
403
+ if (value === null || value === void 0) return value;
404
+ if (value === "$id") {
405
+ return generateUniqueId();
406
+ }
407
+ if (typeof value === "object" && !Array.isArray(value)) {
408
+ const obj = value;
409
+ const keys = Object.keys(obj);
410
+ if (keys.length === 1 && typeof obj.$state === "string") {
411
+ return get(obj.$state);
412
+ }
413
+ if (keys.length === 1 && "$id" in obj) {
414
+ return generateUniqueId();
415
+ }
416
+ }
417
+ if (Array.isArray(value)) {
418
+ return value.map((item) => deepResolveValue(item, get));
419
+ }
420
+ if (typeof value === "object") {
421
+ const resolved = {};
422
+ for (const [key, val] of Object.entries(value)) {
423
+ resolved[key] = deepResolveValue(val, get);
424
+ }
425
+ return resolved;
426
+ }
427
+ return value;
428
+ }
429
+ var ActionContext = createContext4(null);
430
+ function ActionProvider({
431
+ handlers: initialHandlers = {},
432
+ navigate,
433
+ children
434
+ }) {
435
+ const { get, set, getSnapshot } = useStateStore();
436
+ const validation = useOptionalValidation();
437
+ const [handlers, setHandlers] = useState2(initialHandlers);
438
+ const [loadingActions, setLoadingActions] = useState2(/* @__PURE__ */ new Set());
439
+ const [pendingConfirmation, setPendingConfirmation] = useState2(null);
440
+ const registerHandler = useCallback3(
441
+ (name, handler) => {
442
+ setHandlers((prev) => ({ ...prev, [name]: handler }));
443
+ },
444
+ []
445
+ );
446
+ const execute = useCallback3(
447
+ async (binding) => {
448
+ const resolved = resolveAction(binding, getSnapshot());
449
+ const dispatchId = nextActionDispatchId();
450
+ const dispatchedAt = Date.now();
451
+ notifyActionDispatch({
452
+ id: dispatchId,
453
+ name: resolved.action,
454
+ params: resolved.params,
455
+ at: dispatchedAt
456
+ });
457
+ let __ok = true;
458
+ let __error = void 0;
459
+ try {
460
+ if (resolved.action === "setState" && resolved.params) {
461
+ const statePath = resolved.params.statePath;
462
+ const value2 = resolved.params.value;
463
+ if (statePath) {
464
+ set(statePath, value2);
465
+ }
466
+ return;
467
+ }
468
+ if (resolved.action === "pushState" && resolved.params) {
469
+ const statePath = resolved.params.statePath;
470
+ const rawValue = resolved.params.value;
471
+ if (statePath) {
472
+ const resolvedValue = deepResolveValue(rawValue, get);
473
+ const arr = get(statePath) ?? [];
474
+ set(statePath, [...arr, resolvedValue]);
475
+ const clearStatePath = resolved.params.clearStatePath;
476
+ if (clearStatePath) {
477
+ set(clearStatePath, "");
478
+ }
479
+ }
480
+ return;
481
+ }
482
+ if (resolved.action === "removeState" && resolved.params) {
483
+ const statePath = resolved.params.statePath;
484
+ const index = resolved.params.index;
485
+ if (statePath !== void 0 && index !== void 0) {
486
+ const arr = get(statePath) ?? [];
487
+ set(
488
+ statePath,
489
+ arr.filter((_, i) => i !== index)
490
+ );
491
+ }
492
+ return;
493
+ }
494
+ if (resolved.action === "push" && resolved.params) {
495
+ const screen = resolved.params.screen;
496
+ if (screen) {
497
+ const currentScreen = get("/currentScreen");
498
+ const navStack = get("/navStack") ?? [];
499
+ if (currentScreen) {
500
+ set("/navStack", [...navStack, currentScreen]);
501
+ } else {
502
+ set("/navStack", [...navStack, ""]);
503
+ }
504
+ set("/currentScreen", screen);
505
+ }
506
+ return;
507
+ }
508
+ if (resolved.action === "pop") {
509
+ const navStack = get("/navStack") ?? [];
510
+ if (navStack.length > 0) {
511
+ const previousScreen = navStack[navStack.length - 1];
512
+ set("/navStack", navStack.slice(0, -1));
513
+ if (previousScreen) {
514
+ set("/currentScreen", previousScreen);
515
+ } else {
516
+ set("/currentScreen", void 0);
517
+ }
518
+ }
519
+ return;
520
+ }
521
+ if (resolved.action === "validateForm") {
522
+ const validateAll = validation?.validateAll;
523
+ if (!validateAll) {
524
+ console.warn(
525
+ "validateForm action was dispatched but no ValidationProvider is connected. Ensure ValidationProvider is rendered inside the provider tree."
526
+ );
527
+ return;
528
+ }
529
+ const valid = validateAll();
530
+ const errors = {};
531
+ for (const [path, fs] of Object.entries(validation.fieldStates)) {
532
+ if (fs.result && !fs.result.valid) {
533
+ errors[path] = fs.result.errors;
534
+ }
535
+ }
536
+ const statePath = resolved.params?.statePath || "/formValidation";
537
+ set(statePath, { valid, errors });
538
+ return;
539
+ }
540
+ const handler = handlers[resolved.action];
541
+ if (!handler) {
542
+ console.warn(`No handler registered for action: ${resolved.action}`);
543
+ return;
544
+ }
545
+ if (resolved.confirm) {
546
+ return new Promise((resolve, reject) => {
547
+ setPendingConfirmation({
548
+ action: resolved,
549
+ handler,
550
+ resolve: () => {
551
+ setPendingConfirmation(null);
552
+ resolve();
553
+ },
554
+ reject: () => {
555
+ setPendingConfirmation(null);
556
+ reject(new Error("Action cancelled"));
557
+ }
558
+ });
559
+ }).then(async () => {
560
+ setLoadingActions((prev) => new Set(prev).add(resolved.action));
561
+ try {
562
+ await executeAction({
563
+ action: resolved,
564
+ handler,
565
+ setState: set,
566
+ navigate,
567
+ executeAction: async (name) => {
568
+ const subBinding = { action: name };
569
+ await execute(subBinding);
570
+ }
571
+ });
572
+ } finally {
573
+ setLoadingActions((prev) => {
574
+ const next = new Set(prev);
575
+ next.delete(resolved.action);
576
+ return next;
577
+ });
578
+ }
579
+ });
580
+ }
581
+ setLoadingActions((prev) => new Set(prev).add(resolved.action));
582
+ try {
583
+ await executeAction({
584
+ action: resolved,
585
+ handler,
586
+ setState: set,
587
+ navigate,
588
+ executeAction: async (name) => {
589
+ const subBinding = { action: name };
590
+ await execute(subBinding);
591
+ }
592
+ });
593
+ } finally {
594
+ setLoadingActions((prev) => {
595
+ const next = new Set(prev);
596
+ next.delete(resolved.action);
597
+ return next;
598
+ });
599
+ }
600
+ } catch (err) {
601
+ __ok = false;
602
+ __error = err;
603
+ throw err;
604
+ } finally {
605
+ const now = Date.now();
606
+ notifyActionSettle({
607
+ id: dispatchId,
608
+ name: resolved.action,
609
+ ok: __ok,
610
+ at: now,
611
+ durationMs: now - dispatchedAt,
612
+ error: __error
613
+ });
614
+ }
615
+ },
616
+ [handlers, get, set, getSnapshot, navigate, validation]
617
+ );
618
+ const confirm = useCallback3(() => {
619
+ pendingConfirmation?.resolve();
620
+ }, [pendingConfirmation]);
621
+ const cancel = useCallback3(() => {
622
+ pendingConfirmation?.reject();
623
+ }, [pendingConfirmation]);
624
+ const value = useMemo4(
625
+ () => ({
626
+ handlers,
627
+ loadingActions,
628
+ pendingConfirmation,
629
+ execute,
630
+ confirm,
631
+ cancel,
632
+ registerHandler
633
+ }),
634
+ [
635
+ handlers,
636
+ loadingActions,
637
+ pendingConfirmation,
638
+ execute,
639
+ confirm,
640
+ cancel,
641
+ registerHandler
642
+ ]
643
+ );
644
+ return /* @__PURE__ */ jsx4(ActionContext.Provider, { value, children });
645
+ }
646
+ function useActions() {
647
+ const ctx = useContext4(ActionContext);
648
+ if (!ctx) {
649
+ throw new Error("useActions must be used within an ActionProvider");
650
+ }
651
+ return ctx;
652
+ }
653
+ function useAction(binding) {
654
+ const { execute, loadingActions } = useActions();
655
+ const isLoading = loadingActions.has(binding.action);
656
+ const executeAction2 = useCallback3(() => execute(binding), [execute, binding]);
657
+ return { execute: executeAction2, isLoading };
658
+ }
659
+ function ConfirmDialog({
660
+ confirm,
661
+ onConfirm,
662
+ onCancel
663
+ }) {
664
+ const isDanger = confirm.variant === "danger";
665
+ return /* @__PURE__ */ jsx4(
666
+ "div",
667
+ {
668
+ style: {
669
+ position: "fixed",
670
+ inset: 0,
671
+ backgroundColor: "rgba(0, 0, 0, 0.5)",
672
+ display: "flex",
673
+ alignItems: "center",
674
+ justifyContent: "center",
675
+ zIndex: 50
676
+ },
677
+ onClick: onCancel,
678
+ children: /* @__PURE__ */ jsxs(
679
+ "div",
680
+ {
681
+ style: {
682
+ backgroundColor: "white",
683
+ borderRadius: "8px",
684
+ padding: "24px",
685
+ maxWidth: "400px",
686
+ width: "100%",
687
+ boxShadow: "0 20px 25px -5px rgba(0, 0, 0, 0.1)"
688
+ },
689
+ onClick: (e) => e.stopPropagation(),
690
+ children: [
691
+ /* @__PURE__ */ jsx4(
692
+ "h3",
693
+ {
694
+ style: {
695
+ margin: "0 0 8px 0",
696
+ fontSize: "18px",
697
+ fontWeight: 600
698
+ },
699
+ children: confirm.title
700
+ }
701
+ ),
702
+ /* @__PURE__ */ jsx4(
703
+ "p",
704
+ {
705
+ style: {
706
+ margin: "0 0 24px 0",
707
+ color: "#6b7280"
708
+ },
709
+ children: confirm.message
710
+ }
711
+ ),
712
+ /* @__PURE__ */ jsxs(
713
+ "div",
714
+ {
715
+ style: {
716
+ display: "flex",
717
+ gap: "12px",
718
+ justifyContent: "flex-end"
719
+ },
720
+ children: [
721
+ /* @__PURE__ */ jsx4(
722
+ "button",
723
+ {
724
+ onClick: onCancel,
725
+ style: {
726
+ padding: "8px 16px",
727
+ borderRadius: "6px",
728
+ border: "1px solid #d1d5db",
729
+ backgroundColor: "white",
730
+ cursor: "pointer"
731
+ },
732
+ children: confirm.cancelLabel ?? "Cancel"
733
+ }
734
+ ),
735
+ /* @__PURE__ */ jsx4(
736
+ "button",
737
+ {
738
+ onClick: onConfirm,
739
+ style: {
740
+ padding: "8px 16px",
741
+ borderRadius: "6px",
742
+ border: "none",
743
+ backgroundColor: isDanger ? "#dc2626" : "#3b82f6",
744
+ color: "white",
745
+ cursor: "pointer"
746
+ },
747
+ children: confirm.confirmLabel ?? "Confirm"
748
+ }
749
+ )
750
+ ]
751
+ }
752
+ )
753
+ ]
754
+ }
755
+ )
756
+ }
757
+ );
758
+ }
759
+
760
+ // src/contexts/repeat-scope.tsx
761
+ import { createContext as createContext5, useContext as useContext5 } from "react";
762
+ import { jsx as jsx5 } from "react/jsx-runtime";
763
+ var RepeatScopeContext = createContext5(null);
764
+ function RepeatScopeProvider({
765
+ item,
766
+ index,
767
+ basePath,
768
+ children
769
+ }) {
770
+ return /* @__PURE__ */ jsx5(RepeatScopeContext.Provider, { value: { item, index, basePath }, children });
771
+ }
772
+ function useRepeatScope() {
773
+ return useContext5(RepeatScopeContext);
774
+ }
775
+
776
+ // src/index.ts
777
+ import { createStateStore as createStateStore2 } from "@xmachines/json-render-core";
778
+
779
+ // src/renderer.tsx
780
+ import React5, {
781
+ useCallback as useCallback4,
782
+ useEffect as useEffect2,
783
+ useMemo as useMemo5,
784
+ useRef as useRef3
785
+ } from "react";
786
+ import {
787
+ resolveElementProps,
788
+ resolveBindings,
789
+ resolveActionParam,
790
+ evaluateVisibility as evaluateVisibility2,
791
+ getByPath as getByPath2,
792
+ isDevtoolsActive,
793
+ subscribeDevtoolsActive,
794
+ createDirectiveRegistry
795
+ } from "@xmachines/json-render-core";
796
+ import { Fragment, jsx as jsx6, jsxs as jsxs2 } from "react/jsx-runtime";
797
+ function reportRenderError(registry, elementType, error, componentStack) {
798
+ const onRenderError = registry?.onRenderError;
799
+ if (typeof onRenderError === "function") {
800
+ onRenderError(error, elementType);
801
+ return;
802
+ }
803
+ console.error(
804
+ `[json-render] Rendering error in <${elementType}>:`,
805
+ error,
806
+ componentStack
807
+ );
808
+ }
809
+ var ElementErrorBoundary = class extends React5.Component {
810
+ constructor(props) {
811
+ super(props);
812
+ this.state = { hasError: false };
813
+ }
814
+ static getDerivedStateFromError() {
815
+ return { hasError: true };
816
+ }
817
+ componentDidCatch(error, info) {
818
+ reportRenderError(
819
+ this.props.registry,
820
+ this.props.elementType,
821
+ error,
822
+ info.componentStack
823
+ );
824
+ }
825
+ render() {
826
+ if (this.state.hasError) {
827
+ return null;
828
+ }
829
+ return this.props.children;
830
+ }
831
+ };
832
+ var EMPTY_FUNCTIONS = {};
833
+ var FunctionsContext = React5.createContext(EMPTY_FUNCTIONS);
834
+ function useFunctions() {
835
+ return React5.useContext(FunctionsContext);
836
+ }
837
+ var DirectivesContext = React5.createContext(
838
+ void 0
839
+ );
840
+ function useDirectives() {
841
+ return React5.useContext(DirectivesContext);
842
+ }
843
+ function useDevtoolsActive() {
844
+ return React5.useSyncExternalStore(
845
+ subscribeDevtoolsActive,
846
+ isDevtoolsActive,
847
+ () => false
848
+ );
849
+ }
850
+ var ElementRenderer = React5.memo(function ElementRenderer2({
851
+ element,
852
+ elementKey,
853
+ spec,
854
+ registry,
855
+ loading,
856
+ fallback
857
+ }) {
858
+ const devtoolsActive = useDevtoolsActive();
859
+ const repeatScope = useRepeatScope();
860
+ const { ctx } = useVisibility();
861
+ const { execute } = useActions();
862
+ const { getSnapshot, state: watchState } = useStateStore();
863
+ const functions = useFunctions();
864
+ const directives = useDirectives();
865
+ const fullCtx = useMemo5(() => {
866
+ const base = repeatScope ? {
867
+ ...ctx,
868
+ repeatItem: repeatScope.item,
869
+ repeatIndex: repeatScope.index,
870
+ repeatBasePath: repeatScope.basePath
871
+ } : { ...ctx };
872
+ base.functions = functions;
873
+ base.directives = directives;
874
+ return base;
875
+ }, [ctx, repeatScope, functions, directives]);
876
+ const isVisible = element.visible === void 0 ? true : evaluateVisibility2(element.visible, fullCtx);
877
+ const onBindings = element.on;
878
+ const emit = useCallback4(
879
+ async (eventName) => {
880
+ const binding = onBindings?.[eventName];
881
+ if (!binding) return;
882
+ const actionBindings = Array.isArray(binding) ? binding : [binding];
883
+ for (const b of actionBindings) {
884
+ if (!b.params) {
885
+ await execute(b);
886
+ continue;
887
+ }
888
+ const liveCtx = {
889
+ ...fullCtx,
890
+ stateModel: getSnapshot()
891
+ };
892
+ const resolved = {};
893
+ for (const [key, val] of Object.entries(b.params)) {
894
+ resolved[key] = resolveActionParam(val, liveCtx);
895
+ }
896
+ await execute({ ...b, params: resolved });
897
+ }
898
+ },
899
+ [onBindings, execute, fullCtx, getSnapshot]
900
+ );
901
+ const on = useCallback4(
902
+ (eventName) => {
903
+ const binding = onBindings?.[eventName];
904
+ if (!binding) {
905
+ return { emit: () => {
906
+ }, shouldPreventDefault: false, bound: false };
907
+ }
908
+ const actionBindings = Array.isArray(binding) ? binding : [binding];
909
+ const shouldPreventDefault = actionBindings.some((b) => b.preventDefault);
910
+ return {
911
+ emit: () => emit(eventName),
912
+ shouldPreventDefault,
913
+ bound: true
914
+ };
915
+ },
916
+ [onBindings, emit]
917
+ );
918
+ const watchConfig = element.watch;
919
+ const prevWatchValues = useRef3(null);
920
+ const stableWatchRef = useRef3(void 0);
921
+ const watchedValues = useMemo5(() => {
922
+ if (!watchConfig) return void 0;
923
+ const values = {};
924
+ for (const path of Object.keys(watchConfig)) {
925
+ values[path] = getByPath2(watchState, path);
926
+ }
927
+ const prev = stableWatchRef.current;
928
+ if (prev) {
929
+ const keys = Object.keys(values);
930
+ if (keys.length === Object.keys(prev).length && keys.every((k) => values[k] === prev[k])) {
931
+ return prev;
932
+ }
933
+ }
934
+ stableWatchRef.current = values;
935
+ return values;
936
+ }, [watchConfig, watchState]);
937
+ useEffect2(() => {
938
+ if (!watchConfig || !watchedValues) return;
939
+ const paths = Object.keys(watchConfig);
940
+ if (paths.length === 0) return;
941
+ const prev = prevWatchValues.current;
942
+ prevWatchValues.current = watchedValues;
943
+ if (prev === null) return;
944
+ let cancelled = false;
945
+ void (async () => {
946
+ for (const path of paths) {
947
+ if (cancelled) break;
948
+ if (watchedValues[path] !== prev[path]) {
949
+ const binding = watchConfig[path];
950
+ if (!binding) continue;
951
+ const bindings = Array.isArray(binding) ? binding : [binding];
952
+ for (const b of bindings) {
953
+ if (cancelled) break;
954
+ if (!b.params) {
955
+ await execute(b);
956
+ if (cancelled) break;
957
+ continue;
958
+ }
959
+ const liveCtx = {
960
+ ...fullCtx,
961
+ stateModel: getSnapshot()
962
+ };
963
+ const resolved = {};
964
+ for (const [key, val] of Object.entries(b.params)) {
965
+ resolved[key] = resolveActionParam(val, liveCtx);
966
+ }
967
+ await execute({ ...b, params: resolved });
968
+ if (cancelled) break;
969
+ }
970
+ }
971
+ }
972
+ })().catch(console.error);
973
+ return () => {
974
+ cancelled = true;
975
+ };
976
+ }, [watchConfig, watchedValues, execute, fullCtx, getSnapshot]);
977
+ if (!isVisible) {
978
+ return null;
979
+ }
980
+ const rawProps = element.props;
981
+ const elementBindings = resolveBindings(rawProps, fullCtx);
982
+ const resolvedProps = resolveElementProps(rawProps, fullCtx);
983
+ const resolvedElement = resolvedProps !== element.props ? { ...element, props: resolvedProps } : element;
984
+ const Component = registry[resolvedElement.type] ?? fallback;
985
+ if (!Component) {
986
+ console.warn(`No renderer for component type: ${resolvedElement.type}`);
987
+ return null;
988
+ }
989
+ const children = resolvedElement.repeat ? /* @__PURE__ */ jsx6(
990
+ RepeatChildren,
991
+ {
992
+ element: resolvedElement,
993
+ spec,
994
+ registry,
995
+ loading,
996
+ fallback
997
+ }
998
+ ) : resolvedElement.children?.map((childKey) => {
999
+ const childElement = spec.elements[childKey];
1000
+ if (!childElement) {
1001
+ if (!loading) {
1002
+ console.warn(
1003
+ `[json-render] Missing element "${childKey}" referenced as child of "${resolvedElement.type}". This element will not render.`
1004
+ );
1005
+ }
1006
+ return null;
1007
+ }
1008
+ return /* @__PURE__ */ jsx6(
1009
+ ElementRenderer2,
1010
+ {
1011
+ element: childElement,
1012
+ elementKey: childKey,
1013
+ spec,
1014
+ registry,
1015
+ loading,
1016
+ fallback
1017
+ },
1018
+ childKey
1019
+ );
1020
+ });
1021
+ const rendered = /* @__PURE__ */ jsx6(
1022
+ Component,
1023
+ {
1024
+ element: resolvedElement,
1025
+ emit,
1026
+ on,
1027
+ bindings: elementBindings,
1028
+ loading,
1029
+ children
1030
+ }
1031
+ );
1032
+ const tagged = devtoolsActive && elementKey ? /* @__PURE__ */ jsx6("span", { "data-jr-key": elementKey, style: { display: "contents" }, children: rendered }) : rendered;
1033
+ return /* @__PURE__ */ jsx6(
1034
+ ElementErrorBoundary,
1035
+ {
1036
+ elementType: resolvedElement.type,
1037
+ registry,
1038
+ children: tagged
1039
+ }
1040
+ );
1041
+ });
1042
+ function RepeatChildren({
1043
+ element,
1044
+ spec,
1045
+ registry,
1046
+ loading,
1047
+ fallback
1048
+ }) {
1049
+ const { state } = useStateStore();
1050
+ const repeat = element.repeat;
1051
+ const statePath = repeat.statePath;
1052
+ const items = getByPath2(state, statePath) ?? [];
1053
+ return /* @__PURE__ */ jsx6(Fragment, { children: items.map((itemValue, index) => {
1054
+ const key = repeat.key && typeof itemValue === "object" && itemValue !== null ? String(
1055
+ itemValue[repeat.key] ?? index
1056
+ ) : String(index);
1057
+ return /* @__PURE__ */ jsx6(
1058
+ RepeatScopeProvider,
1059
+ {
1060
+ item: itemValue,
1061
+ index,
1062
+ basePath: `${statePath}/${index}`,
1063
+ children: element.children?.map((childKey) => {
1064
+ const childElement = spec.elements[childKey];
1065
+ if (!childElement) {
1066
+ if (!loading) {
1067
+ console.warn(
1068
+ `[json-render] Missing element "${childKey}" referenced as child of "${element.type}" (repeat). This element will not render.`
1069
+ );
1070
+ }
1071
+ return null;
1072
+ }
1073
+ return /* @__PURE__ */ jsx6(
1074
+ ElementRenderer,
1075
+ {
1076
+ element: childElement,
1077
+ elementKey: childKey,
1078
+ spec,
1079
+ registry,
1080
+ loading,
1081
+ fallback
1082
+ },
1083
+ childKey
1084
+ );
1085
+ })
1086
+ },
1087
+ key
1088
+ );
1089
+ }) });
1090
+ }
1091
+ function Renderer({
1092
+ spec,
1093
+ registry,
1094
+ loading,
1095
+ fallback,
1096
+ onRenderError
1097
+ }) {
1098
+ const rendererRegistry = useMemo5(() => {
1099
+ if (!onRenderError) return registry;
1100
+ const next = { ...registry };
1101
+ Object.defineProperty(next, "onRenderError", {
1102
+ value: onRenderError,
1103
+ enumerable: false,
1104
+ configurable: true
1105
+ });
1106
+ return next;
1107
+ }, [registry, onRenderError]);
1108
+ if (!spec || !spec.root) {
1109
+ return null;
1110
+ }
1111
+ const rootElement = spec.elements[spec.root];
1112
+ if (!rootElement) {
1113
+ return null;
1114
+ }
1115
+ return /* @__PURE__ */ jsx6(
1116
+ ElementRenderer,
1117
+ {
1118
+ element: rootElement,
1119
+ elementKey: spec.root,
1120
+ spec,
1121
+ registry: rendererRegistry,
1122
+ loading,
1123
+ fallback
1124
+ }
1125
+ );
1126
+ }
1127
+ function JSONUIProvider({
1128
+ registry,
1129
+ store,
1130
+ initialState,
1131
+ handlers,
1132
+ navigate,
1133
+ validationFunctions,
1134
+ functions,
1135
+ directives,
1136
+ onStateChange,
1137
+ children
1138
+ }) {
1139
+ const directiveRegistry = useMemo5(
1140
+ () => directives ? createDirectiveRegistry(directives) : void 0,
1141
+ [directives]
1142
+ );
1143
+ return /* @__PURE__ */ jsx6(
1144
+ StateProvider,
1145
+ {
1146
+ store,
1147
+ initialState,
1148
+ onStateChange,
1149
+ children: /* @__PURE__ */ jsx6(VisibilityProvider, { children: /* @__PURE__ */ jsx6(ValidationProvider, { customFunctions: validationFunctions, children: /* @__PURE__ */ jsx6(ActionProvider, { handlers, navigate, children: /* @__PURE__ */ jsx6(FunctionsContext.Provider, { value: functions ?? EMPTY_FUNCTIONS, children: /* @__PURE__ */ jsxs2(DirectivesContext.Provider, { value: directiveRegistry, children: [
1150
+ children,
1151
+ /* @__PURE__ */ jsx6(ConfirmationDialogManager, {})
1152
+ ] }) }) }) }) })
1153
+ }
1154
+ );
1155
+ }
1156
+ function ConfirmationDialogManager() {
1157
+ const { pendingConfirmation, confirm, cancel } = useActions();
1158
+ if (!pendingConfirmation?.action.confirm) {
1159
+ return null;
1160
+ }
1161
+ return /* @__PURE__ */ jsx6(
1162
+ ConfirmDialog,
1163
+ {
1164
+ confirm: pendingConfirmation.action.confirm,
1165
+ onConfirm: confirm,
1166
+ onCancel: cancel
1167
+ }
1168
+ );
1169
+ }
1170
+ function defineRegistry(_catalog, options) {
1171
+ const registry = {};
1172
+ if (options.components) {
1173
+ for (const [name, componentFn] of Object.entries(options.components)) {
1174
+ registry[name] = ({
1175
+ element,
1176
+ children,
1177
+ emit,
1178
+ on,
1179
+ bindings,
1180
+ loading
1181
+ }) => {
1182
+ return componentFn({
1183
+ props: element.props,
1184
+ children,
1185
+ emit,
1186
+ on,
1187
+ bindings,
1188
+ loading
1189
+ });
1190
+ };
1191
+ }
1192
+ }
1193
+ const actionMap = options.actions ? Object.entries(options.actions) : [];
1194
+ const handlers = (getSetState, getState) => {
1195
+ const result = {};
1196
+ for (const [name, actionFn] of actionMap) {
1197
+ result[name] = async (params) => {
1198
+ const setState = getSetState();
1199
+ const state = getState();
1200
+ if (setState) {
1201
+ await actionFn(params, setState, state);
1202
+ }
1203
+ };
1204
+ }
1205
+ return result;
1206
+ };
1207
+ const executeAction2 = async (actionName, params, setState, state = {}) => {
1208
+ const entry = actionMap.find(([name]) => name === actionName);
1209
+ if (entry) {
1210
+ await entry[1](params, setState, state);
1211
+ } else {
1212
+ console.warn(`Unknown action: ${actionName}`);
1213
+ }
1214
+ };
1215
+ if (options.onRenderError) {
1216
+ Object.defineProperty(registry, "onRenderError", {
1217
+ value: options.onRenderError,
1218
+ enumerable: false,
1219
+ configurable: true
1220
+ });
1221
+ }
1222
+ return { registry, handlers, executeAction: executeAction2 };
1223
+ }
1224
+ function createRenderer(catalog, components) {
1225
+ const registry = components;
1226
+ return function CatalogRenderer({
1227
+ spec,
1228
+ store,
1229
+ state,
1230
+ onAction,
1231
+ onStateChange,
1232
+ functions,
1233
+ directives,
1234
+ loading,
1235
+ fallback,
1236
+ onRenderError
1237
+ }) {
1238
+ const directiveRegistry = useMemo5(
1239
+ () => directives ? createDirectiveRegistry(directives) : void 0,
1240
+ [directives]
1241
+ );
1242
+ const rendererRegistry = useMemo5(() => {
1243
+ if (!onRenderError) return registry;
1244
+ const next = { ...registry };
1245
+ Object.defineProperty(next, "onRenderError", {
1246
+ value: onRenderError,
1247
+ enumerable: false,
1248
+ configurable: true
1249
+ });
1250
+ return next;
1251
+ }, [onRenderError]);
1252
+ const actionHandlers = onAction ? new Proxy(
1253
+ {},
1254
+ {
1255
+ get: (_target, prop) => {
1256
+ return (params) => onAction(prop, params);
1257
+ },
1258
+ has: () => true
1259
+ }
1260
+ ) : void 0;
1261
+ return /* @__PURE__ */ jsx6(
1262
+ StateProvider,
1263
+ {
1264
+ store,
1265
+ initialState: state,
1266
+ onStateChange,
1267
+ children: /* @__PURE__ */ jsx6(VisibilityProvider, { children: /* @__PURE__ */ jsx6(ValidationProvider, { children: /* @__PURE__ */ jsx6(ActionProvider, { handlers: actionHandlers, children: /* @__PURE__ */ jsx6(FunctionsContext.Provider, { value: functions ?? EMPTY_FUNCTIONS, children: /* @__PURE__ */ jsxs2(DirectivesContext.Provider, { value: directiveRegistry, children: [
1268
+ /* @__PURE__ */ jsx6(
1269
+ Renderer,
1270
+ {
1271
+ spec,
1272
+ registry: rendererRegistry,
1273
+ loading,
1274
+ fallback
1275
+ }
1276
+ ),
1277
+ /* @__PURE__ */ jsx6(ConfirmationDialogManager, {})
1278
+ ] }) }) }) }) })
1279
+ }
1280
+ );
1281
+ };
1282
+ }
1283
+
1284
+ // src/hooks.ts
1285
+ import { useState as useState3, useCallback as useCallback5, useRef as useRef4, useEffect as useEffect3 } from "react";
1286
+ import {
1287
+ setByPath,
1288
+ getByPath as getByPath3,
1289
+ removeByPath,
1290
+ createMixedStreamParser,
1291
+ applySpecPatch,
1292
+ nestedToFlat,
1293
+ SPEC_DATA_PART_TYPE
1294
+ } from "@xmachines/json-render-core";
1295
+ function parseLine(line) {
1296
+ try {
1297
+ const trimmed = line.trim();
1298
+ if (!trimmed || trimmed.startsWith("//")) {
1299
+ return null;
1300
+ }
1301
+ const parsed = JSON.parse(trimmed);
1302
+ if (parsed.__meta === "usage") {
1303
+ return {
1304
+ type: "usage",
1305
+ usage: {
1306
+ promptTokens: parsed.promptTokens ?? 0,
1307
+ completionTokens: parsed.completionTokens ?? 0,
1308
+ totalTokens: parsed.totalTokens ?? 0
1309
+ }
1310
+ };
1311
+ }
1312
+ return { type: "patch", patch: parsed };
1313
+ } catch {
1314
+ return null;
1315
+ }
1316
+ }
1317
+ function setSpecValue(newSpec, path, value) {
1318
+ if (path === "/root") {
1319
+ newSpec.root = value;
1320
+ return;
1321
+ }
1322
+ if (path === "/state") {
1323
+ newSpec.state = value;
1324
+ return;
1325
+ }
1326
+ if (path.startsWith("/state/")) {
1327
+ if (!newSpec.state) newSpec.state = {};
1328
+ const statePath = path.slice("/state".length);
1329
+ setByPath(newSpec.state, statePath, value);
1330
+ return;
1331
+ }
1332
+ if (path.startsWith("/elements/")) {
1333
+ const pathParts = path.slice("/elements/".length).split("/");
1334
+ const elementKey = pathParts[0];
1335
+ if (!elementKey) return;
1336
+ if (pathParts.length === 1) {
1337
+ newSpec.elements[elementKey] = value;
1338
+ } else {
1339
+ const element = newSpec.elements[elementKey];
1340
+ if (element) {
1341
+ const propPath = "/" + pathParts.slice(1).join("/");
1342
+ const newElement = { ...element };
1343
+ setByPath(
1344
+ newElement,
1345
+ propPath,
1346
+ value
1347
+ );
1348
+ newSpec.elements[elementKey] = newElement;
1349
+ }
1350
+ }
1351
+ }
1352
+ }
1353
+ function removeSpecValue(newSpec, path) {
1354
+ if (path === "/state") {
1355
+ delete newSpec.state;
1356
+ return;
1357
+ }
1358
+ if (path.startsWith("/state/") && newSpec.state) {
1359
+ const statePath = path.slice("/state".length);
1360
+ removeByPath(newSpec.state, statePath);
1361
+ return;
1362
+ }
1363
+ if (path.startsWith("/elements/")) {
1364
+ const pathParts = path.slice("/elements/".length).split("/");
1365
+ const elementKey = pathParts[0];
1366
+ if (!elementKey) return;
1367
+ if (pathParts.length === 1) {
1368
+ const { [elementKey]: _, ...rest } = newSpec.elements;
1369
+ newSpec.elements = rest;
1370
+ } else {
1371
+ const element = newSpec.elements[elementKey];
1372
+ if (element) {
1373
+ const propPath = "/" + pathParts.slice(1).join("/");
1374
+ const newElement = { ...element };
1375
+ removeByPath(
1376
+ newElement,
1377
+ propPath
1378
+ );
1379
+ newSpec.elements[elementKey] = newElement;
1380
+ }
1381
+ }
1382
+ }
1383
+ }
1384
+ function getSpecValue(spec, path) {
1385
+ if (path === "/root") return spec.root;
1386
+ if (path === "/state") return spec.state;
1387
+ if (path.startsWith("/state/") && spec.state) {
1388
+ const statePath = path.slice("/state".length);
1389
+ return getByPath3(spec.state, statePath);
1390
+ }
1391
+ return getByPath3(spec, path);
1392
+ }
1393
+ function applyPatch(spec, patch) {
1394
+ const newSpec = {
1395
+ ...spec,
1396
+ elements: { ...spec.elements },
1397
+ ...spec.state ? { state: { ...spec.state } } : {}
1398
+ };
1399
+ switch (patch.op) {
1400
+ case "add":
1401
+ case "replace": {
1402
+ setSpecValue(newSpec, patch.path, patch.value);
1403
+ break;
1404
+ }
1405
+ case "remove": {
1406
+ removeSpecValue(newSpec, patch.path);
1407
+ break;
1408
+ }
1409
+ case "move": {
1410
+ if (!patch.from) break;
1411
+ const moveValue = getSpecValue(newSpec, patch.from);
1412
+ removeSpecValue(newSpec, patch.from);
1413
+ setSpecValue(newSpec, patch.path, moveValue);
1414
+ break;
1415
+ }
1416
+ case "copy": {
1417
+ if (!patch.from) break;
1418
+ const copyValue = getSpecValue(newSpec, patch.from);
1419
+ setSpecValue(newSpec, patch.path, copyValue);
1420
+ break;
1421
+ }
1422
+ case "test": {
1423
+ break;
1424
+ }
1425
+ }
1426
+ return newSpec;
1427
+ }
1428
+ function useUIStream({
1429
+ api,
1430
+ onComplete,
1431
+ onError
1432
+ }) {
1433
+ const [spec, setSpec] = useState3(null);
1434
+ const [isStreaming, setIsStreaming] = useState3(false);
1435
+ const [error, setError] = useState3(null);
1436
+ const [usage, setUsage] = useState3(null);
1437
+ const [rawLines, setRawLines] = useState3([]);
1438
+ const abortControllerRef = useRef4(null);
1439
+ const onCompleteRef = useRef4(onComplete);
1440
+ onCompleteRef.current = onComplete;
1441
+ const onErrorRef = useRef4(onError);
1442
+ onErrorRef.current = onError;
1443
+ const clear = useCallback5(() => {
1444
+ setSpec(null);
1445
+ setError(null);
1446
+ }, []);
1447
+ const send = useCallback5(
1448
+ async (prompt, context) => {
1449
+ abortControllerRef.current?.abort();
1450
+ abortControllerRef.current = new AbortController();
1451
+ setIsStreaming(true);
1452
+ setError(null);
1453
+ setUsage(null);
1454
+ setRawLines([]);
1455
+ const previousSpec = context?.previousSpec;
1456
+ let currentSpec = previousSpec && previousSpec.root ? { ...previousSpec, elements: { ...previousSpec.elements } } : { root: "", elements: {} };
1457
+ setSpec(currentSpec);
1458
+ try {
1459
+ const response = await fetch(api, {
1460
+ method: "POST",
1461
+ headers: { "Content-Type": "application/json" },
1462
+ body: JSON.stringify({
1463
+ prompt,
1464
+ context,
1465
+ currentSpec
1466
+ }),
1467
+ signal: abortControllerRef.current.signal
1468
+ });
1469
+ if (!response.ok) {
1470
+ let errorMessage = `HTTP error: ${response.status}`;
1471
+ try {
1472
+ const errorData = await response.json();
1473
+ if (errorData.message) {
1474
+ errorMessage = errorData.message;
1475
+ } else if (errorData.error) {
1476
+ errorMessage = errorData.error;
1477
+ }
1478
+ } catch {
1479
+ }
1480
+ throw new Error(errorMessage);
1481
+ }
1482
+ const reader = response.body?.getReader();
1483
+ if (!reader) {
1484
+ throw new Error("No response body");
1485
+ }
1486
+ const decoder = new TextDecoder();
1487
+ let buffer = "";
1488
+ while (true) {
1489
+ const { done, value } = await reader.read();
1490
+ if (done) break;
1491
+ buffer += decoder.decode(value, { stream: true });
1492
+ const lines = buffer.split("\n");
1493
+ buffer = lines.pop() ?? "";
1494
+ for (const line of lines) {
1495
+ const trimmed = line.trim();
1496
+ if (!trimmed) continue;
1497
+ const result = parseLine(trimmed);
1498
+ if (!result) continue;
1499
+ if (result.type === "usage") {
1500
+ setUsage(result.usage);
1501
+ } else {
1502
+ setRawLines((prev) => [...prev, trimmed]);
1503
+ currentSpec = applyPatch(currentSpec, result.patch);
1504
+ setSpec({ ...currentSpec });
1505
+ }
1506
+ }
1507
+ }
1508
+ if (buffer.trim()) {
1509
+ const trimmed = buffer.trim();
1510
+ const result = parseLine(trimmed);
1511
+ if (result) {
1512
+ if (result.type === "usage") {
1513
+ setUsage(result.usage);
1514
+ } else {
1515
+ setRawLines((prev) => [...prev, trimmed]);
1516
+ currentSpec = applyPatch(currentSpec, result.patch);
1517
+ setSpec({ ...currentSpec });
1518
+ }
1519
+ }
1520
+ }
1521
+ onCompleteRef.current?.(currentSpec);
1522
+ } catch (err) {
1523
+ if (err.name === "AbortError") {
1524
+ return;
1525
+ }
1526
+ const error2 = err instanceof Error ? err : new Error(String(err));
1527
+ setError(error2);
1528
+ onErrorRef.current?.(error2);
1529
+ } finally {
1530
+ setIsStreaming(false);
1531
+ }
1532
+ },
1533
+ [api]
1534
+ );
1535
+ useEffect3(() => {
1536
+ return () => {
1537
+ abortControllerRef.current?.abort();
1538
+ };
1539
+ }, []);
1540
+ return {
1541
+ spec,
1542
+ isStreaming,
1543
+ error,
1544
+ usage,
1545
+ rawLines,
1546
+ send,
1547
+ clear
1548
+ };
1549
+ }
1550
+ function flatToTree(elements) {
1551
+ const elementMap = {};
1552
+ let root = "";
1553
+ for (const element of elements) {
1554
+ elementMap[element.key] = {
1555
+ type: element.type,
1556
+ props: element.props,
1557
+ children: [],
1558
+ visible: element.visible
1559
+ };
1560
+ }
1561
+ for (const element of elements) {
1562
+ if (element.parentKey) {
1563
+ const parent = elementMap[element.parentKey];
1564
+ if (parent) {
1565
+ if (!parent.children) {
1566
+ parent.children = [];
1567
+ }
1568
+ parent.children.push(element.key);
1569
+ }
1570
+ } else {
1571
+ root = element.key;
1572
+ }
1573
+ }
1574
+ return { root, elements: elementMap };
1575
+ }
1576
+ function useBoundProp(propValue, bindingPath) {
1577
+ const { set } = useStateStore();
1578
+ const setValue = useCallback5(
1579
+ (value) => {
1580
+ if (bindingPath) set(bindingPath, value);
1581
+ },
1582
+ [bindingPath, set]
1583
+ );
1584
+ return [propValue, setValue];
1585
+ }
1586
+ function isSpecDataPart(data) {
1587
+ if (typeof data !== "object" || data === null) return false;
1588
+ const obj = data;
1589
+ switch (obj.type) {
1590
+ case "patch":
1591
+ return typeof obj.patch === "object" && obj.patch !== null;
1592
+ case "flat":
1593
+ case "nested":
1594
+ return typeof obj.spec === "object" && obj.spec !== null;
1595
+ default:
1596
+ return false;
1597
+ }
1598
+ }
1599
+ function buildSpecFromParts(parts) {
1600
+ const spec = { root: "", elements: {} };
1601
+ let hasSpec = false;
1602
+ for (const part of parts) {
1603
+ if (part.type === SPEC_DATA_PART_TYPE) {
1604
+ if (!isSpecDataPart(part.data)) continue;
1605
+ const payload = part.data;
1606
+ if (payload.type === "patch") {
1607
+ hasSpec = true;
1608
+ applySpecPatch(spec, payload.patch);
1609
+ } else if (payload.type === "flat") {
1610
+ hasSpec = true;
1611
+ Object.assign(spec, payload.spec);
1612
+ } else if (payload.type === "nested") {
1613
+ hasSpec = true;
1614
+ const flat = nestedToFlat(payload.spec);
1615
+ Object.assign(spec, flat);
1616
+ }
1617
+ }
1618
+ }
1619
+ return hasSpec ? spec : null;
1620
+ }
1621
+ function getTextFromParts(parts) {
1622
+ return parts.filter(
1623
+ (p) => p.type === "text" && typeof p.text === "string"
1624
+ ).map((p) => p.text.trim()).filter(Boolean).join("\n\n");
1625
+ }
1626
+ function useJsonRenderMessage(parts) {
1627
+ const prevPartsRef = useRef4([]);
1628
+ const prevResultRef = useRef4({
1629
+ spec: null,
1630
+ text: ""
1631
+ });
1632
+ const partsChanged = parts !== prevPartsRef.current && (parts.length !== prevPartsRef.current.length || parts[parts.length - 1] !== prevPartsRef.current[prevPartsRef.current.length - 1]);
1633
+ if (partsChanged || prevPartsRef.current.length === 0) {
1634
+ prevPartsRef.current = parts;
1635
+ prevResultRef.current = {
1636
+ spec: buildSpecFromParts(parts),
1637
+ text: getTextFromParts(parts)
1638
+ };
1639
+ }
1640
+ const { spec, text } = prevResultRef.current;
1641
+ const hasSpec = spec !== null && Object.keys(spec.elements || {}).length > 0;
1642
+ return { spec, text, hasSpec };
1643
+ }
1644
+ var chatMessageIdCounter = 0;
1645
+ function generateChatId() {
1646
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1647
+ return crypto.randomUUID();
1648
+ }
1649
+ chatMessageIdCounter += 1;
1650
+ return `msg-${Date.now()}-${chatMessageIdCounter}`;
1651
+ }
1652
+ function useChatUI({
1653
+ api,
1654
+ onComplete,
1655
+ onError
1656
+ }) {
1657
+ const [messages, setMessages] = useState3([]);
1658
+ const [isStreaming, setIsStreaming] = useState3(false);
1659
+ const [error, setError] = useState3(null);
1660
+ const abortControllerRef = useRef4(null);
1661
+ const messagesRef = useRef4(messages);
1662
+ messagesRef.current = messages;
1663
+ const onCompleteRef = useRef4(onComplete);
1664
+ onCompleteRef.current = onComplete;
1665
+ const onErrorRef = useRef4(onError);
1666
+ onErrorRef.current = onError;
1667
+ const clear = useCallback5(() => {
1668
+ setMessages([]);
1669
+ setError(null);
1670
+ }, []);
1671
+ const send = useCallback5(
1672
+ async (text) => {
1673
+ if (!text.trim()) return;
1674
+ abortControllerRef.current?.abort();
1675
+ abortControllerRef.current = new AbortController();
1676
+ const userMessage = {
1677
+ id: generateChatId(),
1678
+ role: "user",
1679
+ text: text.trim(),
1680
+ spec: null
1681
+ };
1682
+ const assistantId = generateChatId();
1683
+ const assistantMessage = {
1684
+ id: assistantId,
1685
+ role: "assistant",
1686
+ text: "",
1687
+ spec: null
1688
+ };
1689
+ setMessages((prev) => [...prev, userMessage, assistantMessage]);
1690
+ setIsStreaming(true);
1691
+ setError(null);
1692
+ const historyForApi = [
1693
+ ...messagesRef.current.map((m) => ({
1694
+ role: m.role,
1695
+ content: m.text
1696
+ })),
1697
+ { role: "user", content: text.trim() }
1698
+ ];
1699
+ let accumulatedText = "";
1700
+ let currentSpec = { root: "", elements: {} };
1701
+ let hasSpec = false;
1702
+ try {
1703
+ const response = await fetch(api, {
1704
+ method: "POST",
1705
+ headers: { "Content-Type": "application/json" },
1706
+ body: JSON.stringify({ messages: historyForApi }),
1707
+ signal: abortControllerRef.current.signal
1708
+ });
1709
+ if (!response.ok) {
1710
+ let errorMessage = `HTTP error: ${response.status}`;
1711
+ try {
1712
+ const errorData = await response.json();
1713
+ if (errorData.message) {
1714
+ errorMessage = errorData.message;
1715
+ } else if (errorData.error) {
1716
+ errorMessage = errorData.error;
1717
+ }
1718
+ } catch {
1719
+ }
1720
+ throw new Error(errorMessage);
1721
+ }
1722
+ const reader = response.body?.getReader();
1723
+ if (!reader) {
1724
+ throw new Error("No response body");
1725
+ }
1726
+ const decoder = new TextDecoder();
1727
+ const parser = createMixedStreamParser({
1728
+ onPatch(patch) {
1729
+ hasSpec = true;
1730
+ applySpecPatch(currentSpec, patch);
1731
+ setMessages(
1732
+ (prev) => prev.map(
1733
+ (m) => m.id === assistantId ? {
1734
+ ...m,
1735
+ spec: {
1736
+ root: currentSpec.root,
1737
+ elements: { ...currentSpec.elements },
1738
+ ...currentSpec.state ? { state: { ...currentSpec.state } } : {}
1739
+ }
1740
+ } : m
1741
+ )
1742
+ );
1743
+ },
1744
+ onText(line) {
1745
+ accumulatedText += (accumulatedText ? "\n" : "") + line;
1746
+ setMessages(
1747
+ (prev) => prev.map(
1748
+ (m) => m.id === assistantId ? { ...m, text: accumulatedText } : m
1749
+ )
1750
+ );
1751
+ }
1752
+ });
1753
+ while (true) {
1754
+ const { done, value } = await reader.read();
1755
+ if (done) break;
1756
+ parser.push(decoder.decode(value, { stream: true }));
1757
+ }
1758
+ parser.flush();
1759
+ const finalMessage = {
1760
+ id: assistantId,
1761
+ role: "assistant",
1762
+ text: accumulatedText,
1763
+ spec: hasSpec ? {
1764
+ root: currentSpec.root,
1765
+ elements: { ...currentSpec.elements },
1766
+ ...currentSpec.state ? { state: { ...currentSpec.state } } : {}
1767
+ } : null
1768
+ };
1769
+ onCompleteRef.current?.(finalMessage);
1770
+ } catch (err) {
1771
+ if (err.name === "AbortError") {
1772
+ return;
1773
+ }
1774
+ const resolvedError = err instanceof Error ? err : new Error(String(err));
1775
+ setError(resolvedError);
1776
+ setMessages(
1777
+ (prev) => prev.filter((m) => m.id !== assistantId || m.text.length > 0)
1778
+ );
1779
+ onErrorRef.current?.(resolvedError);
1780
+ } finally {
1781
+ setIsStreaming(false);
1782
+ }
1783
+ },
1784
+ [api]
1785
+ );
1786
+ useEffect3(() => {
1787
+ return () => {
1788
+ abortControllerRef.current?.abort();
1789
+ };
1790
+ }, []);
1791
+ return {
1792
+ messages,
1793
+ isStreaming,
1794
+ error,
1795
+ send,
1796
+ clear
1797
+ };
1798
+ }
1799
+ export {
1800
+ ActionProvider,
1801
+ ConfirmDialog,
1802
+ JSONUIProvider,
1803
+ Renderer,
1804
+ RepeatScopeProvider,
1805
+ StateProvider,
1806
+ ValidationProvider,
1807
+ VisibilityProvider,
1808
+ buildSpecFromParts,
1809
+ createRenderer,
1810
+ createStateStore2 as createStateStore,
1811
+ defineRegistry,
1812
+ elementTreeSchema,
1813
+ flatToTree,
1814
+ getTextFromParts,
1815
+ schema,
1816
+ useAction,
1817
+ useActions,
1818
+ useBoundProp,
1819
+ useChatUI,
1820
+ useFieldValidation,
1821
+ useIsVisible,
1822
+ useJsonRenderMessage,
1823
+ useOptionalValidation,
1824
+ useRepeatScope,
1825
+ useStateBinding,
1826
+ useStateStore,
1827
+ useStateValue,
1828
+ useUIStream,
1829
+ useValidation,
1830
+ useVisibility
1831
+ };
1832
+ //# sourceMappingURL=index.mjs.map