@xmachines/json-render-core 0.19.0-xm.3 → 0.20.0-xm.2

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.js CHANGED
@@ -34,6 +34,7 @@ __export(index_exports, {
34
34
  ValidationCheckSchema: () => ValidationCheckSchema,
35
35
  ValidationConfigSchema: () => ValidationConfigSchema,
36
36
  VisibilityConditionSchema: () => VisibilityConditionSchema,
37
+ VisibilityConditionStrictSchema: () => VisibilityConditionStrictSchema,
37
38
  action: () => action,
38
39
  actionBinding: () => actionBinding,
39
40
  addByPath: () => addByPath,
@@ -46,6 +47,7 @@ __export(index_exports, {
46
47
  builtInValidationFunctions: () => builtInValidationFunctions,
47
48
  check: () => check,
48
49
  compileSpecStream: () => compileSpecStream,
50
+ conditionUsesItemScope: () => conditionUsesItemScope,
49
51
  createDirectiveRegistry: () => createDirectiveRegistry,
50
52
  createJsonRenderTransform: () => createJsonRenderTransform,
51
53
  createMixedStreamParser: () => createMixedStreamParser,
@@ -80,9 +82,12 @@ __export(index_exports, {
80
82
  resolveDynamicValue: () => resolveDynamicValue,
81
83
  resolveElementProps: () => resolveElementProps,
82
84
  resolvePropValue: () => resolvePropValue,
85
+ resolveRepeatItemStatePath: () => resolveRepeatItemStatePath,
86
+ resolveRepeatStatePath: () => resolveRepeatStatePath,
83
87
  runValidation: () => runValidation,
84
88
  runValidationCheck: () => runValidationCheck,
85
89
  setByPath: () => setByPath,
90
+ splitRepeatVisibility: () => splitRepeatVisibility,
86
91
  subscribeDevtoolsActive: () => subscribeDevtoolsActive,
87
92
  validateSpec: () => validateSpec,
88
93
  visibility: () => visibility
@@ -147,6 +152,28 @@ function getByPath(obj, path) {
147
152
  }
148
153
  return current;
149
154
  }
155
+ function resolveRepeatStatePath(statePath, repeatBasePath) {
156
+ if (typeof statePath === "string") {
157
+ return statePath;
158
+ }
159
+ if (repeatBasePath == null) {
160
+ return void 0;
161
+ }
162
+ if (statePath.$item === "" || statePath.$item === "/") {
163
+ return repeatBasePath;
164
+ }
165
+ return joinStatePath(repeatBasePath, statePath.$item);
166
+ }
167
+ function resolveRepeatItemStatePath(statePath, index) {
168
+ return joinStatePath(statePath, String(index));
169
+ }
170
+ function joinStatePath(basePath, childPath) {
171
+ const child = childPath.startsWith("/") ? childPath.slice(1) : childPath;
172
+ if (basePath === "" || basePath === "/") {
173
+ return `/${child}`;
174
+ }
175
+ return `${basePath}/${child}`;
176
+ }
150
177
  function isNumericIndex(str) {
151
178
  return /^\d+$/.test(str);
152
179
  }
@@ -350,7 +377,13 @@ function nestedToFlat(nested) {
350
377
  let counter = 0;
351
378
  function walk(node) {
352
379
  const key = `el-${counter++}`;
353
- const { type, props, children: rawChildren, ...rest } = node;
380
+ const {
381
+ type,
382
+ props,
383
+ children: rawChildren,
384
+ slots: rawSlots,
385
+ ...rest
386
+ } = node;
354
387
  const childKeys = [];
355
388
  if (Array.isArray(rawChildren)) {
356
389
  for (const child of rawChildren) {
@@ -359,10 +392,20 @@ function nestedToFlat(nested) {
359
392
  }
360
393
  }
361
394
  }
395
+ const slots = {};
396
+ if (rawSlots && typeof rawSlots === "object") {
397
+ for (const [slotName, slotChildren] of Object.entries(rawSlots)) {
398
+ if (!Array.isArray(slotChildren)) continue;
399
+ slots[slotName] = slotChildren.flatMap(
400
+ (child) => child && typeof child === "object" && "type" in child ? [walk(child)] : []
401
+ );
402
+ }
403
+ }
362
404
  const element = {
363
405
  type: type ?? "unknown",
364
406
  props: props ?? {},
365
- children: childKeys
407
+ children: childKeys,
408
+ ...Object.keys(slots).length > 0 ? { slots } : {}
366
409
  };
367
410
  for (const [k, v] of Object.entries(rest)) {
368
411
  if (k !== "state" && v !== void 0) {
@@ -762,6 +805,53 @@ var VisibilityConditionSchema = import_zod2.z.lazy(
762
805
  import_zod2.z.object({ $or: import_zod2.z.array(VisibilityConditionSchema) })
763
806
  ])
764
807
  );
808
+ var StrictSingleConditionSchema = import_zod2.z.union([
809
+ import_zod2.z.strictObject({ $state: import_zod2.z.string(), ...comparisonOps }),
810
+ import_zod2.z.strictObject({ $item: import_zod2.z.string(), ...comparisonOps }),
811
+ import_zod2.z.strictObject({ $index: import_zod2.z.literal(true), ...comparisonOps })
812
+ ]);
813
+ function conditionUsesItemScope(condition) {
814
+ if (condition === void 0 || typeof condition === "boolean") return false;
815
+ if (Array.isArray(condition)) return condition.some(conditionUsesItemScope);
816
+ if (typeof condition !== "object" || condition === null) return false;
817
+ if ("$item" in condition || "$index" in condition) return true;
818
+ if ("$and" in condition)
819
+ return condition.$and.some(
820
+ conditionUsesItemScope
821
+ );
822
+ if ("$or" in condition)
823
+ return condition.$or.some(
824
+ conditionUsesItemScope
825
+ );
826
+ return false;
827
+ }
828
+ function splitRepeatVisibility(condition) {
829
+ if (condition === void 0 || !conditionUsesItemScope(condition)) {
830
+ return { container: condition, itemFilter: void 0 };
831
+ }
832
+ const partition = (parts) => {
833
+ const container = parts.filter((part) => !conditionUsesItemScope(part));
834
+ const item = parts.filter((part) => conditionUsesItemScope(part));
835
+ return {
836
+ container: container.length > 0 ? { $and: container } : void 0,
837
+ itemFilter: item.length > 0 ? { $and: item } : void 0
838
+ };
839
+ };
840
+ if (Array.isArray(condition)) return partition(condition);
841
+ if (typeof condition === "object" && condition !== null && "$and" in condition) {
842
+ return partition(condition.$and);
843
+ }
844
+ return { container: void 0, itemFilter: condition };
845
+ }
846
+ var VisibilityConditionStrictSchema = import_zod2.z.lazy(
847
+ () => import_zod2.z.union([
848
+ import_zod2.z.boolean(),
849
+ StrictSingleConditionSchema,
850
+ import_zod2.z.array(StrictSingleConditionSchema),
851
+ import_zod2.z.strictObject({ $and: import_zod2.z.array(VisibilityConditionStrictSchema) }),
852
+ import_zod2.z.strictObject({ $or: import_zod2.z.array(VisibilityConditionStrictSchema) })
853
+ ])
854
+ );
765
855
  function resolveComparisonValue(value, ctx) {
766
856
  if (typeof value === "object" && value !== null) {
767
857
  if ("$state" in value && typeof value.$state === "string") {
@@ -1171,11 +1261,17 @@ var ActionConfirmSchema = import_zod3.z.object({
1171
1261
  var ActionOnSuccessSchema = import_zod3.z.union([
1172
1262
  import_zod3.z.object({ navigate: import_zod3.z.string() }),
1173
1263
  import_zod3.z.object({ set: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()) }),
1174
- import_zod3.z.object({ action: import_zod3.z.string() })
1264
+ import_zod3.z.object({
1265
+ action: import_zod3.z.string(),
1266
+ params: import_zod3.z.record(import_zod3.z.string(), DynamicValueSchema).optional()
1267
+ })
1175
1268
  ]);
1176
1269
  var ActionOnErrorSchema = import_zod3.z.union([
1177
1270
  import_zod3.z.object({ set: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()) }),
1178
- import_zod3.z.object({ action: import_zod3.z.string() })
1271
+ import_zod3.z.object({
1272
+ action: import_zod3.z.string(),
1273
+ params: import_zod3.z.record(import_zod3.z.string(), DynamicValueSchema).optional()
1274
+ })
1179
1275
  ]);
1180
1276
  var ActionBindingSchema = import_zod3.z.object({
1181
1277
  action: import_zod3.z.string(),
@@ -1227,7 +1323,7 @@ async function executeAction(ctx) {
1227
1323
  setState(path, value);
1228
1324
  }
1229
1325
  } else if ("action" in action2.onSuccess && executeAction2) {
1230
- await executeAction2(action2.onSuccess.action);
1326
+ await executeAction2(action2.onSuccess);
1231
1327
  }
1232
1328
  }
1233
1329
  } catch (error) {
@@ -1238,7 +1334,7 @@ async function executeAction(ctx) {
1238
1334
  setState(path, resolvedValue);
1239
1335
  }
1240
1336
  } else if ("action" in action2.onError && executeAction2) {
1241
- await executeAction2(action2.onError.action);
1337
+ await executeAction2(action2.onError);
1242
1338
  }
1243
1339
  } else {
1244
1340
  throw error;
@@ -1587,6 +1683,38 @@ function validateSpec(spec, options = {}) {
1587
1683
  }
1588
1684
  }
1589
1685
  }
1686
+ if (element.slots) {
1687
+ for (const [slotName, childKeys] of Object.entries(element.slots)) {
1688
+ for (const childKey of childKeys) {
1689
+ if (!spec.elements[childKey]) {
1690
+ issues.push({
1691
+ severity: "error",
1692
+ message: `Element "${key}" references child "${childKey}" in slot "${slotName}" which does not exist in the elements map.`,
1693
+ elementKey: key,
1694
+ code: "missing_child"
1695
+ });
1696
+ }
1697
+ }
1698
+ }
1699
+ }
1700
+ if (element.repeat !== void 0) {
1701
+ if (!element.children || element.children.length === 0) {
1702
+ issues.push({
1703
+ severity: "error",
1704
+ message: `Element "${key}" has "repeat" but no children. The repeated template must be a child element: add a child that renders one item (it may read fields with {"$item": "field"}).`,
1705
+ elementKey: key,
1706
+ code: "repeat_without_children"
1707
+ });
1708
+ }
1709
+ }
1710
+ if (element.visible !== void 0 && !VisibilityConditionStrictSchema.safeParse(element.visible).success) {
1711
+ issues.push({
1712
+ severity: "error",
1713
+ message: `Element "${key}" has an invalid "visible" condition: ${JSON.stringify(element.visible)}. Valid forms: true, false, {"$state":"/path","eq":value}, {"$item":"field","eq":value}, {"$index":true,"eq":n}, an array of those (AND), or {"$and":[...]} / {"$or":[...]}. Use exactly one of $state, $item, or $index per condition object.`,
1714
+ elementKey: key,
1715
+ code: "invalid_visible"
1716
+ });
1717
+ }
1590
1718
  const props = element.props;
1591
1719
  if (props && "visible" in props && props.visible !== void 0) {
1592
1720
  issues.push({
@@ -1621,6 +1749,77 @@ function validateSpec(spec, options = {}) {
1621
1749
  });
1622
1750
  }
1623
1751
  }
1752
+ const repeatValidatedKeys = /* @__PURE__ */ new Set();
1753
+ const repeatValidatedContexts = /* @__PURE__ */ new Set();
1754
+ const validateRepeatPaths = (key, repeatBasePath, sampleAvailable, ancestors) => {
1755
+ if (ancestors.has(key)) return;
1756
+ const element = spec.elements[key];
1757
+ if (!element) return;
1758
+ repeatValidatedKeys.add(key);
1759
+ const contextKey = `${key}\0${repeatBasePath ?? ""}\0${sampleAvailable}`;
1760
+ if (repeatValidatedContexts.has(contextKey)) return;
1761
+ repeatValidatedContexts.add(contextKey);
1762
+ let childRepeatBasePath = repeatBasePath;
1763
+ let childSampleAvailable = sampleAvailable;
1764
+ if (element.repeat !== void 0) {
1765
+ const statePath = resolveRepeatStatePath(
1766
+ element.repeat.statePath,
1767
+ repeatBasePath
1768
+ );
1769
+ const displayPath = typeof element.repeat.statePath === "string" ? element.repeat.statePath : JSON.stringify(element.repeat.statePath);
1770
+ if (statePath === void 0) {
1771
+ issues.push({
1772
+ severity: "error",
1773
+ message: `Element "${key}" uses relative repeat statePath ${displayPath} outside a repeat scope.`,
1774
+ elementKey: key,
1775
+ code: "repeat_item_outside_scope"
1776
+ });
1777
+ childRepeatBasePath = void 0;
1778
+ childSampleAvailable = false;
1779
+ } else {
1780
+ const canCheckSample = spec.state !== void 0 && (typeof element.repeat.statePath === "string" || sampleAvailable);
1781
+ const value = canCheckSample ? getByPath(spec.state, statePath) : void 0;
1782
+ if (canCheckSample && !Array.isArray(value)) {
1783
+ issues.push({
1784
+ severity: "error",
1785
+ message: `Element "${key}" repeats over "${statePath}" but state${value === void 0 ? " has no value there" : ` has a ${typeof value} there`}. Repeat statePath must reference an array in state; add sample items to state at that path.`,
1786
+ elementKey: key,
1787
+ code: "repeat_state_mismatch"
1788
+ });
1789
+ }
1790
+ childRepeatBasePath = resolveRepeatItemStatePath(statePath, 0);
1791
+ childSampleAvailable = canCheckSample && Array.isArray(value) && value.length > 0;
1792
+ }
1793
+ }
1794
+ const nextAncestors = new Set(ancestors);
1795
+ nextAncestors.add(key);
1796
+ for (const childKey of element.children ?? []) {
1797
+ validateRepeatPaths(
1798
+ childKey,
1799
+ childRepeatBasePath,
1800
+ childSampleAvailable,
1801
+ nextAncestors
1802
+ );
1803
+ }
1804
+ for (const childKeys of Object.values(element.slots ?? {})) {
1805
+ for (const childKey of childKeys) {
1806
+ validateRepeatPaths(
1807
+ childKey,
1808
+ repeatBasePath,
1809
+ sampleAvailable,
1810
+ nextAncestors
1811
+ );
1812
+ }
1813
+ }
1814
+ };
1815
+ if (spec.elements[spec.root]) {
1816
+ validateRepeatPaths(spec.root, void 0, true, /* @__PURE__ */ new Set());
1817
+ }
1818
+ for (const key of Object.keys(spec.elements)) {
1819
+ if (!repeatValidatedKeys.has(key)) {
1820
+ validateRepeatPaths(key, void 0, true, /* @__PURE__ */ new Set());
1821
+ }
1822
+ }
1624
1823
  if (checkOrphans) {
1625
1824
  const reachable = /* @__PURE__ */ new Set();
1626
1825
  const walk = (key) => {
@@ -1634,6 +1833,15 @@ function validateSpec(spec, options = {}) {
1634
1833
  }
1635
1834
  }
1636
1835
  }
1836
+ if (el?.slots) {
1837
+ for (const childKeys of Object.values(el.slots)) {
1838
+ for (const childKey of childKeys) {
1839
+ if (spec.elements[childKey]) {
1840
+ walk(childKey);
1841
+ }
1842
+ }
1843
+ }
1844
+ }
1637
1845
  };
1638
1846
  if (spec.elements[spec.root]) {
1639
1847
  walk(spec.root);
@@ -1652,8 +1860,14 @@ function validateSpec(spec, options = {}) {
1652
1860
  const hasErrors = issues.some((i) => i.severity === "error");
1653
1861
  return { valid: !hasErrors, issues };
1654
1862
  }
1655
- function autoFixSpec(spec) {
1656
- const fixes = [];
1863
+ function autoFixSpec(spec, options = {}) {
1864
+ const applyLossy = options.lossy !== false;
1865
+ const fixDetails = [];
1866
+ const fixes = {
1867
+ push(message, lossy = false) {
1868
+ fixDetails.push({ message, lossy });
1869
+ }
1870
+ };
1657
1871
  const fixedElements = {};
1658
1872
  for (const [key, element] of Object.entries(spec.elements)) {
1659
1873
  const props = element.props;
@@ -1699,9 +1913,55 @@ function autoFixSpec(spec) {
1699
1913
  }
1700
1914
  fixedElements[key] = fixed;
1701
1915
  }
1916
+ if (applyLossy)
1917
+ for (const [key, element] of Object.entries(fixedElements)) {
1918
+ if (!element.children || element.children.length === 0) continue;
1919
+ const present = element.children.filter(
1920
+ (child) => child in fixedElements
1921
+ );
1922
+ if (present.length === element.children.length) continue;
1923
+ if (element.repeat !== void 0 && present.length === 0) {
1924
+ continue;
1925
+ }
1926
+ for (const child of element.children) {
1927
+ if (!(child in fixedElements)) {
1928
+ fixes.push(
1929
+ `Removed reference to undefined element "${child}" from children of "${key}".`,
1930
+ true
1931
+ );
1932
+ }
1933
+ }
1934
+ fixedElements[key] = { ...element, children: present };
1935
+ }
1936
+ if (applyLossy)
1937
+ for (const [key, element] of Object.entries(fixedElements)) {
1938
+ if (!element.slots) continue;
1939
+ let changed = false;
1940
+ const slots = Object.fromEntries(
1941
+ Object.entries(element.slots).map(([slotName, childKeys]) => {
1942
+ const present = childKeys.filter((child) => child in fixedElements);
1943
+ if (present.length !== childKeys.length) {
1944
+ changed = true;
1945
+ for (const child of childKeys) {
1946
+ if (!(child in fixedElements)) {
1947
+ fixes.push(
1948
+ `Removed reference to undefined element "${child}" from slot "${slotName}" of "${key}".`,
1949
+ true
1950
+ );
1951
+ }
1952
+ }
1953
+ }
1954
+ return [slotName, present];
1955
+ })
1956
+ );
1957
+ if (changed) {
1958
+ fixedElements[key] = { ...element, slots };
1959
+ }
1960
+ }
1702
1961
  return {
1703
1962
  spec: { root: spec.root, elements: fixedElements, state: spec.state },
1704
- fixes
1963
+ fixes: fixDetails.map((fix) => fix.message),
1964
+ fixDetails
1705
1965
  };
1706
1966
  }
1707
1967
  function formatSpecIssues(issues) {
@@ -2162,6 +2422,12 @@ function generatePrompt(catalog, options) {
2162
2422
  lines.push("Example output (each line is a separate JSON object):");
2163
2423
  lines.push("");
2164
2424
  const allComponents = catalog.data.components;
2425
+ const specDefinition = catalog.schema.definition.spec;
2426
+ const specShape = specDefinition.kind === "object" ? specDefinition.inner : void 0;
2427
+ const elementsDefinition = specShape?.elements;
2428
+ const elementDefinition = elementsDefinition?.kind === "record" ? elementsDefinition.inner : void 0;
2429
+ const elementShape = elementDefinition?.kind === "object" ? elementDefinition.inner : void 0;
2430
+ const supportsNamedSlots = elementShape?.slots !== void 0;
2165
2431
  const cn = catalog.componentNames;
2166
2432
  const comp1 = cn[0] || "Component";
2167
2433
  const comp2 = cn.length > 1 ? cn[1] : comp1;
@@ -2254,6 +2520,9 @@ Note: state patches appear right after the elements that use them, so the UI fil
2254
2520
  lines.push(
2255
2521
  'The element itself renders once (as the container), and its children are expanded once per array item. "statePath" is the state array path. "key" is an optional field name on each item for stable React keys.'
2256
2522
  );
2523
+ lines.push(
2524
+ 'For nested lists, an inner repeat can read an array from the enclosing item with { "statePath": { "$item": "field" } }. This form is valid only inside another repeat. Use an empty field to repeat over the enclosing item itself.'
2525
+ );
2257
2526
  lines.push(
2258
2527
  `Example: ${JSON.stringify({ type: comp1, props: comp1Props, repeat: { statePath: "/todos", key: "id" }, children: ["todo-item"] })}`
2259
2528
  );
@@ -2297,11 +2566,17 @@ Note: state patches appear right after the elements that use them, so the UI fil
2297
2566
  lines.push("");
2298
2567
  for (const [name, def] of Object.entries(components)) {
2299
2568
  const propsStr = def.props ? formatZodType(def.props) : "{}";
2300
- const hasChildren = def.slots && def.slots.length > 0;
2301
- const childrenStr = hasChildren ? " [accepts children]" : "";
2569
+ const slotNames = def.slots ?? [];
2570
+ const namedSlotNames = slotNames.filter((slot) => slot !== "default");
2571
+ const acceptsChildren = slotNames.includes("default");
2572
+ const slotsStr = supportsNamedSlots ? [
2573
+ acceptsChildren ? "accepts children" : "",
2574
+ namedSlotNames.length > 0 ? `slots: ${namedSlotNames.join(", ")}` : ""
2575
+ ].filter(Boolean).join("; ") : slotNames.length > 0 ? "accepts children" : "";
2576
+ const slotsSuffix = slotsStr ? ` [${slotsStr}]` : "";
2302
2577
  const eventsStr = def.events && def.events.length > 0 ? ` [events: ${def.events.join(", ")}]` : "";
2303
2578
  const descStr = def.description ? ` - ${def.description}` : "";
2304
- lines.push(`- ${name}: ${propsStr}${descStr}${childrenStr}${eventsStr}`);
2579
+ lines.push(`- ${name}: ${propsStr}${descStr}${slotsSuffix}${eventsStr}`);
2305
2580
  }
2306
2581
  lines.push("");
2307
2582
  }
@@ -3000,6 +3275,7 @@ function diffToPatches(oldObj, newObj, basePath = "") {
3000
3275
  ValidationCheckSchema,
3001
3276
  ValidationConfigSchema,
3002
3277
  VisibilityConditionSchema,
3278
+ VisibilityConditionStrictSchema,
3003
3279
  action,
3004
3280
  actionBinding,
3005
3281
  addByPath,
@@ -3012,6 +3288,7 @@ function diffToPatches(oldObj, newObj, basePath = "") {
3012
3288
  builtInValidationFunctions,
3013
3289
  check,
3014
3290
  compileSpecStream,
3291
+ conditionUsesItemScope,
3015
3292
  createDirectiveRegistry,
3016
3293
  createJsonRenderTransform,
3017
3294
  createMixedStreamParser,
@@ -3046,9 +3323,12 @@ function diffToPatches(oldObj, newObj, basePath = "") {
3046
3323
  resolveDynamicValue,
3047
3324
  resolveElementProps,
3048
3325
  resolvePropValue,
3326
+ resolveRepeatItemStatePath,
3327
+ resolveRepeatStatePath,
3049
3328
  runValidation,
3050
3329
  runValidationCheck,
3051
3330
  setByPath,
3331
+ splitRepeatVisibility,
3052
3332
  subscribeDevtoolsActive,
3053
3333
  validateSpec,
3054
3334
  visibility