@xmachines/json-render-core 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/LICENSE +201 -0
- package/README.md +633 -0
- package/dist/chunk-AFLK3Q4T.mjs +718 -0
- package/dist/chunk-AFLK3Q4T.mjs.map +1 -0
- package/dist/index.d.mts +893 -0
- package/dist/index.d.ts +893 -0
- package/dist/index.js +3056 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2357 -0
- package/dist/index.mjs.map +1 -0
- package/dist/store-utils-D98Czbil.d.mts +823 -0
- package/dist/store-utils-D98Czbil.d.ts +823 -0
- package/dist/store-utils.d.mts +2 -0
- package/dist/store-utils.d.ts +2 -0
- package/dist/store-utils.js +176 -0
- package/dist/store-utils.js.map +1 -0
- package/dist/store-utils.mjs +11 -0
- package/dist/store-utils.mjs.map +1 -0
- package/package.json +63 -0
package/README.md
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
# @xmachines/json-render-core
|
|
2
|
+
|
|
3
|
+
Core library for json-render. Define schemas, create catalogs, generate AI prompts, and stream specs.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @xmachines/json-render-core zod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Key Concepts
|
|
12
|
+
|
|
13
|
+
- **Schema**: Defines the structure of specs and catalogs
|
|
14
|
+
- **Catalog**: Maps component/action names to their definitions with Zod props
|
|
15
|
+
- **Spec**: JSON output from AI that conforms to the schema
|
|
16
|
+
- **SpecStream**: JSONL streaming format for progressive spec building
|
|
17
|
+
|
|
18
|
+
## Quick Start
|
|
19
|
+
|
|
20
|
+
### Define a Schema
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { defineSchema } from "@xmachines/json-render-core";
|
|
24
|
+
|
|
25
|
+
export const schema = defineSchema((s) => ({
|
|
26
|
+
spec: s.object({
|
|
27
|
+
root: s.object({
|
|
28
|
+
type: s.ref("catalog.components"),
|
|
29
|
+
props: s.propsOf("catalog.components"),
|
|
30
|
+
children: s.array(s.string()), // Element keys (flat spec format)
|
|
31
|
+
}),
|
|
32
|
+
}),
|
|
33
|
+
catalog: s.object({
|
|
34
|
+
components: s.map({
|
|
35
|
+
props: s.zod(),
|
|
36
|
+
description: s.string(),
|
|
37
|
+
}),
|
|
38
|
+
actions: s.map({
|
|
39
|
+
description: s.string(),
|
|
40
|
+
}),
|
|
41
|
+
}),
|
|
42
|
+
}), {
|
|
43
|
+
promptTemplate: myPromptTemplate, // Optional custom AI prompt generator
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Create a Catalog
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
import { defineCatalog } from "@xmachines/json-render-core";
|
|
51
|
+
import { schema } from "./schema";
|
|
52
|
+
import { z } from "zod";
|
|
53
|
+
|
|
54
|
+
export const catalog = defineCatalog(schema, {
|
|
55
|
+
components: {
|
|
56
|
+
Card: {
|
|
57
|
+
props: z.object({
|
|
58
|
+
title: z.string(),
|
|
59
|
+
subtitle: z.string().nullable(),
|
|
60
|
+
}),
|
|
61
|
+
description: "A card container with title",
|
|
62
|
+
},
|
|
63
|
+
Button: {
|
|
64
|
+
props: z.object({
|
|
65
|
+
label: z.string(),
|
|
66
|
+
variant: z.enum(["primary", "secondary"]).nullable(),
|
|
67
|
+
}),
|
|
68
|
+
description: "A clickable button",
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
actions: {
|
|
72
|
+
submit: { description: "Submit the form" },
|
|
73
|
+
cancel: { description: "Cancel and close" },
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Generate AI Prompts
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
// Generate system prompt for AI
|
|
82
|
+
const systemPrompt = catalog.prompt();
|
|
83
|
+
|
|
84
|
+
// With custom rules
|
|
85
|
+
const systemPrompt = catalog.prompt({
|
|
86
|
+
system: "You are a dashboard builder.",
|
|
87
|
+
customRules: [
|
|
88
|
+
"Always include a header",
|
|
89
|
+
"Use Card components for grouping",
|
|
90
|
+
],
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Stream AI Responses (SpecStream)
|
|
95
|
+
|
|
96
|
+
The SpecStream format uses JSONL patches to progressively build specs:
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { createSpecStreamCompiler } from "@xmachines/json-render-core";
|
|
100
|
+
|
|
101
|
+
// Create a compiler for your spec type
|
|
102
|
+
const compiler = createSpecStreamCompiler<MySpec>();
|
|
103
|
+
|
|
104
|
+
// Process streaming chunks from AI
|
|
105
|
+
while (streaming) {
|
|
106
|
+
const chunk = await reader.read();
|
|
107
|
+
const { result, newPatches } = compiler.push(chunk);
|
|
108
|
+
|
|
109
|
+
if (newPatches.length > 0) {
|
|
110
|
+
// Update UI with partial result
|
|
111
|
+
setSpec(result);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Get final compiled result
|
|
116
|
+
const finalSpec = compiler.getResult();
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
SpecStream format uses [RFC 6902 JSON Patch](https://datatracker.ietf.org/doc/html/rfc6902) operations (each line is a patch):
|
|
120
|
+
|
|
121
|
+
```jsonl
|
|
122
|
+
{"op":"add","path":"/root","value":"card-1"}
|
|
123
|
+
{"op":"add","path":"/elements/card-1","value":{"type":"Card","props":{"title":"Hello"},"children":["btn-1"]}}
|
|
124
|
+
{"op":"add","path":"/elements/btn-1","value":{"type":"Button","props":{"label":"Click"},"children":[]}}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
All six RFC 6902 operations are supported: `add`, `remove`, `replace`, `move`, `copy`, `test`.
|
|
128
|
+
|
|
129
|
+
### Low-Level Utilities
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import {
|
|
133
|
+
parseSpecStreamLine,
|
|
134
|
+
applySpecStreamPatch,
|
|
135
|
+
compileSpecStream,
|
|
136
|
+
} from "@xmachines/json-render-core";
|
|
137
|
+
|
|
138
|
+
// Parse a single line
|
|
139
|
+
const patch = parseSpecStreamLine('{"op":"add","path":"/root","value":{}}');
|
|
140
|
+
// { op: "add", path: "/root", value: {} }
|
|
141
|
+
|
|
142
|
+
// Apply a patch to an object
|
|
143
|
+
const obj = {};
|
|
144
|
+
applySpecStreamPatch(obj, patch);
|
|
145
|
+
// obj is now { root: {} }
|
|
146
|
+
|
|
147
|
+
// Compile entire JSONL string at once
|
|
148
|
+
const spec = compileSpecStream<MySpec>(jsonlString);
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## API Reference
|
|
152
|
+
|
|
153
|
+
### Schema
|
|
154
|
+
|
|
155
|
+
| Export | Purpose |
|
|
156
|
+
|--------|---------|
|
|
157
|
+
| `defineSchema(builder, options?)` | Create a schema with spec/catalog structure |
|
|
158
|
+
| `SchemaBuilder` | Builder with `s.object()`, `s.array()`, `s.map()`, etc. |
|
|
159
|
+
|
|
160
|
+
Schema options:
|
|
161
|
+
|
|
162
|
+
| Option | Purpose |
|
|
163
|
+
|--------|---------|
|
|
164
|
+
| `promptTemplate` | Custom AI prompt generator |
|
|
165
|
+
| `defaultRules` | Default rules injected before custom rules in prompts |
|
|
166
|
+
| `builtInActions` | Actions always available at runtime, auto-injected into prompts (e.g. `setState`) |
|
|
167
|
+
|
|
168
|
+
### Catalog
|
|
169
|
+
|
|
170
|
+
| Export | Purpose |
|
|
171
|
+
|--------|---------|
|
|
172
|
+
| `defineCatalog(schema, data)` | Create a type-safe catalog from schema |
|
|
173
|
+
| `catalog.prompt(options?)` | Generate AI system prompt |
|
|
174
|
+
|
|
175
|
+
### SpecStream
|
|
176
|
+
|
|
177
|
+
| Export | Purpose |
|
|
178
|
+
|--------|---------|
|
|
179
|
+
| `createSpecStreamCompiler<T>()` | Create streaming compiler |
|
|
180
|
+
| `parseSpecStreamLine(line)` | Parse single JSONL line |
|
|
181
|
+
| `applySpecStreamPatch(obj, patch)` | Apply patch to object |
|
|
182
|
+
| `compileSpecStream<T>(jsonl)` | Compile entire JSONL string |
|
|
183
|
+
|
|
184
|
+
### Dynamic Props
|
|
185
|
+
|
|
186
|
+
| Export | Purpose |
|
|
187
|
+
|--------|---------|
|
|
188
|
+
| `resolvePropValue(value, ctx)` | Resolve a single prop expression |
|
|
189
|
+
| `resolveElementProps(props, ctx)` | Resolve all prop expressions in an element |
|
|
190
|
+
| `PropExpression<T>` | Type for prop values that may contain expressions |
|
|
191
|
+
| `ComputedFunction` | Function signature for `$computed` expressions |
|
|
192
|
+
| `PropResolutionContext` | Context for resolving props (includes `functions` for `$computed`) |
|
|
193
|
+
|
|
194
|
+
### Validation
|
|
195
|
+
|
|
196
|
+
| Export | Purpose |
|
|
197
|
+
|--------|---------|
|
|
198
|
+
| `check.required()` | Required validation helper |
|
|
199
|
+
| `check.email()` | Email validation helper |
|
|
200
|
+
| `check.matches(path)` | Cross-field match helper |
|
|
201
|
+
| `check.equalTo(path)` | Cross-field equality helper |
|
|
202
|
+
| `check.lessThan(path)` | Cross-field less-than helper |
|
|
203
|
+
| `check.greaterThan(path)` | Cross-field greater-than helper |
|
|
204
|
+
| `check.requiredIf(path)` | Conditional required helper |
|
|
205
|
+
| `builtInValidationFunctions` | All built-in validation functions |
|
|
206
|
+
| `runValidationCheck()` | Run a single validation check |
|
|
207
|
+
|
|
208
|
+
### User Prompt
|
|
209
|
+
|
|
210
|
+
| Export | Purpose |
|
|
211
|
+
|--------|---------|
|
|
212
|
+
| `buildUserPrompt(options)` | Build a user prompt with optional spec refinement and state context |
|
|
213
|
+
| `buildEditUserPrompt(options)` | Build a user prompt for editing an existing spec (used internally by `buildUserPrompt`) |
|
|
214
|
+
| `buildEditInstructions(config, format)` | Generate the prompt section describing available edit modes |
|
|
215
|
+
| `isNonEmptySpec(spec)` | Check whether a spec has a root and at least one element |
|
|
216
|
+
| `UserPromptOptions` | Options type for `buildUserPrompt` |
|
|
217
|
+
| `EditMode` | `"patch" \| "merge" \| "diff"` |
|
|
218
|
+
| `EditConfig` | Configuration for edit modes (`{ modes: EditMode[] }`) |
|
|
219
|
+
| `BuildEditUserPromptOptions` | Options type for `buildEditUserPrompt` |
|
|
220
|
+
|
|
221
|
+
### Merge and Diff
|
|
222
|
+
|
|
223
|
+
| Export | Purpose |
|
|
224
|
+
|--------|---------|
|
|
225
|
+
| `deepMergeSpec(base, patch)` | RFC 7396 deep merge (null deletes, arrays replace, objects recurse) |
|
|
226
|
+
| `diffToPatches(oldObj, newObj)` | Generate RFC 6902 JSON Patch operations from object diff |
|
|
227
|
+
|
|
228
|
+
### Spec Validation
|
|
229
|
+
|
|
230
|
+
| Export | Purpose |
|
|
231
|
+
|--------|---------|
|
|
232
|
+
| `validateSpec(spec, options?)` | Validate spec structure and return issues |
|
|
233
|
+
| `autoFixSpec(spec)` | Auto-fix common spec issues (returns corrected copy) |
|
|
234
|
+
| `formatSpecIssues(issues)` | Format validation issues as readable strings |
|
|
235
|
+
|
|
236
|
+
### Actions
|
|
237
|
+
|
|
238
|
+
| Export | Purpose |
|
|
239
|
+
|--------|---------|
|
|
240
|
+
| `ActionBinding` | Action binding with `action`, `params`, `confirm`, `preventDefault`, etc. |
|
|
241
|
+
| `BuiltInAction` | Built-in action definition with `name` and `description` |
|
|
242
|
+
|
|
243
|
+
### Inline Mode (Mixed Streams)
|
|
244
|
+
|
|
245
|
+
| Export | Purpose |
|
|
246
|
+
|--------|---------|
|
|
247
|
+
| `createJsonRenderTransform()` | TransformStream that separates text from JSONL patches in a mixed stream |
|
|
248
|
+
| `pipeJsonRender()` | Server-side helper to pipe a mixed stream through the transform |
|
|
249
|
+
| `SPEC_DATA_PART` / `SPEC_DATA_PART_TYPE` | Constants for filtering spec data parts |
|
|
250
|
+
|
|
251
|
+
The transform splits text blocks around spec data by emitting `text-end`/`text-start` pairs, ensuring the AI SDK creates separate text parts and preserving correct interleaving of prose and UI in `message.parts`.
|
|
252
|
+
|
|
253
|
+
### State Store
|
|
254
|
+
|
|
255
|
+
| Export | Purpose |
|
|
256
|
+
|--------|---------|
|
|
257
|
+
| `createStateStore(initialState?)` | Create a framework-agnostic in-memory `StateStore` |
|
|
258
|
+
| `StateStore` | Interface for plugging in external state management (Redux, Zustand, XState, etc.) |
|
|
259
|
+
| `StateModel` | State model type (`Record<string, unknown>`) |
|
|
260
|
+
|
|
261
|
+
The `StateStore` interface allows renderers to use external state management instead of the built-in internal store:
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
import { createStateStore, type StateStore } from "@xmachines/json-render-core";
|
|
265
|
+
|
|
266
|
+
// Simple in-memory store
|
|
267
|
+
const store = createStateStore({ count: 0 });
|
|
268
|
+
|
|
269
|
+
store.get("/count"); // 0
|
|
270
|
+
store.set("/count", 1); // updates and notifies subscribers
|
|
271
|
+
store.getSnapshot(); // { count: 1 }
|
|
272
|
+
|
|
273
|
+
// Subscribe to changes (compatible with React's useSyncExternalStore)
|
|
274
|
+
const unsubscribe = store.subscribe(() => {
|
|
275
|
+
console.log("state changed:", store.getSnapshot());
|
|
276
|
+
});
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
Pass the store to `StateProvider` in any renderer package (`@xmachines/json-render-react`, `@xmachines/json-render-react-native`, `@xmachines/json-render-react-pdf`) for controlled mode.
|
|
280
|
+
|
|
281
|
+
### Store Utilities (for adapter authors)
|
|
282
|
+
|
|
283
|
+
Available via `@xmachines/json-render-core/store-utils`:
|
|
284
|
+
|
|
285
|
+
| Export | Purpose |
|
|
286
|
+
|--------|---------|
|
|
287
|
+
| `createStoreAdapter(config)` | Build a full `StateStore` from a minimal `{ getSnapshot, setSnapshot, subscribe }` config |
|
|
288
|
+
| `immutableSetByPath(root, path, value)` | Immutably set a value at a JSON Pointer path with structural sharing |
|
|
289
|
+
| `flattenToPointers(obj)` | Flatten a nested object into JSON Pointer keyed entries |
|
|
290
|
+
| `StoreAdapterConfig` | Config type for `createStoreAdapter` |
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
import { createStoreAdapter, immutableSetByPath, flattenToPointers } from "@xmachines/json-render-core/store-utils";
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
`createStoreAdapter` handles `get`, `set` (with no-op detection), batched `update`, `getSnapshot`, `getServerSnapshot`, and `subscribe` -- adapter authors only need to supply the snapshot source, write API, and subscribe mechanism:
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
import { createStoreAdapter } from "@xmachines/json-render-core/store-utils";
|
|
300
|
+
|
|
301
|
+
const store = createStoreAdapter({
|
|
302
|
+
getSnapshot: () => myLib.getState(),
|
|
303
|
+
setSnapshot: (next) => myLib.setState(next),
|
|
304
|
+
subscribe: (listener) => myLib.subscribe(listener),
|
|
305
|
+
});
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
The official adapter packages (`@xmachines/json-render-redux`, `@xmachines/json-render-zustand`, `@xmachines/json-render-jotai`) are all built on top of `createStoreAdapter`.
|
|
309
|
+
|
|
310
|
+
### Types
|
|
311
|
+
|
|
312
|
+
| Export | Purpose |
|
|
313
|
+
|--------|---------|
|
|
314
|
+
| `Spec` | Base spec type |
|
|
315
|
+
| `Catalog` | Catalog type |
|
|
316
|
+
| `BuiltInAction` | Built-in action type (`name` + `description`) |
|
|
317
|
+
| `ComputedFunction` | Function signature for `$computed` expressions |
|
|
318
|
+
| `VisibilityCondition` | Visibility condition type (used by `$cond`) |
|
|
319
|
+
| `VisibilityContext` | Context for evaluating visibility and prop expressions |
|
|
320
|
+
| `SpecStreamLine` | Single patch operation |
|
|
321
|
+
| `SpecStreamCompiler` | Streaming compiler interface |
|
|
322
|
+
|
|
323
|
+
## Dynamic Prop Expressions
|
|
324
|
+
|
|
325
|
+
Any prop value can be a dynamic expression that resolves based on data state at render time. Expressions are resolved by the renderer before props reach components.
|
|
326
|
+
|
|
327
|
+
### Data Binding (`$state`)
|
|
328
|
+
|
|
329
|
+
Read a value directly from the state model:
|
|
330
|
+
|
|
331
|
+
```json
|
|
332
|
+
{
|
|
333
|
+
"color": { "$state": "/theme/primary" },
|
|
334
|
+
"label": { "$state": "/user/name" }
|
|
335
|
+
}
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
### Two-Way Binding (`$bindState` / `$bindItem`)
|
|
339
|
+
|
|
340
|
+
Use `{ "$bindState": "/path" }` on the natural value prop for form components that need read/write access. The component reads from and writes to the state path:
|
|
341
|
+
|
|
342
|
+
```json
|
|
343
|
+
{
|
|
344
|
+
"type": "Input",
|
|
345
|
+
"props": {
|
|
346
|
+
"value": { "$bindState": "/form/email" },
|
|
347
|
+
"placeholder": "Email"
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
Inside a repeat scope, use `{ "$bindItem": "completed" }` to bind to a field on the current item:
|
|
353
|
+
|
|
354
|
+
### Conditional (`$cond` / `$then` / `$else`)
|
|
355
|
+
|
|
356
|
+
Evaluate a condition (same syntax as visibility conditions) and pick a value:
|
|
357
|
+
|
|
358
|
+
```json
|
|
359
|
+
{
|
|
360
|
+
"color": {
|
|
361
|
+
"$cond": { "$state": "/activeTab", "eq": "home" },
|
|
362
|
+
"$then": "#007AFF",
|
|
363
|
+
"$else": "#8E8E93"
|
|
364
|
+
},
|
|
365
|
+
"name": {
|
|
366
|
+
"$cond": { "$state": "/activeTab", "eq": "home" },
|
|
367
|
+
"$then": "home",
|
|
368
|
+
"$else": "home-outline"
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
`$then` and `$else` can themselves be expressions (recursive):
|
|
374
|
+
|
|
375
|
+
```json
|
|
376
|
+
{
|
|
377
|
+
"label": {
|
|
378
|
+
"$cond": { "$state": "/user/isAdmin" },
|
|
379
|
+
"$then": { "$state": "/admin/greeting" },
|
|
380
|
+
"$else": "Welcome"
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
### Repeat Item (`$item`)
|
|
386
|
+
|
|
387
|
+
Inside children of a repeated element, read a field from the current array item:
|
|
388
|
+
|
|
389
|
+
```json
|
|
390
|
+
{ "$item": "title" }
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Use `""` to get the entire item object. `$item` takes a path string because items are typically objects with nested fields to navigate.
|
|
394
|
+
|
|
395
|
+
### Repeat Index (`$index`)
|
|
396
|
+
|
|
397
|
+
Get the current array index inside a repeat:
|
|
398
|
+
|
|
399
|
+
```json
|
|
400
|
+
{ "$index": true }
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
`$index` uses `true` as a sentinel flag because the index is a scalar value with no sub-path to navigate (unlike `$item` which needs a path).
|
|
404
|
+
|
|
405
|
+
### Template (`$template`)
|
|
406
|
+
|
|
407
|
+
Interpolate state values into strings using `${/path}` syntax:
|
|
408
|
+
|
|
409
|
+
```json
|
|
410
|
+
{
|
|
411
|
+
"label": { "$template": "Hello, ${/user/name}! You have ${/inbox/count} messages." }
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
Missing paths resolve to an empty string.
|
|
416
|
+
|
|
417
|
+
### Computed (`$computed`)
|
|
418
|
+
|
|
419
|
+
Call a registered function with resolved arguments:
|
|
420
|
+
|
|
421
|
+
```json
|
|
422
|
+
{
|
|
423
|
+
"text": {
|
|
424
|
+
"$computed": "fullName",
|
|
425
|
+
"args": {
|
|
426
|
+
"first": { "$state": "/form/firstName" },
|
|
427
|
+
"last": { "$state": "/form/lastName" }
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
Functions are registered in the catalog and provided at runtime via the `functions` prop on the renderer.
|
|
434
|
+
|
|
435
|
+
```typescript
|
|
436
|
+
import type { ComputedFunction } from "@xmachines/json-render-core";
|
|
437
|
+
|
|
438
|
+
const functions: Record<string, ComputedFunction> = {
|
|
439
|
+
fullName: (args) => `${args.first} ${args.last}`,
|
|
440
|
+
};
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
### API
|
|
444
|
+
|
|
445
|
+
```typescript
|
|
446
|
+
import { resolvePropValue, resolveElementProps } from "@xmachines/json-render-core";
|
|
447
|
+
|
|
448
|
+
// Resolve a single value
|
|
449
|
+
const color = resolvePropValue(
|
|
450
|
+
{ $cond: { $state: "/active", eq: "yes" }, $then: "blue", $else: "gray" },
|
|
451
|
+
{ stateModel: myState }
|
|
452
|
+
);
|
|
453
|
+
|
|
454
|
+
// Resolve all props on an element
|
|
455
|
+
const resolved = resolveElementProps(element.props, { stateModel: myState });
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
## Visibility Conditions
|
|
459
|
+
|
|
460
|
+
Visibility conditions control when elements are shown. `VisibilityContext` is `{ stateModel: StateModel, repeatItem?: unknown, repeatIndex?: number }`.
|
|
461
|
+
|
|
462
|
+
### Syntax
|
|
463
|
+
|
|
464
|
+
```typescript
|
|
465
|
+
{ "$state": "/path" } // truthiness
|
|
466
|
+
{ "$state": "/path", "not": true } // falsy
|
|
467
|
+
{ "$state": "/path", "eq": value } // equality
|
|
468
|
+
{ "$state": "/path", "neq": value } // inequality
|
|
469
|
+
{ "$state": "/path", "gt": number } // greater than
|
|
470
|
+
{ "$item": "field" } // repeat item field
|
|
471
|
+
{ "$index": true, "gt": 0 } // repeat index
|
|
472
|
+
[ condition, condition ] // implicit AND
|
|
473
|
+
{ "$and": [ condition, condition ] } // explicit AND
|
|
474
|
+
{ "$or": [ condition, condition ] } // OR
|
|
475
|
+
true / false // always / never
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
### TypeScript Helpers
|
|
479
|
+
|
|
480
|
+
```typescript
|
|
481
|
+
import { visibility } from "@xmachines/json-render-core";
|
|
482
|
+
|
|
483
|
+
visibility.always // true
|
|
484
|
+
visibility.never // false
|
|
485
|
+
visibility.when("/path") // { $state: "/path" }
|
|
486
|
+
visibility.unless("/path") // { $state: "/path", not: true }
|
|
487
|
+
visibility.eq("/path", val) // { $state: "/path", eq: val }
|
|
488
|
+
visibility.neq("/path", val) // { $state: "/path", neq: val }
|
|
489
|
+
visibility.gt("/path", n) // { $state: "/path", gt: n }
|
|
490
|
+
visibility.gte("/path", n) // { $state: "/path", gte: n }
|
|
491
|
+
visibility.lt("/path", n) // { $state: "/path", lt: n }
|
|
492
|
+
visibility.lte("/path", n) // { $state: "/path", lte: n }
|
|
493
|
+
visibility.and(cond1, cond2) // { $and: [cond1, cond2] }
|
|
494
|
+
visibility.or(cond1, cond2) // { $or: [cond1, cond2] }
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
## User Prompt Builder
|
|
498
|
+
|
|
499
|
+
Build structured user prompts for AI generation, with support for refinement and state context:
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
import { buildUserPrompt } from "@xmachines/json-render-core";
|
|
503
|
+
|
|
504
|
+
// Fresh generation
|
|
505
|
+
const prompt = buildUserPrompt({ prompt: "create a todo app" });
|
|
506
|
+
|
|
507
|
+
// Refinement with edit modes (default: patch-only)
|
|
508
|
+
const refinementPrompt = buildUserPrompt({
|
|
509
|
+
prompt: "add a dark mode toggle",
|
|
510
|
+
currentSpec: existingSpec,
|
|
511
|
+
editModes: ["patch", "merge"],
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
// With runtime state context
|
|
515
|
+
const contextPrompt = buildUserPrompt({
|
|
516
|
+
prompt: "show my data",
|
|
517
|
+
state: { todos: [{ text: "Buy milk" }] },
|
|
518
|
+
});
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
When `currentSpec` is provided, the prompt instructs the AI to use the specified edit modes. Available modes:
|
|
522
|
+
|
|
523
|
+
- **`"patch"`** — RFC 6902 JSON Patch. One operation per line. Best for precise, targeted single-field updates.
|
|
524
|
+
- **`"merge"`** — RFC 7396 JSON Merge Patch. Partial object deep-merged; `null` deletes. Best for structural changes.
|
|
525
|
+
- **`"diff"`** — Unified diff against the serialized spec. Best for small text-level changes.
|
|
526
|
+
|
|
527
|
+
## Deep Merge and Diff
|
|
528
|
+
|
|
529
|
+
Format-agnostic utilities for working with specs:
|
|
530
|
+
|
|
531
|
+
```typescript
|
|
532
|
+
import { deepMergeSpec, diffToPatches } from "@xmachines/json-render-core";
|
|
533
|
+
|
|
534
|
+
// RFC 7396 deep merge: null deletes, arrays replace, objects recurse
|
|
535
|
+
const merged = deepMergeSpec(baseSpec, { elements: { main: { props: { title: "New" } } } });
|
|
536
|
+
|
|
537
|
+
// RFC 6902 diff: generate JSON Patch operations from two objects
|
|
538
|
+
const patches = diffToPatches(oldSpec, newSpec);
|
|
539
|
+
// [{ op: "replace", path: "/elements/main/props/title", value: "New" }]
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
## Spec Validation
|
|
543
|
+
|
|
544
|
+
Validate spec structure and auto-fix common issues:
|
|
545
|
+
|
|
546
|
+
```typescript
|
|
547
|
+
import { validateSpec, autoFixSpec, formatSpecIssues } from "@xmachines/json-render-core";
|
|
548
|
+
|
|
549
|
+
// Validate a spec
|
|
550
|
+
const { valid, issues } = validateSpec(spec);
|
|
551
|
+
|
|
552
|
+
// Format issues for display
|
|
553
|
+
console.log(formatSpecIssues(issues));
|
|
554
|
+
|
|
555
|
+
// Auto-fix common issues (returns a corrected copy)
|
|
556
|
+
const fixed = autoFixSpec(spec);
|
|
557
|
+
```
|
|
558
|
+
|
|
559
|
+
## State Watchers
|
|
560
|
+
|
|
561
|
+
Elements can declare a `watch` field to trigger actions when state values change. `watch` is a top-level field on the element (sibling of `type`, `props`, `children`), not inside `props`.
|
|
562
|
+
|
|
563
|
+
```json
|
|
564
|
+
{
|
|
565
|
+
"type": "Select",
|
|
566
|
+
"props": {
|
|
567
|
+
"label": "Country",
|
|
568
|
+
"value": { "$bindState": "/form/country" },
|
|
569
|
+
"options": ["US", "Canada", "UK"]
|
|
570
|
+
},
|
|
571
|
+
"watch": {
|
|
572
|
+
"/form/country": {
|
|
573
|
+
"action": "loadCities",
|
|
574
|
+
"params": { "country": { "$state": "/form/country" } }
|
|
575
|
+
}
|
|
576
|
+
},
|
|
577
|
+
"children": []
|
|
578
|
+
}
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
Watchers only fire on value changes, not on initial render. Multiple action bindings per path execute sequentially.
|
|
582
|
+
|
|
583
|
+
## Validation
|
|
584
|
+
|
|
585
|
+
### Built-in Validation Functions
|
|
586
|
+
|
|
587
|
+
| Function | Description | Args |
|
|
588
|
+
|----------|-------------|------|
|
|
589
|
+
| `required` | Value must not be empty | — |
|
|
590
|
+
| `email` | Must be a valid email | — |
|
|
591
|
+
| `url` | Must be a valid URL | — |
|
|
592
|
+
| `numeric` | Must be a number | — |
|
|
593
|
+
| `minLength` | Minimum string length | `{ min: number }` |
|
|
594
|
+
| `maxLength` | Maximum string length | `{ max: number }` |
|
|
595
|
+
| `min` | Minimum numeric value | `{ min: number }` |
|
|
596
|
+
| `max` | Maximum numeric value | `{ max: number }` |
|
|
597
|
+
| `pattern` | Must match regex | `{ pattern: string }` |
|
|
598
|
+
| `matches` | Must equal another field | `{ other: { $state: "/path" } }` |
|
|
599
|
+
| `equalTo` | Alias for matches | `{ other: { $state: "/path" } }` |
|
|
600
|
+
| `lessThan` | Must be less than another field | `{ other: { $state: "/path" } }` |
|
|
601
|
+
| `greaterThan` | Must be greater than another field | `{ other: { $state: "/path" } }` |
|
|
602
|
+
| `requiredIf` | Required when condition is truthy | `{ field: { $state: "/path" } }` |
|
|
603
|
+
|
|
604
|
+
### TypeScript Helpers
|
|
605
|
+
|
|
606
|
+
```typescript
|
|
607
|
+
import { check } from "@xmachines/json-render-core";
|
|
608
|
+
|
|
609
|
+
check.required("Field is required");
|
|
610
|
+
check.email("Invalid email");
|
|
611
|
+
check.matches("/form/password", "Passwords must match");
|
|
612
|
+
check.equalTo("/form/password", "Passwords must match");
|
|
613
|
+
check.lessThan("/form/endDate", "Must be before end date");
|
|
614
|
+
check.greaterThan("/form/startDate", "Must be after start date");
|
|
615
|
+
check.requiredIf("/form/enableNotifications", "Required when notifications enabled");
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
## Custom Schemas
|
|
619
|
+
|
|
620
|
+
json-render supports completely different spec formats for different renderers:
|
|
621
|
+
|
|
622
|
+
```typescript
|
|
623
|
+
// React: Flat element map
|
|
624
|
+
{ root: "card-1", elements: { "card-1": { type: "Card", props: {...}, children: [...] } } }
|
|
625
|
+
|
|
626
|
+
// Remotion: Timeline
|
|
627
|
+
{ composition: {...}, tracks: [...], clips: [...] }
|
|
628
|
+
|
|
629
|
+
// Your own: Whatever you need
|
|
630
|
+
{ pages: [...], navigation: {...}, theme: {...} }
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
Each renderer defines its own schema with `defineSchema()` and its own prompt template.
|