@mastra/json-render 0.0.0-dashboard-view-tabs-20261123152418

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 ADDED
@@ -0,0 +1,371 @@
1
+ import { t as JSON_RENDER_STATE } from "./state-Bl6NZlzO.js";
2
+ import { SPEC_DATA_PART_TYPE, applySpecPatch, diffToPatches, formatSpecIssues, getByPath, parseSpecStreamLine, resolveElementProps, resolveRepeatItemStatePath, resolveRepeatStatePath, validateSpec } from "@json-render/core";
3
+ import { REPROCESS_PART_KEY } from "@mastra/core/processors";
4
+ // src/processor.ts
5
+ const FENCE_OPEN = "```spec";
6
+ const FENCE_CLOSE = "```";
7
+ /** Where a patch can write in a spec. Outside a ```spec block, only patches here are taken as interface edits. */
8
+ const SPEC_PATH = /^\/(root|elements|state)(\/|$)/;
9
+ /** A part that empties an interface the client has already rendered. */
10
+ const CLEARED = {
11
+ type: "flat",
12
+ spec: {
13
+ root: "",
14
+ elements: {}
15
+ }
16
+ };
17
+ /** The code block a line opens, as CommonMark reads it. */
18
+ function fenceOpenedBy(line) {
19
+ const [, marker, info] = /^(`{3,}|~{3,})(.*)$/.exec(line) ?? [];
20
+ if (!marker || marker.startsWith("`") && info.includes("`")) return;
21
+ return {
22
+ marker,
23
+ spec: info.trim().split(/\s/)[0] === "spec"
24
+ };
25
+ }
26
+ /** Whether a line closes a code block: the fence's character, at least as many times, and nothing else. */
27
+ function closes(fence, line) {
28
+ const [, marker] = /^(`+|~+)$/.exec(line) ?? [];
29
+ return !!marker && marker[0] === fence.marker[0] && marker.length >= fence.marker.length;
30
+ }
31
+ /**
32
+ * Whether a line held back may still turn out to be a code fence or a patch
33
+ * (`{"op": …}`). Lines that cannot are released as prose right away, so
34
+ * only a reply cut off inside a patch line ends with text held back.
35
+ */
36
+ function couldOpenSpecLine(line) {
37
+ if (line.startsWith("`") || line.startsWith("~")) {
38
+ const fence = line[0].repeat(3);
39
+ return fence.startsWith(line) || line.startsWith(fence);
40
+ }
41
+ return /^\{\s*("|$)/.test(line);
42
+ }
43
+ function uiStateIn(requestContext) {
44
+ return requestContext?.get(JSON_RENDER_STATE);
45
+ }
46
+ /** The spec the latest message with one builds, which a block not starting at `/root` edits. */
47
+ function latestSpec(messages) {
48
+ for (let i = messages.length - 1; i >= 0; i--) {
49
+ const spec = specOf(messages[i].content.parts ?? []);
50
+ if (spec) return spec;
51
+ }
52
+ }
53
+ /**
54
+ * Turns the ```spec blocks a model writes (json-render's text format) into
55
+ * `data-spec` parts, so the interface streams to the client and is saved with
56
+ * the message while the text keeps only the prose.
57
+ *
58
+ * A block that does not start by setting `/root` edits the latest interface in
59
+ * the thread: the reply saves that spec first, then the patches, so every
60
+ * message rebuilds its own interface and earlier ones stay as they were.
61
+ */
62
+ var JsonRenderProcessor = class {
63
+ options;
64
+ id = "json-render";
65
+ name = "json-render";
66
+ constructor(options) {
67
+ this.options = options;
68
+ }
69
+ /**
70
+ * Shows the model the latest interface it wrote, which Mastra leaves out of the
71
+ * prompt with every `data-*` part: the ```spec block goes back into the reply
72
+ * that wrote it, as the spec is now, holding the state the user set in it.
73
+ * Only this call's prompt changes, not the thread.
74
+ */
75
+ async processLLMRequest({ prompt, messageList, requestContext }) {
76
+ const messages = messageList?.get.all.db() ?? [];
77
+ const reply = messages.findLast((message) => specOf(message.content.parts ?? []));
78
+ if (!reply) return;
79
+ const spec = specOf(reply.content.parts);
80
+ const uiState = uiStateIn(requestContext);
81
+ const text = specBlock(uiState ? {
82
+ ...spec,
83
+ state: uiState
84
+ } : spec);
85
+ const written = new Set(reply.content.parts.map((part) => part.createdAt));
86
+ const wrote = (message) => !!message && message.role !== "user" && writtenAt(message).some((createdAt) => written.has(createdAt));
87
+ let at = prompt.findIndex(wrote);
88
+ if (at < 0) {
89
+ const later = messages.slice(messages.indexOf(reply) + 1).filter((message) => message.role === "user").length;
90
+ const users = prompt.flatMap((message, index) => message.role === "user" ? [index] : []);
91
+ const after = later > 0 ? users.at(-later) : void 0;
92
+ if (after === void 0) return;
93
+ return { prompt: prompt.toSpliced(after, 0, {
94
+ role: "assistant",
95
+ content: [{
96
+ type: "text",
97
+ text
98
+ }]
99
+ }) };
100
+ }
101
+ while (wrote(prompt[at + 1])) at++;
102
+ const message = prompt[at];
103
+ if (message.role === "assistant" && !message.content.some((part) => part.type === "tool-call")) {
104
+ const prose = message.content.findLast((part) => part.type === "text")?.text ?? "";
105
+ const block = {
106
+ type: "text",
107
+ text: prose && !prose.endsWith("\n") ? `\n${text}` : text
108
+ };
109
+ return { prompt: prompt.with(at, {
110
+ ...message,
111
+ content: [...message.content, block]
112
+ }) };
113
+ }
114
+ return { prompt: prompt.toSpliced(at + 1, 0, {
115
+ role: "assistant",
116
+ content: [{
117
+ type: "text",
118
+ text
119
+ }]
120
+ }) };
121
+ }
122
+ async processOutputStream({ part, state, writer, messageList, requestContext }) {
123
+ if (part.type !== "text-delta" && part.type !== "text-end") return part;
124
+ const split = state.split ??= {
125
+ line: "",
126
+ holding: false,
127
+ midLine: false,
128
+ indent: 0,
129
+ started: false
130
+ };
131
+ const live = state.live ??= { rejected: [] };
132
+ const parts = [];
133
+ let text = "";
134
+ /** `last`: the text block ended on this line, so no newline follows it. */
135
+ const endLine = (last = false) => {
136
+ const line = split.line;
137
+ const trimmed = line.trim();
138
+ split.line = "";
139
+ split.holding = false;
140
+ const keep = () => void (text += last ? line : `${line}\n`);
141
+ const fence = split.fence;
142
+ if (fence && closes(fence, trimmed)) {
143
+ split.fence = void 0;
144
+ return fence.spec ? void 0 : keep();
145
+ }
146
+ if (fence && !fence.spec) return keep();
147
+ const opened = !fence && fenceOpenedBy(trimmed);
148
+ if (opened) {
149
+ split.fence = opened;
150
+ split.started = false;
151
+ return opened.spec ? void 0 : keep();
152
+ }
153
+ const parsed = parseSpecStreamLine(trimmed);
154
+ const patch = parsed && (fence || SPEC_PATH.test(parsed.path)) ? parsed : null;
155
+ if (!patch) return void (!fence && keep());
156
+ if (!split.started) {
157
+ split.started = true;
158
+ const latest = patch.path !== "/root" && messageList && latestSpec(messageList.get.all.db());
159
+ const uiState = uiStateIn(requestContext);
160
+ const edited = latest && (uiState ? {
161
+ ...latest,
162
+ state: uiState
163
+ } : latest);
164
+ if (edited) {
165
+ live.spec = structuredClone(edited);
166
+ parts.push({
167
+ type: "flat",
168
+ spec: edited
169
+ });
170
+ }
171
+ }
172
+ try {
173
+ applyPatch(live.spec ??= {
174
+ root: "",
175
+ elements: {}
176
+ }, patch);
177
+ parts.push({
178
+ type: "patch",
179
+ patch
180
+ });
181
+ } catch (error) {
182
+ live.rejected.push(error.message);
183
+ }
184
+ };
185
+ if (part.type === "text-end") {
186
+ if (split.holding) endLine(true);
187
+ state.split = void 0;
188
+ } else for (const char of part.payload.text) {
189
+ const inSpec = !!split.fence?.spec;
190
+ if (char === "\n") {
191
+ if (split.holding) endLine();
192
+ else if (!inSpec) text += char;
193
+ split.midLine = false;
194
+ split.indent = 0;
195
+ } else if (split.holding) {
196
+ split.line += char;
197
+ if (!inSpec && !couldOpenSpecLine(split.line)) {
198
+ text += split.line;
199
+ split.line = "";
200
+ split.holding = false;
201
+ split.midLine = true;
202
+ }
203
+ } else if (inSpec || !split.midLine && split.indent < 4 && (char === "{" || char === "`" || char === "~")) {
204
+ split.holding = true;
205
+ split.line = char;
206
+ } else {
207
+ text += char;
208
+ if (!/\s/.test(char)) split.midLine = true;
209
+ else if (!split.midLine) split.indent += char === " " ? 4 : 1;
210
+ }
211
+ }
212
+ for (const data of parts) await writer?.custom({
213
+ type: SPEC_DATA_PART_TYPE,
214
+ data
215
+ });
216
+ if (part.type !== "text-end") return text ? {
217
+ ...part,
218
+ payload: {
219
+ ...part.payload,
220
+ text
221
+ }
222
+ } : null;
223
+ if (!text) return part;
224
+ state[REPROCESS_PART_KEY] = part;
225
+ return {
226
+ type: "text-delta",
227
+ runId: part.runId,
228
+ from: part.from,
229
+ payload: {
230
+ id: part.payload.id,
231
+ text
232
+ }
233
+ };
234
+ }
235
+ /** Sends a reply whose interface cannot render back to the model, with what is wrong. */
236
+ async processOutputStep({ messages, abort, state, writer }) {
237
+ const live = state.live;
238
+ const rejected = live?.rejected.splice(0) ?? [];
239
+ const reply = messages.at(-1);
240
+ if (reply?.role !== "assistant") return messages;
241
+ let problems = rejected.join("\n") || void 0;
242
+ try {
243
+ const spec = buildSpec(reply.content.parts);
244
+ problems ??= spec && problemsIn(spec, this.options.catalog);
245
+ } catch (error) {
246
+ problems ??= error.message;
247
+ }
248
+ if (problems) {
249
+ if (live?.spec) {
250
+ live.spec = void 0;
251
+ await writer?.custom({
252
+ type: SPEC_DATA_PART_TYPE,
253
+ data: CLEARED,
254
+ transient: true
255
+ });
256
+ }
257
+ abort(`The interface in your \`\`\`spec block cannot be shown. Write it again without these problems:\n${problems}`, { retry: true });
258
+ }
259
+ return messages;
260
+ }
261
+ };
262
+ /** The ```spec block json-render's prompt asks for, writing `spec` from nothing. */
263
+ function specBlock({ root, state, elements }) {
264
+ const patches = diffToPatches({ elements: {} }, {
265
+ root,
266
+ ...state && { state },
267
+ elements
268
+ });
269
+ return [
270
+ FENCE_OPEN,
271
+ ...patches.map((patch) => JSON.stringify(patch)),
272
+ FENCE_CLOSE
273
+ ].join("\n");
274
+ }
275
+ /** When the parts of a prompt message were written, as Mastra records it on each part. */
276
+ function writtenAt(message) {
277
+ if (typeof message.content === "string") return [];
278
+ return message.content.flatMap((part) => {
279
+ const at = part.providerOptions?.mastra?.createdAt;
280
+ return typeof at === "number" ? [at] : [];
281
+ });
282
+ }
283
+ /**
284
+ * The spec a message's `data-spec` parts build, the way the client renders it,
285
+ * leaving the parts as they are. Throws when a patch cannot be applied, naming it.
286
+ */
287
+ function buildSpec(parts) {
288
+ let spec;
289
+ for (const part of parts) {
290
+ if (part.type !== SPEC_DATA_PART_TYPE) continue;
291
+ const data = part.data;
292
+ if (data.type === "flat") spec = structuredClone(data.spec);
293
+ else if (data.type === "patch") applyPatch(spec ??= {
294
+ root: "",
295
+ elements: {}
296
+ }, data.patch);
297
+ }
298
+ return spec;
299
+ }
300
+ /**
301
+ * Applies a copy of `patch` to `spec`: `applySpecPatch` inserts the values a
302
+ * patch holds, so applying the patch itself would let later patches change it.
303
+ * Throws when it cannot be applied, naming it.
304
+ */
305
+ function applyPatch(spec, patch) {
306
+ try {
307
+ if (typeof patch.path !== "string") throw new Error("its path is not a string");
308
+ applySpecPatch(spec, structuredClone(patch));
309
+ } catch (error) {
310
+ throw new Error(`- ${JSON.stringify(patch)} cannot be applied: ${error.message}`);
311
+ }
312
+ }
313
+ /** The spec a message's `data-spec` parts build, or none when they cannot build one. */
314
+ function specOf(parts) {
315
+ try {
316
+ return buildSpec(parts);
317
+ } catch {
318
+ return;
319
+ }
320
+ }
321
+ /** What keeps a spec from rendering: broken structure, unknown components, or props a component does not take. */
322
+ function problemsIn(spec, catalog) {
323
+ const problems = validateSpec(spec).issues.filter((issue) => issue.severity === "error");
324
+ const lines = problems.length ? [formatSpecIssues(problems)] : [];
325
+ const components = catalog.data.components ?? {};
326
+ const stateModel = spec.state ?? {};
327
+ const seen = /* @__PURE__ */ new Set();
328
+ const report = (line) => {
329
+ if (seen.has(line)) return;
330
+ seen.add(line);
331
+ lines.push(line);
332
+ };
333
+ const visit = (key, scope, path) => {
334
+ const element = spec.elements[key];
335
+ if (!element || path.has(key)) return;
336
+ const component = components[element.type];
337
+ if (!component) report(`- "${key}" uses "${element.type}", which is not in the catalog`);
338
+ else {
339
+ const result = component.props.safeParse(resolveElementProps(element.props ?? {}, {
340
+ stateModel,
341
+ ...scope
342
+ }));
343
+ for (const issue of result.success ? [] : result.error.issues) report(`- "${key}" (${element.type}) prop "${issue.path.join(".")}": ${issue.message}`);
344
+ }
345
+ const inner = new Set(path).add(key);
346
+ const children = [...element.children ?? [], ...Object.values(element.slots ?? {}).flat()];
347
+ if (!element.repeat) return children.forEach((child) => visit(child, scope, inner));
348
+ const statePath = resolveRepeatStatePath(element.repeat.statePath, scope.repeatBasePath);
349
+ const items = statePath === void 0 ? [] : getByPath(stateModel, statePath);
350
+ if (!Array.isArray(items)) return;
351
+ const keyField = element.repeat.key;
352
+ if (keyField) {
353
+ const keys = items.map((item, index) => String(item?.[keyField] ?? index));
354
+ const repeated = keys.find((itemKey, index) => keys.indexOf(itemKey) !== index);
355
+ if (repeated !== void 0) report(`- "${key}" repeats ${statePath} keyed by "${keyField}", but "${repeated}" appears more than once; each item needs its own key`);
356
+ }
357
+ items.forEach((repeatItem, repeatIndex) => {
358
+ const itemScope = {
359
+ repeatItem,
360
+ repeatIndex,
361
+ repeatBasePath: resolveRepeatItemStatePath(statePath, repeatIndex)
362
+ };
363
+ children.forEach((child) => visit(child, itemScope, inner));
364
+ });
365
+ };
366
+ visit(spec.root, {}, /* @__PURE__ */ new Set());
367
+ return lines.length ? lines.join("\n") : void 0;
368
+ }
369
+ export { JSON_RENDER_STATE, JsonRenderProcessor };
370
+
371
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/processor.ts"],"sourcesContent":["import {\n SPEC_DATA_PART_TYPE,\n applySpecPatch,\n diffToPatches,\n formatSpecIssues,\n getByPath,\n parseSpecStreamLine,\n resolveElementProps,\n resolveRepeatItemStatePath,\n resolveRepeatStatePath,\n validateSpec,\n} from '@json-render/core';\nimport type { Catalog, PropResolutionContext, Spec, SpecDataPart } from '@json-render/core';\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { REPROCESS_PART_KEY } from '@mastra/core/processors';\nimport type {\n ProcessLLMRequestArgs,\n ProcessLLMRequestResult,\n ProcessOutputStepArgs,\n ProcessOutputStreamArgs,\n Processor,\n ProcessorContext,\n} from '@mastra/core/processors';\nimport type { ChunkType } from '@mastra/core/stream';\nimport type { z } from 'zod';\nimport { JSON_RENDER_STATE } from './state';\n\nconst FENCE_OPEN = '```spec';\nconst FENCE_CLOSE = '```';\n/** Where a patch can write in a spec. Outside a ```spec block, only patches here are taken as interface edits. */\nconst SPEC_PATH = /^\\/(root|elements|state)(\\/|$)/;\n\nexport interface JsonRenderProcessorOptions {\n /** The catalog the model composes interfaces from. */\n catalog: Catalog;\n}\n\n/** An open code block: its fence (three or more backticks or tildes), and whether it is a ```spec block. */\ninterface Fence {\n marker: string;\n spec: boolean;\n}\n\n/** Where the text stream is: lines that may be a patch or a fence are held until they end. */\ninterface Split {\n line: string;\n holding: boolean;\n /** Whether the line has prose before this point, so a fence or patch can no longer start it. */\n midLine: boolean;\n /** Columns of whitespace the line starts with: from four, Markdown reads it as indented code, not a fence or patch. */\n indent: number;\n /** The code block the stream is in: a ```spec block, or any other, whose lines stay prose. */\n fence?: Fence;\n /** Whether the open fence has had its first patch, which decides if it starts a new spec or edits the last one. */\n started: boolean;\n}\n\n/** The interface the current message has streamed so far, and the patches held back from it. */\ninterface Live {\n spec?: Spec;\n rejected: string[];\n}\n\n/** A part that empties an interface the client has already rendered. */\nconst CLEARED: SpecDataPart = { type: 'flat', spec: { root: '', elements: {} } };\n\n/** The code block a line opens, as CommonMark reads it. */\nfunction fenceOpenedBy(line: string): Fence | undefined {\n const [, marker, info] = /^(`{3,}|~{3,})(.*)$/.exec(line) ?? [];\n if (!marker || (marker.startsWith('`') && info!.includes('`'))) return;\n return { marker, spec: info!.trim().split(/\\s/)[0] === 'spec' };\n}\n\n/** Whether a line closes a code block: the fence's character, at least as many times, and nothing else. */\nfunction closes(fence: Fence, line: string) {\n const [, marker] = /^(`+|~+)$/.exec(line) ?? [];\n return !!marker && marker[0] === fence.marker[0] && marker.length >= fence.marker.length;\n}\n\n/**\n * Whether a line held back may still turn out to be a code fence or a patch\n * (`{\"op\": …}`). Lines that cannot are released as prose right away, so\n * only a reply cut off inside a patch line ends with text held back.\n */\nfunction couldOpenSpecLine(line: string) {\n if (line.startsWith('`') || line.startsWith('~')) {\n const fence = line[0]!.repeat(3);\n return fence.startsWith(line) || line.startsWith(fence);\n }\n return /^\\{\\s*(\"|$)/.test(line);\n}\n\nfunction uiStateIn(requestContext: ProcessorContext['requestContext']) {\n return requestContext?.get(JSON_RENDER_STATE) as Spec['state'];\n}\n\n/** The spec the latest message with one builds, which a block not starting at `/root` edits. */\nfunction latestSpec(messages: ReadonlyArray<MastraDBMessage>): Spec | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const spec = specOf(messages[i]!.content.parts ?? []);\n if (spec) return spec;\n }\n}\n\n/**\n * Turns the ```spec blocks a model writes (json-render's text format) into\n * `data-spec` parts, so the interface streams to the client and is saved with\n * the message while the text keeps only the prose.\n *\n * A block that does not start by setting `/root` edits the latest interface in\n * the thread: the reply saves that spec first, then the patches, so every\n * message rebuilds its own interface and earlier ones stay as they were.\n */\nexport class JsonRenderProcessor implements Processor<'json-render'> {\n readonly id = 'json-render';\n readonly name = 'json-render';\n\n constructor(readonly options: JsonRenderProcessorOptions) {}\n\n /**\n * Shows the model the latest interface it wrote, which Mastra leaves out of the\n * prompt with every `data-*` part: the ```spec block goes back into the reply\n * that wrote it, as the spec is now, holding the state the user set in it.\n * Only this call's prompt changes, not the thread.\n */\n async processLLMRequest({\n prompt,\n messageList,\n requestContext,\n }: ProcessLLMRequestArgs): Promise<ProcessLLMRequestResult> {\n const messages = messageList?.get.all.db() ?? [];\n const reply = messages.findLast(message => specOf(message.content.parts ?? []));\n if (!reply) return;\n const spec = specOf(reply.content.parts)!;\n const uiState = uiStateIn(requestContext);\n const text = specBlock(uiState ? { ...spec, state: uiState } : spec);\n\n // The prompt does not say which message each one comes from, but its parts keep the time they were written.\n // Parts can share a millisecond with the next user message, so only the model's own messages are matched.\n const written = new Set(reply.content.parts.map(part => (part as { createdAt?: number }).createdAt));\n const wrote = (message: (typeof prompt)[number] | undefined) =>\n !!message && message.role !== 'user' && writtenAt(message).some(createdAt => written.has(createdAt));\n let at = prompt.findIndex(wrote);\n if (at < 0) {\n // A reply with no text or tool calls has no message in the prompt. Memory keeps messages in the order they were\n // saved, so the block goes before the user message that followed it, counted from the end.\n const later = messages.slice(messages.indexOf(reply) + 1).filter(message => message.role === 'user').length;\n const users = prompt.flatMap((message, index) => (message.role === 'user' ? [index] : []));\n const after = later > 0 ? users.at(-later) : undefined;\n if (after === undefined) return;\n return { prompt: prompt.toSpliced(after, 0, { role: 'assistant', content: [{ type: 'text', text }] }) };\n }\n // A reply that calls tools spans several prompt messages; the block goes after its last one.\n while (wrote(prompt[at + 1])) at++;\n const message = prompt[at]!;\n if (message.role === 'assistant' && !message.content.some(part => part.type === 'tool-call')) {\n const prose = message.content.findLast(part => part.type === 'text')?.text ?? '';\n const block = { type: 'text' as const, text: prose && !prose.endsWith('\\n') ? `\\n${text}` : text };\n return { prompt: prompt.with(at, { ...message, content: [...message.content, block] }) };\n }\n return { prompt: prompt.toSpliced(at + 1, 0, { role: 'assistant', content: [{ type: 'text', text }] }) };\n }\n\n async processOutputStream({\n part,\n state,\n writer,\n messageList,\n requestContext,\n }: ProcessOutputStreamArgs): Promise<ChunkType | null> {\n if (part.type !== 'text-delta' && part.type !== 'text-end') return part;\n const split = ((state.split as Split | undefined) ??= {\n line: '',\n holding: false,\n midLine: false,\n indent: 0,\n started: false,\n });\n const live = ((state.live as Live | undefined) ??= { rejected: [] });\n const parts: SpecDataPart[] = [];\n let text = '';\n\n /** `last`: the text block ended on this line, so no newline follows it. */\n const endLine = (last = false) => {\n const line = split.line;\n const trimmed = line.trim();\n split.line = '';\n split.holding = false;\n const keep = () => void (text += last ? line : `${line}\\n`);\n const fence = split.fence;\n if (fence && closes(fence, trimmed)) {\n split.fence = undefined;\n return fence.spec ? undefined : keep();\n }\n if (fence && !fence.spec) return keep();\n const opened = !fence && fenceOpenedBy(trimmed);\n if (opened) {\n split.fence = opened;\n split.started = false;\n return opened.spec ? undefined : keep();\n }\n const parsed = parseSpecStreamLine(trimmed);\n // The edit prompt asks for the patch lines alone, so they count outside a block too, when they write to a spec.\n const patch = parsed && (fence || SPEC_PATH.test(parsed.path)) ? parsed : null;\n if (!patch) return void (!fence && keep());\n if (!split.started) {\n split.started = true;\n const latest = patch.path !== '/root' && messageList && latestSpec(messageList.get.all.db());\n const uiState = uiStateIn(requestContext);\n const edited = latest && (uiState ? { ...latest, state: uiState } : latest);\n if (edited) {\n live.spec = structuredClone(edited);\n parts.push({ type: 'flat', spec: edited });\n }\n }\n // The client applies each patch as it arrives, so one that cannot apply is held back and sent to the model instead.\n try {\n applyPatch((live.spec ??= { root: '', elements: {} }), patch);\n parts.push({ type: 'patch', patch });\n } catch (error) {\n live.rejected.push((error as Error).message);\n }\n };\n\n if (part.type === 'text-end') {\n if (split.holding) endLine(true);\n state.split = undefined;\n } else {\n for (const char of part.payload.text) {\n const inSpec = !!split.fence?.spec;\n if (char === '\\n') {\n if (split.holding) endLine();\n else if (!inSpec) text += char;\n split.midLine = false;\n split.indent = 0;\n } else if (split.holding) {\n split.line += char;\n if (!inSpec && !couldOpenSpecLine(split.line)) {\n text += split.line;\n split.line = '';\n split.holding = false;\n split.midLine = true;\n }\n } else if (inSpec || (!split.midLine && split.indent < 4 && (char === '{' || char === '`' || char === '~'))) {\n split.holding = true;\n split.line = char;\n } else {\n text += char;\n if (!/\\s/.test(char)) split.midLine = true;\n else if (!split.midLine) split.indent += char === '\\t' ? 4 : 1;\n }\n }\n }\n\n for (const data of parts) await writer?.custom({ type: SPEC_DATA_PART_TYPE, data });\n if (part.type !== 'text-end') return text ? { ...part, payload: { ...part.payload, text } } : null;\n if (!text) return part;\n // Text held to the end of the block goes out before the block closes. Only one\n // part can be returned, so the runner sends the text-end after it.\n state[REPROCESS_PART_KEY] = part;\n return { type: 'text-delta', runId: part.runId, from: part.from, payload: { id: part.payload.id, text } };\n }\n\n /** Sends a reply whose interface cannot render back to the model, with what is wrong. */\n async processOutputStep({\n messages,\n abort,\n state,\n writer,\n }: ProcessOutputStepArgs): Promise<ProcessOutputStepArgs['messages']> {\n const live = state.live as Live | undefined;\n const rejected = live?.rejected.splice(0) ?? [];\n const reply = messages.at(-1);\n if (reply?.role !== 'assistant') return messages;\n let problems = rejected.join('\\n') || undefined;\n try {\n const spec = buildSpec(reply.content.parts);\n problems ??= spec && problemsIn(spec, this.options.catalog);\n } catch (error) {\n problems ??= (error as Error).message;\n }\n if (problems) {\n // The retry writes a new message; this one stays on the client until it reloads, so its interface is cleared.\n // Transient: the rejected message is not saved, and nothing else should be.\n if (live?.spec) {\n live.spec = undefined;\n await writer?.custom({ type: SPEC_DATA_PART_TYPE, data: CLEARED, transient: true });\n }\n abort(\n `The interface in your \\`\\`\\`spec block cannot be shown. Write it again without these problems:\\n${problems}`,\n {\n retry: true,\n },\n );\n }\n return messages;\n }\n}\n\n/** The ```spec block json-render's prompt asks for, writing `spec` from nothing. */\nfunction specBlock({ root, state, elements }: Spec) {\n const patches = diffToPatches({ elements: {} }, { root, ...(state && { state }), elements });\n return [FENCE_OPEN, ...patches.map(patch => JSON.stringify(patch)), FENCE_CLOSE].join('\\n');\n}\n\n/** When the parts of a prompt message were written, as Mastra records it on each part. */\nfunction writtenAt(message: ProcessLLMRequestArgs['prompt'][number]): number[] {\n if (typeof message.content === 'string') return [];\n return message.content.flatMap(part => {\n const at = part.providerOptions?.mastra?.createdAt;\n return typeof at === 'number' ? [at] : [];\n });\n}\n\n/**\n * The spec a message's `data-spec` parts build, the way the client renders it,\n * leaving the parts as they are. Throws when a patch cannot be applied, naming it.\n */\nfunction buildSpec(parts: ReadonlyArray<{ type: string }>): Spec | undefined {\n let spec: Spec | undefined;\n for (const part of parts) {\n if (part.type !== SPEC_DATA_PART_TYPE) continue;\n const data = (part as unknown as { data: SpecDataPart }).data;\n if (data.type === 'flat') spec = structuredClone(data.spec);\n else if (data.type === 'patch') applyPatch((spec ??= { root: '', elements: {} }), data.patch);\n }\n return spec;\n}\n\n/**\n * Applies a copy of `patch` to `spec`: `applySpecPatch` inserts the values a\n * patch holds, so applying the patch itself would let later patches change it.\n * Throws when it cannot be applied, naming it.\n */\nfunction applyPatch(spec: Spec, patch: Extract<SpecDataPart, { type: 'patch' }>['patch']) {\n try {\n if (typeof patch.path !== 'string') throw new Error('its path is not a string');\n applySpecPatch(spec, structuredClone(patch));\n } catch (error) {\n throw new Error(`- ${JSON.stringify(patch)} cannot be applied: ${(error as Error).message}`);\n }\n}\n\n/** The spec a message's `data-spec` parts build, or none when they cannot build one. */\nfunction specOf(parts: ReadonlyArray<{ type: string }>): Spec | undefined {\n try {\n return buildSpec(parts);\n } catch {\n return undefined;\n }\n}\n\n/** What keeps a spec from rendering: broken structure, unknown components, or props a component does not take. */\nfunction problemsIn(spec: Spec, catalog: Catalog): string | undefined {\n const problems = validateSpec(spec).issues.filter(issue => issue.severity === 'error');\n const lines = problems.length ? [formatSpecIssues(problems)] : [];\n const components = (catalog.data as { components?: Record<string, { props: z.ZodType }> }).components ?? {};\n const stateModel = spec.state ?? {};\n const seen = new Set<string>();\n const report = (line: string) => {\n if (seen.has(line)) return;\n seen.add(line);\n lines.push(line);\n };\n\n // Walks the tree the way the renderer does, so props bound to `$item` are checked against each item they render for.\n const visit = (key: string, scope: Omit<PropResolutionContext, 'stateModel'>, path: ReadonlySet<string>) => {\n const element = spec.elements[key];\n if (!element || path.has(key)) return;\n const component = components[element.type];\n if (!component) report(`- \"${key}\" uses \"${element.type}\", which is not in the catalog`);\n else {\n const result = component.props.safeParse(resolveElementProps(element.props ?? {}, { stateModel, ...scope }));\n for (const issue of result.success ? [] : result.error.issues) {\n report(`- \"${key}\" (${element.type}) prop \"${issue.path.join('.')}\": ${issue.message}`);\n }\n }\n const inner = new Set(path).add(key);\n const children = [...(element.children ?? []), ...Object.values(element.slots ?? {}).flat()];\n if (!element.repeat) return children.forEach(child => visit(child, scope, inner));\n const statePath = resolveRepeatStatePath(element.repeat.statePath, scope.repeatBasePath);\n const items = statePath === undefined ? [] : getByPath(stateModel, statePath);\n if (!Array.isArray(items)) return;\n const keyField = element.repeat.key;\n if (keyField) {\n const keys = items.map((item, index) => String((item as Record<string, unknown> | null)?.[keyField] ?? index));\n const repeated = keys.find((itemKey, index) => keys.indexOf(itemKey) !== index);\n if (repeated !== undefined) {\n report(\n `- \"${key}\" repeats ${statePath} keyed by \"${keyField}\", but \"${repeated}\" appears more than once; each item needs its own key`,\n );\n }\n }\n items.forEach((repeatItem, repeatIndex) => {\n const itemScope = {\n repeatItem,\n repeatIndex,\n repeatBasePath: resolveRepeatItemStatePath(statePath!, repeatIndex),\n };\n children.forEach(child => visit(child, itemScope, inner));\n });\n };\n visit(spec.root, {}, new Set());\n return lines.length ? lines.join('\\n') : undefined;\n}\n"],"mappings":";;;;AA2BA,MAAM,aAAa;AACnB,MAAM,cAAc;;AAEpB,MAAM,YAAY;;AAkClB,MAAM,UAAwB;CAAE,MAAM;CAAQ,MAAM;EAAE,MAAM;EAAI,UAAU,CAAC;CAAE;AAAE;;AAG/E,SAAS,cAAc,MAAiC;CACtD,MAAM,GAAG,QAAQ,QAAQ,sBAAsB,KAAK,IAAI,KAAK,CAAC;CAC9D,IAAI,CAAC,UAAW,OAAO,WAAW,GAAG,KAAK,KAAM,SAAS,GAAG,GAAI;CAChE,OAAO;EAAE;EAAQ,MAAM,KAAM,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,OAAO;CAAO;AAChE;;AAGA,SAAS,OAAO,OAAc,MAAc;CAC1C,MAAM,GAAG,UAAU,YAAY,KAAK,IAAI,KAAK,CAAC;CAC9C,OAAO,CAAC,CAAC,UAAU,OAAO,OAAO,MAAM,OAAO,MAAM,OAAO,UAAU,MAAM,OAAO;AACpF;;;;;;AAOA,SAAS,kBAAkB,MAAc;CACvC,IAAI,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG,GAAG;EAChD,MAAM,QAAQ,KAAK,EAAE,CAAE,OAAO,CAAC;EAC/B,OAAO,MAAM,WAAW,IAAI,KAAK,KAAK,WAAW,KAAK;CACxD;CACA,OAAO,cAAc,KAAK,IAAI;AAChC;AAEA,SAAS,UAAU,gBAAoD;CACrE,OAAO,gBAAgB,IAAI,iBAAiB;AAC9C;;AAGA,SAAS,WAAW,UAA4D;CAC9E,KAAK,IAAI,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OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;EAC3F,IAAI,CAAC,QAAQ,QAAQ,OAAO,SAAS,SAAQ,UAAS,MAAM,OAAO,OAAO,KAAK,CAAC;EAChF,MAAM,YAAY,uBAAuB,QAAQ,OAAO,WAAW,MAAM,cAAc;EACvF,MAAM,QAAQ,cAAc,KAAA,IAAY,CAAC,IAAI,UAAU,YAAY,SAAS;EAC5E,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;EAC3B,MAAM,WAAW,QAAQ,OAAO;EAChC,IAAI,UAAU;GACZ,MAAM,OAAO,MAAM,KAAK,MAAM,UAAU,OAAQ,OAA0C,aAAa,KAAK,CAAC;GAC7G,MAAM,WAAW,KAAK,MAAM,SAAS,UAAU,KAAK,QAAQ,OAAO,MAAM,KAAK;GAC9E,IAAI,aAAa,KAAA,GACf,OACE,MAAM,IAAI,YAAY,UAAU,aAAa,SAAS,UAAU,SAAS,sDAC3E;EAEJ;EACA,MAAM,SAAS,YAAY,gBAAgB;GACzC,MAAM,YAAY;IAChB;IACA;IACA,gBAAgB,2BAA2B,WAAY,WAAW;GACpE;GACA,SAAS,SAAQ,UAAS,MAAM,OAAO,WAAW,KAAK,CAAC;EAC1D,CAAC;CACH;CACA,MAAM,KAAK,MAAM,CAAC,mBAAG,IAAI,IAAI,CAAC;CAC9B,OAAO,MAAM,SAAS,MAAM,KAAK,IAAI,IAAI,KAAA;AAC3C"}
@@ -0,0 +1,33 @@
1
+ import type { Catalog } from '@json-render/core';
2
+ import type { ProcessLLMRequestArgs, ProcessLLMRequestResult, ProcessOutputStepArgs, ProcessOutputStreamArgs, Processor } from '@mastra/core/processors';
3
+ import type { ChunkType } from '@mastra/core/stream';
4
+ export interface JsonRenderProcessorOptions {
5
+ /** The catalog the model composes interfaces from. */
6
+ catalog: Catalog;
7
+ }
8
+ /**
9
+ * Turns the ```spec blocks a model writes (json-render's text format) into
10
+ * `data-spec` parts, so the interface streams to the client and is saved with
11
+ * the message while the text keeps only the prose.
12
+ *
13
+ * A block that does not start by setting `/root` edits the latest interface in
14
+ * the thread: the reply saves that spec first, then the patches, so every
15
+ * message rebuilds its own interface and earlier ones stay as they were.
16
+ */
17
+ export declare class JsonRenderProcessor implements Processor<'json-render'> {
18
+ readonly options: JsonRenderProcessorOptions;
19
+ readonly id = "json-render";
20
+ readonly name = "json-render";
21
+ constructor(options: JsonRenderProcessorOptions);
22
+ /**
23
+ * Shows the model the latest interface it wrote, which Mastra leaves out of the
24
+ * prompt with every `data-*` part: the ```spec block goes back into the reply
25
+ * that wrote it, as the spec is now, holding the state the user set in it.
26
+ * Only this call's prompt changes, not the thread.
27
+ */
28
+ processLLMRequest({ prompt, messageList, requestContext, }: ProcessLLMRequestArgs): Promise<ProcessLLMRequestResult>;
29
+ processOutputStream({ part, state, writer, messageList, requestContext, }: ProcessOutputStreamArgs): Promise<ChunkType | null>;
30
+ /** Sends a reply whose interface cannot render back to the model, with what is wrong. */
31
+ processOutputStep({ messages, abort, state, writer, }: ProcessOutputStepArgs): Promise<ProcessOutputStepArgs['messages']>;
32
+ }
33
+ //# sourceMappingURL=processor.d.ts.map
@@ -0,0 +1,11 @@
1
+ // src/state.ts
2
+ /** The `requestContext` key a client sends the state its interface holds under, so the model can see it. */
3
+ const JSON_RENDER_STATE = "jsonRender.state";
4
+ Object.defineProperty(exports, "JSON_RENDER_STATE", {
5
+ enumerable: true,
6
+ get: function() {
7
+ return JSON_RENDER_STATE;
8
+ }
9
+ });
10
+
11
+ //# sourceMappingURL=state-BJ97_AE8.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-BJ97_AE8.cjs","names":[],"sources":["../src/state.ts"],"sourcesContent":["/** The `requestContext` key a client sends the state its interface holds under, so the model can see it. */\nexport const JSON_RENDER_STATE = 'jsonRender.state';\n"],"mappings":";;AACA,MAAa,oBAAoB"}
@@ -0,0 +1,6 @@
1
+ // src/state.ts
2
+ /** The `requestContext` key a client sends the state its interface holds under, so the model can see it. */
3
+ const JSON_RENDER_STATE = "jsonRender.state";
4
+ export { JSON_RENDER_STATE as t };
5
+
6
+ //# sourceMappingURL=state-Bl6NZlzO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state-Bl6NZlzO.js","names":[],"sources":["../src/state.ts"],"sourcesContent":["/** The `requestContext` key a client sends the state its interface holds under, so the model can see it. */\nexport const JSON_RENDER_STATE = 'jsonRender.state';\n"],"mappings":";;AACA,MAAa,oBAAoB"}
@@ -0,0 +1,3 @@
1
+ /** The `requestContext` key a client sends the state its interface holds under, so the model can see it. */
2
+ export declare const JSON_RENDER_STATE = "jsonRender.state";
3
+ //# sourceMappingURL=state.d.ts.map