diff --git a/Cargo.toml b/Cargo.toml index 192635ca..f1ff3f0b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,6 +114,7 @@ serde_json = { workspace = true, optional = true } # --- Dependencies for diagram feature +jsonschema = { version = "0.62", default-features = false, optional = true } schemars = { workspace = true, optional = true } serde_with = { workspace = true, optional = true } cel-interpreter = { version = "0.9.0", features = ["json"], optional = true } @@ -152,6 +153,7 @@ json = [ single_threaded_async = ["dep:async-task"] diagram = [ "json", + "dep:jsonschema", "dep:cel-interpreter", "dep:semver", "dep:serde_with", diff --git a/diagram-editor/dist.hash b/diagram-editor/dist.hash index dd31433b..29e0d89a 100644 --- a/diagram-editor/dist.hash +++ b/diagram-editor/dist.hash @@ -1 +1 @@ -04431de9d34dd48519d8e1a7d3b846e91743f9021e023ad7427ac3b12492dd24 \ No newline at end of file +d07f108c826cdf7d99e8b793b7fbdd106c6bf37b70729f98470f34a7d7c8f770 \ No newline at end of file diff --git a/diagram-editor/frontend/api.preprocessed.schema.json b/diagram-editor/frontend/api.preprocessed.schema.json index 1cc4e725..f81dcd88 100644 --- a/diagram-editor/frontend/api.preprocessed.schema.json +++ b/diagram-editor/frontend/api.preprocessed.schema.json @@ -1364,6 +1364,13 @@ "type": "string" }, "config": true, + "config_bindings": { + "additionalProperties": { + "type": "string" + }, + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object" + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -1872,6 +1879,13 @@ "config": { "description": "Configured data to pass into the function that `run` refers to. This will\nbe passed in as a keyword argument named `config`." }, + "config_bindings": { + "additionalProperties": { + "type": "string" + }, + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object" + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -2061,8 +2075,12 @@ { "description": "Connect the request to a registered section.\n\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"builder\": \"my_section_builder\",\n \"connect\": {\n \"my_section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```\n\nCustom sections can also be created via templates\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"templates\": {\n \"my_template\": {\n \"inputs\": [\"section_input\"],\n \"outputs\": [\"section_output\"],\n \"buffers\": [],\n \"ops\": {\n \"section_input\": {\n \"type\": \"node\",\n \"builder\": \"my_node\",\n \"next\": \"section_output\"\n }\n }\n }\n },\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"template\": \"my_template\",\n \"connect\": {\n \"section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```", "properties": { - "config": { - "default": null + "config": true, + "config_bindings": { + "additionalProperties": { + "type": "string" + }, + "type": "object" }, "connect": { "additionalProperties": { @@ -2104,6 +2122,23 @@ "buffers": { "$ref": "#/$defs/InputRemapping" }, + "config_schema": { + "anyOf": [ + { + "$ref": "#/$defs/Schema" + }, + { + "type": "null" + } + ] + }, + "input_schemas": { + "additionalProperties": { + "$ref": "#/$defs/Schema" + }, + "description": "JSON Schemas for the template's exposed input ports.", + "type": "object" + }, "inputs": { "$ref": "#/$defs/InputRemapping" }, @@ -2114,6 +2149,13 @@ "description": "Operations that define the behavior of the section.", "type": "object" }, + "output_schemas": { + "additionalProperties": { + "$ref": "#/$defs/Schema" + }, + "description": "JSON Schemas for the template's exposed output ports.", + "type": "object" + }, "outputs": { "default": [], "description": "These are the outputs that the section is exposing so you can connect\nthem into siblings of the section.", diff --git a/diagram-editor/frontend/command-panel.tsx b/diagram-editor/frontend/command-panel.tsx index 9f98614d..56acfddd 100644 --- a/diagram-editor/frontend/command-panel.tsx +++ b/diagram-editor/frontend/command-panel.tsx @@ -20,6 +20,7 @@ export interface CommandPanelProps { exportDisabledReason?: string; isDirty: boolean; scriptNodeBinding?: ScriptNodeEnvironmentBinding; + templatePanel?: React.ReactNode; } const VisuallyHiddenInput = styled('input')({ @@ -43,6 +44,7 @@ function CommandPanel({ exportDisabledReason, isDirty, scriptNodeBinding, + templatePanel, }: CommandPanelProps) { const theme = useTheme(); const [openEditTemplatesDialog, setOpenEditTemplatesDialog] = @@ -88,34 +90,31 @@ function CommandPanel({ )} - {editorMode.mode === EditorMode.Normal && ( - - - - )} - {editorMode.mode === EditorMode.Normal && ( - + {( + [ + ['environments', 'Script Environment Manager', 'code'], + [ + 'properties', + editorMode.mode === EditorMode.Template + ? 'Template settings' + : 'Diagram properties', + 'info', + ], + ] as const + ).map(([tab, title, symbol]) => ( + - )} + ))} {editorMode.mode === EditorMode.Normal && ( + + ); } diff --git a/diagram-editor/frontend/forms/schema-editor.tsx b/diagram-editor/frontend/forms/schema-editor.tsx new file mode 100644 index 00000000..bb58a996 --- /dev/null +++ b/diagram-editor/frontend/forms/schema-editor.tsx @@ -0,0 +1,639 @@ +import { + Button, + Checkbox, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + Divider, + FormControlLabel, + IconButton, + MenuItem, + Stack, + TextField, + Typography, +} from '@mui/material'; +import { + type FieldProps, + isObject, + type RJSFSchema, + type UiSchema, +} from '@rjsf/utils'; +import type { NodeChange } from '@xyflow/react'; +import { createContext, useContext, useMemo, useState } from 'react'; +import { + MaterialSymbol, + type SectionInputNode, + type SectionOutputNode, +} from '../nodes'; +import { useRegistry } from '../registry-provider'; +import ajv from '../utils/ajv'; +import { pointerSegment } from '../utils/schema-types'; +import SchemaConfigForm from './schema-config-form'; +import TypeLabel from './type-label'; + +type Schema = RJSFSchema | boolean; +const initial: RJSFSchema = { type: 'string' }; +const schemasByKind: Record = { + string: initial, + integer: { type: 'integer' }, + number: { type: 'number' }, + boolean: { type: 'boolean' }, + null: { type: 'null' }, + array: { type: 'array', items: initial }, + object: { type: 'object' }, + enum: { enum: ['option'] }, + anyOf: { anyOf: [initial] }, + oneOf: { oneOf: [initial] }, + any: {}, +}; +const choiceRef = { $ref: '#/$defs/choice' }; +const nullConstraints = [ + 'const', + '$ref', + '$dynamicRef', + 'allOf', + 'anyOf', + 'oneOf', + 'not', + 'if', +]; +const choice: RJSFSchema = { + default: '', + oneOf: [ + { type: 'string', default: '' }, + { type: 'number', default: 0 }, + { type: 'boolean', enum: [true, false], default: false }, + { type: 'null' }, + { type: 'array', items: choiceRef, default: [] }, + { type: 'object', additionalProperties: choiceRef, default: {} }, + ], +}; + +function concreteType(type: unknown) { + if (Array.isArray(type) && type.length === 2 && type.includes('null')) + type = type.find((t) => t !== 'null'); + return typeof type === 'string' && schemasByKind[type]?.type === type + ? type + : undefined; +} + +function withNull(schema: RJSFSchema, allow: boolean): RJSFSchema { + const next = { ...schema }; + const type = concreteType(schema.type); + if (type && type !== 'null') next.type = allow ? [type, 'null'] : type; + if (Array.isArray(schema.enum)) { + const values = schema.enum.filter((v) => v !== null); + next.enum = allow ? [...values, null] : values; + } + if (!allow && schema.default === null) delete next.default; + return next; +} + +function kindOf(schema: Schema) { + if (typeof schema === 'boolean') return 'JSON'; + if (Object.keys(schema).every((key) => key === 'title')) return 'any'; + if (Array.isArray(schema.enum)) return 'enum'; + return ( + concreteType(schema.type) ?? + ['anyOf', 'oneOf', '$ref'].find((key) => key in schema) ?? + 'JSON' + ); +} + +export function schemaSummary(schema: Schema) { + if (typeof schema === 'boolean') return schema ? 'any' : 'never'; + if (typeof schema.title === 'string') return schema.title; + if (typeof schema.$ref === 'string') return schema.$ref.split('/').pop(); + return Array.isArray(schema.type) ? schema.type.join(' | ') : kindOf(schema); +} + +function readSchema(draft: Schema | string) { + try { + const schema: Schema = + typeof draft === 'string' ? JSON.parse(draft) : draft; + if (typeof schema !== 'boolean' && !isObject(schema)) + return { error: 'A JSON Schema must be an object or a boolean.' }; + if (!ajv.validateSchema(schema)) + return { schema, error: ajv.errorsText(ajv.errors) }; + return { schema, kind: kindOf(schema) }; + } catch (err) { + return { error: String(err) }; + } +} + +export type RenameProperty = ( + from: string, + to: string, + schema: RJSFSchema, +) => string | undefined; + +const PortSchemaContext = createContext(false); + +export function PortSchemaEditor< + N extends SectionInputNode | SectionOutputNode, +>({ node, onChange }: { node: N; onChange?: (change: NodeChange) => void }) { + return ( + + + onChange?.({ + type: 'replace', + id: node.id, + item: { ...node, data: { ...node.data, schema } }, + }) + } + /> + + ); +} + +function SchemaItem({ formData, onChange, fieldPathId }: FieldProps) { + const index = fieldPathId.path.at(-1); + return ( + onChange(schema, fieldPathId.path)} + /> + ); +} + +interface SchemaFieldsProps { + value: RJSFSchema; + onChange: (value: RJSFSchema) => void; +} + +function schemaList(items: UiSchema): UiSchema { + // RJSF provides the add button and item toolbar. Share the title row with + // the add button, keeping a single column of items below it. + return { + 'ui:mui': { + rjsfSlotProps: { + arrayPaper: { elevation: 0, sx: { bgcolor: 'transparent' } }, + arrayBox: { sx: { p: 0, display: 'grid' } }, + titleBox: { + sx: { + gridArea: '1 / 1', + m: 0, + alignContent: 'center', + borderBottom: 1, + borderColor: 'divider', + }, + }, + titleTypography: { variant: 'subtitle2', sx: { width: 'fit-content' } }, + titleDivider: { sx: { display: 'none' } }, + arrayAddButtonGridContainer: { + sx: { gridArea: '1 / 1', justifySelf: 'end' }, + }, + arrayAddButtonBox: { sx: { mt: 0 } }, + }, + }, + items, + }; +} + +const schemaItem = { 'ui:field': SchemaItem }; +const alternatives = schemaList(schemaItem); +const schemaUi: UiSchema = { + default: { 'ui:placeholder': 'No default' }, + enum: schemaList({ 'ui:emptyValue': '' }), + items: schemaItem, + anyOf: alternatives, + oneOf: alternatives, +}; + +// RJSF edits the schema document itself. For example, its standard array +// control adds and reorders the schema objects saved under anyOf or oneOf. +function SchemaFields({ + value, + onChange, + inlineTitle, +}: SchemaFieldsProps & { inlineTitle?: boolean }) { + const registry = useRegistry(); + const port = useContext(PortSchemaContext); + const kind = kindOf(value); + const type = concreteType(value.type); + const choices = value.enum; + // A sibling constraint can reject null even when the type admits it. + // Those schemas retain their explicit alternatives or JSON editor. + const canAllowNull = + (type ? type !== 'null' : choices && value.type === undefined) && + !nullConstraints.some((key) => key in value); + const nullable = + (value.type === undefined || + (Array.isArray(value.type) && value.type.includes('null'))) && + (!choices || choices.includes(null)); + const enumType = useMemo( + () => + kind === 'enum' && value.type + ? ajv.compile({ type: value.type }) + : undefined, + [kind, value.type], + ); + const refs = Object.keys(registry.schemas).map( + (name) => `#/schemas/${pointerSegment(name)}`, + ); + const fields: Record = {}; + if (!inlineTitle) fields.title = { type: 'string', title: 'Title' }; + if (kind === '$ref') + fields.$ref = { + type: 'string', + title: 'Registered type', + enum: [...new Set([...refs, String(value.$ref)])], + }; + if (choices || kind === 'anyOf' || kind === 'oneOf') { + fields[kind] = { + type: 'array', + minItems: 1, + title: choices ? 'Choices' : 'Alternatives', + items: choices + ? { ...choiceRef, title: 'Choice type' } + : { type: 'object', default: initial }, + }; + if (choices) fields.enum.uniqueItems = true; + } + if (kind === 'array') fields.items = { type: 'object', title: 'Items' }; + if (['number', 'integer'].includes(kind)) { + fields.minimum = { type: 'number', title: 'Minimum' }; + fields.maximum = { type: 'number', title: 'Maximum' }; + } + if ( + !port && + (choices?.length || + ['string', 'integer', 'number', 'boolean'].includes(kind)) + ) { + fields.default = { title: 'Default value' }; + if (choices) fields.default.enum = choices; + else if (kind === 'boolean') + fields.default.enum = nullable ? [true, false, null] : [true, false]; + else fields.default.type = value.type; + } + const kinds = { ...schemasByKind }; + if (refs.length || kind === '$ref') kinds.$ref = { $ref: refs[0] }; + return ( + + + { + const next = kinds[target.value]; + onChange({ + ...(canAllowNull && nullable ? withNull(next, true) : next), + ...(value.title !== undefined && { title: value.title }), + }); + }} + > + {Object.keys(kinds).map((k) => ( + + {k === '$ref' ? 'Registered type' : k} + + ))} + + {canAllowNull && ( + } + checked={nullable} + onChange={(_, checked) => onChange(withNull(value, checked))} + /> + )} + + { + const next = data as RJSFSchema; + // Older enums declared a redundant type. Widen it when the author + // adds a choice of another type, preserving other schema constraints. + if ( + enumType && + choices?.every((item) => enumType(item)) && + next.enum?.some((item) => !enumType(item)) + ) { + const { type: _oldType, ...widened } = next; + onChange(widened); + } else onChange(next); + }} + /> + {kind === 'object' && } + + ); +} + +interface DraftProps { + label: string; + value: Schema; + name?: string; + required?: boolean; + names?: string[]; + json?: boolean; + inlineTitle?: boolean; + onSave: ( + schema: Schema, + name: string, + required: boolean, + ) => string | undefined; + onClose: () => void; +} + +function SchemaDialog(props: DraftProps) { + const [name, setName] = useState(props.name ?? ''); + const [nameError, setNameError] = useState(); + const [required, setRequired] = useState(props.required ?? false); + const [draft, setDraft] = useState(() => { + const { kind } = readSchema(props.value); + return props.json || !kind || kind === 'JSON' + ? JSON.stringify(props.value, null, 2) + : props.value; + }); + const json = typeof draft === 'string'; + const { schema = props.value, kind, error } = readSchema(draft); + const duplicate = + name !== props.name && props.names?.includes(name) + ? 'A property with this name already exists.' + : undefined; + return ( + + {props.label} + + + {props.names && ( + { + setName(target.value); + setNameError(undefined); + }} + /> + )} + {json ? ( + setDraft(target.value)} + error={!!error} + helperText={error} + slotProps={{ input: { sx: { fontFamily: 'monospace' } } }} + /> + ) : ( + + )} + {props.name !== undefined && ( + } + checked={required} + onChange={(_, checked) => setRequired(checked)} + /> + )} + + + + + + + + + ); +} + +function iconButton(label: string, symbol: string, onClick: () => void) { + return ( + + + + ); +} + +function Properties({ + value, + onChange, + onRenameProperty, +}: SchemaFieldsProps & { onRenameProperty?: RenameProperty }) { + const fields = value.properties ?? {}; + const required = value.required ?? []; + const [editing, setEditing] = useState(); + function update( + schema: Schema | undefined, + name: string, + isRequired = false, + ) { + const previous = editing ?? name; + const rename = (key: string) => (key === previous ? name : key); + const properties = new Map( + Object.entries(fields).map(([key, field]) => [rename(key), field]), + ); + if (schema === undefined) properties.delete(name); + else properties.set(name, schema); + const keys = new Set(required.map(rename)); + if (isRequired) keys.add(name); + else keys.delete(name); + const next: RJSFSchema = { + ...value, + properties: Object.fromEntries(properties), + }; + if (keys.size) next.required = [...keys]; + else delete next.required; + if (previous !== name && onRenameProperty) + return onRenameProperty(previous, name, next); + onChange(next); + } + return ( + + {Object.entries(fields).map(([name, schema]) => ( + + + + {name} + {required.includes(name) && ' *'} + + {schemaSummary(schema)} + + {iconButton(`Edit ${name}`, 'edit', () => setEditing(name))} + {iconButton(`Delete ${name}`, 'delete', () => { + if (window.confirm(`Delete property “${name}”?`)) + update(undefined, name); + })} + + ))} + + {editing !== undefined && ( + setEditing(undefined)} + onSave={update} + /> + )} + + ); +} + +export default function SchemaEditor({ + label, + value, + onChange, + onRenameProperty, + object = false, + removable = true, + alternative = false, +}: { + label: string; + value?: Schema; + onChange: (value: Schema | undefined) => void; + onRenameProperty?: RenameProperty; + object?: boolean; + removable?: boolean; + alternative?: boolean; +}) { + const [open, setOpen] = useState(false); + const schema: Schema = value ?? (object ? { type: 'object' } : initial); + const inlineTitle = alternative && typeof schema === 'object'; + const { title, ...definition } = inlineTitle ? schema : {}; + const name = typeof title === 'string' ? title : ''; + return ( + + + {inlineTitle ? ( + + onChange( + target.value + ? { ...definition, title: target.value } + : definition, + ) + } + /> + ) : ( + + {label} + + )} + {!object && value !== undefined && ( + + {schemaSummary(inlineTitle ? definition : value)} + + )} + + {removable && + value !== undefined && + iconButton(`Remove ${label}`, 'delete', () => { + if (!object || window.confirm('Remove the configuration schema?')) + onChange(undefined); + })} + + {object && readSchema(schema).kind === 'object' && ( + <> + + + + )} + {open && ( + setOpen(false)} + onSave={(next) => { + onChange(next); + return undefined; + }} + /> + )} + + ); +} diff --git a/diagram-editor/frontend/forms/script-environment-workspace.test.tsx b/diagram-editor/frontend/forms/script-environment-workspace.test.tsx index a2790a2d..f1f6cde4 100644 --- a/diagram-editor/frontend/forms/script-environment-workspace.test.tsx +++ b/diagram-editor/frontend/forms/script-environment-workspace.test.tsx @@ -1,3 +1,4 @@ +import { createTheme, ThemeProvider } from '@mui/material'; import { act, fireEvent, @@ -172,6 +173,10 @@ function PanelStateProbe() { return {JSON.stringify(state)}; } +const workspaceTheme = createTheme({ + components: { MuiDialog: { defaultProps: { transitionDuration: 0 } } }, +}); + function renderWorkspace( ui: ReactNode, registry: DiagramElementMetadata = testRegistry, @@ -193,6 +198,11 @@ function renderWorkspace( , + { + wrapper: ({ children }) => ( + {children} + ), + }, ); } @@ -224,19 +234,21 @@ describe('ScriptEnvironmentWorkspace', () => { screen.getByRole('option', { name: 'generic-script-builder' }), ); - await waitFor(() => { - expect( - screen.getByLabelText('Builder Config (JSON)'), - ).toBeInTheDocument(); - }); - const config = screen.getByLabelText('Builder Config (JSON)'); - fireEvent.change(config, { - target: { value: '{"script_content":"first"}' }, - }); + fireEvent.change( + await screen.findByRole('textbox', { name: 'script_content' }), + { + target: { value: 'first' }, + }, + ); fireEvent.mouseDown(screen.getByLabelText('Code Field')); fireEvent.click(screen.getByRole('option', { name: 'script_content' })); expect(scriptEditor()).toHaveValue('first'); + expect( + screen.queryByRole('textbox', { name: 'script_content' }), + ).not.toBeInTheDocument(); changeScript('second'); + fireEvent.click(screen.getByRole('button', { name: 'Edit JSON' })); + const config = screen.getByLabelText('Builder Config'); expect(JSON.parse((config as HTMLTextAreaElement).value)).toEqual({ script_content: 'second', }); diff --git a/diagram-editor/frontend/forms/script-environment-workspace.tsx b/diagram-editor/frontend/forms/script-environment-workspace.tsx index 36a4022f..12d90097 100644 --- a/diagram-editor/frontend/forms/script-environment-workspace.tsx +++ b/diagram-editor/frontend/forms/script-environment-workspace.tsx @@ -37,6 +37,7 @@ import { useRegistry } from '../registry-provider'; import { useTransientEditorDrafts } from '../transient-editor-drafts'; import type { DiagramElementMetadata } from '../types/api'; import { EnvironmentWindow } from './environment-window'; +import SchemaConfigForm from './schema-config-form'; import { ScriptEnvironmentPanel } from './script-environment-panel'; import { scriptEnvironmentPlugins } from './script-environments/registry'; @@ -191,6 +192,7 @@ export function ScriptEnvironmentWorkspace({ }, [draft, editorWindow, expanded, width, updateDraft]); const plugin = scriptEnvironmentPlugins[builder]; const activeCodeField = plugin?.defaultCodeField || selectedCodeField; + const builderSchema = registry.scripting?.[builder]?.config_schema; const builderDraft = useCallback( (builder: string) => ({ @@ -215,7 +217,7 @@ export function ScriptEnvironmentWorkspace({ const values = builderDraft(environment?.builder || defaultBuilder); if (environment) values.config = JSON.stringify( - objectConfig(environment.config), + environment.config === undefined ? {} : environment.config, null, 2, ); @@ -260,13 +262,14 @@ export function ScriptEnvironmentWorkspace({ [nodeManager.nodes], ); - let parsedConfig: Record = {}; + let configValue: unknown; let jsonError: string | null = null; try { - parsedConfig = objectConfig(JSON.parse(config)); + configValue = JSON.parse(config); } catch (error) { jsonError = (error as Error).message; } + const parsedConfig = objectConfig(configValue); const configKeys = Object.keys(parsedConfig).filter( (key) => typeof parsedConfig[key] === 'string', ); @@ -732,6 +735,29 @@ export function ScriptEnvironmentWorkspace({ registry={registry} scriptText={scriptText} /> + ) : builderSchema && + typeof builderSchema === 'object' && + Object.keys(builderSchema).length ? ( + { + if (text !== undefined) updateDraft({ config: text }); + }} + onChange={(value) => + updateDraft({ config: JSON.stringify(value, null, 2) ?? '' }) + } + /> ) : ( { ); const selectElement = screen.getByLabelText('Environment Ownership'); - expect(selectElement).toBeTruthy(); - expect(screen.getByText('Persistent')).toBeTruthy(); + expect(selectElement).toHaveValue('persistent'); }); test('invokes onChange when ownership option is changed', async () => { @@ -56,7 +55,7 @@ describe('PythonPropertiesForm', () => { fireEvent.mouseDown(selectElement); // Select 'Isolated' - const isolatedOption = screen.getByRole('option', { name: 'Isolated' }); + const isolatedOption = screen.getByRole('option', { name: 'isolated' }); fireEvent.click(isolatedOption); expect(mockOnChange).toHaveBeenCalled(); @@ -106,7 +105,10 @@ describe('PythonPropertiesForm', () => { }, definitions: { PythonEnvironmentOwnership: { - enum: ['shared_custom', 'persistent_custom'], + oneOf: [ + { type: 'string', const: 'shared_custom' }, + { type: 'string', const: 'persistent_custom' }, + ], }, }, }, @@ -128,9 +130,9 @@ describe('PythonPropertiesForm', () => { const selectElement = screen.getByRole('combobox'); fireEvent.mouseDown(selectElement); - expect(screen.getByRole('option', { name: 'Shared_custom' })).toBeTruthy(); + expect(screen.getByRole('option', { name: 'shared_custom' })).toBeTruthy(); expect( - screen.getByRole('option', { name: 'Persistent_custom' }), + screen.getByRole('option', { name: 'persistent_custom' }), ).toBeTruthy(); }); }); diff --git a/diagram-editor/frontend/forms/script-environments/python-form.tsx b/diagram-editor/frontend/forms/script-environments/python-form.tsx index 3bee173c..3d31ccf2 100644 --- a/diagram-editor/frontend/forms/script-environments/python-form.tsx +++ b/diagram-editor/frontend/forms/script-environments/python-form.tsx @@ -1,24 +1,14 @@ -import { MenuItem, TextField } from '@mui/material'; import { useEffect, useMemo } from 'react'; +import SchemaConfigForm from '../schema-config-form'; import type { ScriptEnvironmentFormProps } from './registry'; -type JsonSchemaProperty = { - $ref?: string; - anyOf?: JsonSchemaProperty[]; - enum?: string[]; +const fallback = { + type: 'object', + properties: { + ownership: { type: 'string', enum: ['shared', 'persistent', 'isolated'] }, + }, }; -type JsonSchemaObject = JsonSchemaProperty & { - definitions?: Record; - properties?: Record; -}; - -function schemaObject(value: unknown): JsonSchemaObject | null { - return typeof value === 'object' && value !== null && !Array.isArray(value) - ? (value as JsonSchemaObject) - : null; -} - export function PythonPropertiesForm({ config, onChange, @@ -27,73 +17,30 @@ export function PythonPropertiesForm({ registry, scriptText, }: ScriptEnvironmentFormProps) { - const ownershipOptions = useMemo(() => { - const schema = schemaObject( - registry?.scripting?.['process-bound-python']?.config_schema, - ); - const ownershipProp = schema?.properties?.ownership; - const ref = ownershipProp?.$ref || ownershipProp?.anyOf?.[0]?.$ref; - let enumValues: string[] = ['shared', 'persistent', 'isolated']; - if (ref) { - const defName = ref.split('/').pop(); - const def = defName - ? schemaObject(schema?.definitions?.[defName]) || - schemaObject(registry?.schemas?.[defName]) - : null; - if (def?.enum) { - enumValues = def.enum; - } - } else if (ownershipProp?.enum) { - enumValues = ownershipProp.enum; - } - return enumValues; - }, [registry]); - - const getOwnershipValue = () => { - try { - const obj = JSON.parse(config); - return obj.ownership || 'persistent'; - } catch { - return 'persistent'; - } - }; - - // Validate config is valid JSON - useEffect(() => { + const parsed = useMemo(() => { try { - JSON.parse(config); - onValidationError(null); - } catch (err) { - onValidationError(err instanceof Error ? err.message : 'Invalid JSON'); + return { value: JSON.parse(config), error: null }; + } catch (error) { + return { value: { script: scriptText }, error: String(error) }; } - }, [config, onValidationError]); - - const handleOwnershipChange = (newVal: string) => { - try { - const obj = JSON.parse(config) || {}; - obj.ownership = newVal; - onChange(JSON.stringify(obj, null, 2)); - } catch { - const obj = { ownership: newVal, script: scriptText }; - onChange(JSON.stringify(obj, null, 2)); - } - }; - + }, [config, scriptText]); + useEffect( + () => onValidationError(parsed.error), + [parsed.error, onValidationError], + ); + const schema = registry.scripting?.['process-bound-python']?.config_schema; return ( - handleOwnershipChange(e.target.value)} - fullWidth + onChange(JSON.stringify(value, null, 2))} disabled={mode === 'view'} - sx={{ flex: 1 }} - > - {ownershipOptions.map((opt) => ( - - {opt.charAt(0).toUpperCase() + opt.slice(1)} - - ))} - + uiSchema={{ + 'ui:label': false, + ownership: { 'ui:title': 'Environment Ownership' }, + script: { 'ui:widget': 'hidden' }, + }} + /> ); } diff --git a/diagram-editor/frontend/forms/script-form.tsx b/diagram-editor/frontend/forms/script-form.tsx index 81fc850d..2f94a7fc 100644 --- a/diagram-editor/frontend/forms/script-form.tsx +++ b/diagram-editor/frontend/forms/script-form.tsx @@ -7,14 +7,15 @@ import { Tooltip, Typography, } from '@mui/material'; -import { useMemo, useState } from 'react'; +import { useMemo } from 'react'; import { useDiagramProperties } from '../diagram-properties-provider'; import { useDiagramSidePanel } from '../diagram-side-panel-controller'; import { MaterialSymbol } from '../nodes'; -import { useTransientEditorDrafts } from '../transient-editor-drafts'; import BaseEditOperationForm, { type BaseEditOperationFormProps, + operationUpdater, } from './base-edit-operation-form'; +import OperationConfigForm from './operation-config-form'; import { useScriptEnvironmentNavigation } from './use-script-environment-navigation'; export type ScriptFormProps = BaseEditOperationFormProps<'script'>; @@ -22,8 +23,9 @@ export type ScriptFormProps = BaseEditOperationFormProps<'script'>; const CREATE_ENVIRONMENT_VALUE = '__create_script_environment__'; function ScriptForm(props: ScriptFormProps) { + const { op } = props.node.data; + const replaceOp = operationUpdater(props); const [diagramProperties] = useDiagramProperties(); - const { drafts, setOperationConfigDraft } = useTransientEditorDrafts(); const environments = diagramProperties.script_environments || {}; const openScriptEnvironment = useScriptEnvironmentNavigation(); const { @@ -33,48 +35,14 @@ function ScriptForm(props: ScriptFormProps) { requestEnvironmentLeave, } = useDiagramSidePanel(); - // Track raw string of node config to support JSON editing - const configDraftKey = `script:${props.node.id}:config`; - const [configValue, setConfigValue] = useState( - () => - drafts.operationConfigs[configDraftKey] ?? - (props.node.data.op.config - ? JSON.stringify(props.node.data.op.config, null, 2) - : ''), - ); - - const configError = useMemo(() => { - if (configValue === '') return false; - try { - JSON.parse(configValue); - return false; - } catch { - return true; - } - }, [configValue]); - const handleEnvChange = (envName: string) => requestEnvironmentLeave(() => { - const updatedNode = { - ...props.node, - data: { - ...props.node.data, - op: { - ...props.node.data.op, - environment: envName, - }, - }, - }; - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); + replaceOp({ ...op, environment: envName }); openScriptEnvironment(envName, false); }); // Real-time parse python entrypoint functions from selected environment - const selectedEnvName = props.node.data.op.environment; + const selectedEnvName = op.environment; const selectedEnv = selectedEnvName ? environments[selectedEnvName] : undefined; @@ -110,23 +78,17 @@ function ScriptForm(props: ScriptFormProps) { { - const updatedNode = { ...props.node }; - updatedNode.data.op.display_text = ev.target.value || undefined; - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); - }} + value={op.display_text || ''} + onChange={(ev) => + replaceOp({ ...op, display_text: ev.target.value || undefined }) + } /> { if (e.target.value === CREATE_ENVIRONMENT_VALUE) { requestEnvironmentLeave(startEnvironmentCreate); @@ -170,10 +132,7 @@ function ScriptForm(props: ScriptFormProps) { closePanel(); return; } - openScriptEnvironment( - props.node.data.op.environment || undefined, - false, - ); + openScriptEnvironment(selectedEnvName || undefined, false); }} > @@ -186,24 +145,10 @@ function ScriptForm(props: ScriptFormProps) { freeSolo autoSelect options={availableFunctions} - value={props.node.data.op.run || ''} - onChange={(_, val) => { - const updatedNode = { ...props.node }; - updatedNode.data.op.run = val ?? ''; - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); - }} - onInputChange={(_, val) => { - const updatedNode = { ...props.node }; - updatedNode.data.op.run = val; - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); + value={op.run || ''} + onChange={(_, val) => replaceOp({ ...op, run: val ?? '' })} + onInputChange={(_, val, reason) => { + if (reason === 'input') replaceOp({ ...op, run: val }); }} renderInput={(params) => ( - { - setConfigValue(ev.target.value); - try { - const updatedNode = { ...props.node }; - updatedNode.data.op.config = - ev.target.value === '' ? undefined : JSON.parse(ev.target.value); - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); - setOperationConfigDraft(configDraftKey, undefined); - } catch { - setOperationConfigDraft(configDraftKey, ev.target.value); - } - }} - error={configError} - slotProps={{ - htmlInput: { - sx: { fontFamily: 'monospace', whiteSpace: 'nowrap' }, - }, - }} /> ); diff --git a/diagram-editor/frontend/forms/section-form.tsx b/diagram-editor/frontend/forms/section-form.tsx index a58db85d..bcabafc5 100644 --- a/diagram-editor/frontend/forms/section-form.tsx +++ b/diagram-editor/frontend/forms/section-form.tsx @@ -21,9 +21,13 @@ import { } from '../nodes'; import { useRegistry } from '../registry-provider'; import { useTemplates } from '../templates-provider'; +import { useTransientEditorDrafts } from '../transient-editor-drafts'; import BaseEditOperationForm, { type BaseEditOperationFormProps, + operationUpdater, } from './base-edit-operation-form'; +import OperationConfigForm from './operation-config-form'; +import { PortSchemaEditor } from './schema-editor'; export interface BaseSectionInterfaceFormProps { node: SectionInterfaceNode; @@ -80,6 +84,7 @@ export function SectionInputForm({ }); }} /> + ); @@ -144,6 +149,7 @@ export function SectionOutputForm({ }); }} /> + ); @@ -152,66 +158,54 @@ export function SectionOutputForm({ export type SectionFormProps = BaseEditOperationFormProps<'section'>; export function SectionForm(props: SectionFormProps) { + const { clearOperationConfigDrafts } = useTransientEditorDrafts(); const registry = useRegistry(); - const [templates, _setTemplates] = useTemplates(); + const [templates] = useTemplates(); const sectionBuilders = Object.keys(registry.sections); const sectionTemplates = Object.keys(templates); const sections = [...sectionBuilders, ...sectionTemplates].sort(); + const op = props.node.data.op; + const replaceOp = operationUpdater(props); + const template = + typeof op.template === 'string' ? templates[op.template] : undefined; + const schema = + typeof op.builder === 'string' + ? registry.sections[op.builder]?.config_schema + : template?.config_schema; + return ( { - try { - const updatedNode = { ...props.node }; - updatedNode.data.op.display_text = ev.target.value || undefined; - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); - } catch {} - }} + value={op.display_text || ''} + onChange={(ev) => + replaceOp({ ...op, display_text: ev.target.value || undefined }) + } /> option} - value={ - (props.node.data.op.builder || - props.node.data.op.template || - '') as string - } + value={(op.builder ?? op.template ?? '') as string} onChange={(_, value) => { - if (value === null) { - return; - } - - const updatedNode = { ...props.node }; - if (sectionBuilders.includes(value)) { - updatedNode.data.op.builder = value; - delete updatedNode.data.op.template; - } else if (sectionTemplates.includes(value)) { - updatedNode.data.op.template = value; - delete updatedNode.data.op.builder; - } else { - // unable to determine if selected option is a builder or template, assume template. - updatedNode.data.op.template = value; - delete updatedNode.data.op.builder; - } - props.onChange?.({ - type: 'replace', - id: props.node.id, - item: updatedNode, - }); + if (value === null || value === (op.builder ?? op.template)) return; + clearOperationConfigDrafts([props.node.id]); + const { builder: _builder, template: _template, ...rest } = op; + replaceOp( + sectionBuilders.includes(value) + ? { ...rest, builder: value } + : { ...rest, template: value }, + ); }} renderInput={(params) => ( )} /> + {(!template || schema != null) && ( + + )} ); } diff --git a/diagram-editor/frontend/forms/template-panel.tsx b/diagram-editor/frontend/forms/template-panel.tsx new file mode 100644 index 00000000..ca183109 --- /dev/null +++ b/diagram-editor/frontend/forms/template-panel.tsx @@ -0,0 +1,87 @@ +import { Box, Divider, Stack, Typography } from '@mui/material'; +import { Fragment, type ReactNode } from 'react'; +import { useCompatibilityChecker } from '../connection-compatibility-provider'; +import { useNodeManager } from '../node-manager'; +import { useTemplates } from '../templates-provider'; +import type { Schema } from '../types/api'; +import { useEdges } from '../use-edges'; +import SchemaEditor, { schemaSummary } from './schema-editor'; +import TypeLabel from './type-label'; + +export default function TemplatePanel({ + templateId, + onChangeSchema, +}: { + templateId: string; + onChangeSchema: ( + schema: Schema | undefined, + rename?: { from: string; to: string }, + ) => string | undefined; +}) { + const [templates] = useTemplates(); + const template = templates[templateId]; + const { nodes } = useNodeManager(); + const edges = useEdges(); + const { edgeResults } = useCompatibilityChecker(); + const ports: Record<'Inputs' | 'Outputs', ReactNode[]> = { + Inputs: [], + Outputs: [], + }; + for (const node of nodes) { + if (node.type !== 'sectionInput' && node.type !== 'sectionOutput') continue; + const input = node.type === 'sectionInput'; + const edge = edges.find((e) => (input ? e.source : e.target) === node.id); + const result = edge && edgeResults.get(edge.id); + const type = + node.data.schema === undefined + ? ((input ? result?.targetType : result?.sourceType) ?? 'unknown') + : schemaSummary(node.data.schema); + ports[input ? 'Inputs' : 'Outputs'].push( + +
{input ? node.data.remappedId : node.data.outputId}
+ + {type} + +
, + ); + } + + return ( + + {(ports.Inputs.length > 0 || ports.Outputs.length > 0) && ( + <> + + {Object.entries(ports).map(([direction, entries]) => ( + + {direction} + + {entries} + + + ))} + + + + )} + + onChangeSchema(schema, { from, to }) + } + /> + + ); +} diff --git a/diagram-editor/frontend/forms/type-label.tsx b/diagram-editor/frontend/forms/type-label.tsx new file mode 100644 index 00000000..af646677 --- /dev/null +++ b/diagram-editor/frontend/forms/type-label.tsx @@ -0,0 +1,40 @@ +import { Tooltip, Typography, type TypographyProps } from '@mui/material'; +import { useRef, useState } from 'react'; + +export default function TypeLabel({ + children, + component = 'span', + sx, +}: { + children: string | undefined; + component?: 'dd' | 'span'; + sx?: TypographyProps['sx']; +}) { + const label = useRef(null); + const [open, setOpen] = useState(false); + return ( + { + const el = label.current; + if (el) setOpen(el.scrollWidth > el.clientWidth); + }} + onClose={() => setOpen(false)} + > + + {children} + + + ); +} diff --git a/diagram-editor/frontend/nodes/section-node.tsx b/diagram-editor/frontend/nodes/section-node.tsx index ff2234df..ef9bb737 100644 --- a/diagram-editor/frontend/nodes/section-node.tsx +++ b/diagram-editor/frontend/nodes/section-node.tsx @@ -1,7 +1,7 @@ import { type NodeProps, Position } from '@xyflow/react'; import { Handle, HandleType } from '../handles'; import { useRegistry } from '../registry-provider'; -import type { NextOperation } from '../types/api'; +import type { NextOperation, Schema } from '../types/api'; import type { Node } from '../types/react-flow'; import { isSectionBuilder } from '../utils/operation'; import type { OperationNode } from '.'; @@ -16,12 +16,14 @@ import { export type SectionInputData = { remappedId: string; targetId: NextOperation; + schema?: Schema; }; export type SectionInputNode = Node; export type SectionOutputData = { outputId: string; + schema?: Schema; }; export type SectionOutputNode = Node; diff --git a/diagram-editor/frontend/templates-provider.tsx b/diagram-editor/frontend/templates-provider.tsx index ec099e0c..2c7a9d4c 100644 --- a/diagram-editor/frontend/templates-provider.tsx +++ b/diagram-editor/frontend/templates-provider.tsx @@ -6,6 +6,7 @@ import { useContext, useState, } from 'react'; +import { useTemplateId } from './editor-mode'; import type { SectionTemplate } from './types/api'; export type TemplatesContext = [ @@ -27,6 +28,12 @@ export function TemplatesProvider({ children }: PropsWithChildren) { ); } +export function useActiveTemplate(): SectionTemplate | undefined { + const id = useTemplateId(); + const context = useContext(TemplatesContextComp); + return id === undefined ? undefined : context?.[0][id]; +} + export function useTemplates(): TemplatesContext { const context = useContext(TemplatesContextComp); if (!context) { diff --git a/diagram-editor/frontend/transient-editor-drafts.tsx b/diagram-editor/frontend/transient-editor-drafts.tsx index b28efcb0..5b5d82d7 100644 --- a/diagram-editor/frontend/transient-editor-drafts.tsx +++ b/diagram-editor/frontend/transient-editor-drafts.tsx @@ -68,15 +68,12 @@ export function TransientEditorDraftProvider({ children }: PropsWithChildren) { const operationConfigs = { ...prev.operationConfigs }; let changed = false; for (const key of keys) { - const nodeKey = `node:${key}:config`; - const scriptKey = `script:${key}:config`; - if (nodeKey in operationConfigs) { - delete operationConfigs[nodeKey]; - changed = true; - } - if (scriptKey in operationConfigs) { - delete operationConfigs[scriptKey]; - changed = true; + for (const type of ['node', 'script', 'section']) { + const field = `${type}:${key}:config`; + if (field in operationConfigs) { + delete operationConfigs[field]; + changed = true; + } } } return changed ? { ...prev, operationConfigs } : prev; diff --git a/diagram-editor/frontend/types/api.d.ts b/diagram-editor/frontend/types/api.d.ts index ca8848df..e93f0c53 100644 --- a/diagram-editor/frontend/types/api.d.ts +++ b/diagram-editor/frontend/types/api.d.ts @@ -154,6 +154,9 @@ export type SectionSchema = ( } ) & { config?: unknown; + config_bindings?: { + [k: string]: string; + }; connect?: { [k: string]: NextOperation; }; @@ -619,6 +622,12 @@ export interface InputExample { export interface NodeSchema { builder: string; config?: unknown; + /** + * JSON pointers within config linked to properties of the enclosing template. + */ + config_bindings?: { + [k: string]: string; + }; /** * Override for text that should be displayed for an operation within an * editor. @@ -1306,6 +1315,12 @@ export interface ScriptSchema { * be passed in as a keyword argument named `config`. */ config?: unknown; + /** + * JSON pointers within config linked to properties of the enclosing template. + */ + config_bindings?: { + [k: string]: string; + }; /** * Override for text that should be displayed for an operation within an * editor. @@ -1354,6 +1369,13 @@ export interface ScriptEnvironmentSchema { */ export interface SectionTemplate { buffers?: InputRemapping; + config_schema?: Schema | null; + /** + * JSON Schemas for the template's exposed input ports. + */ + input_schemas?: { + [k: string]: Schema; + }; inputs?: InputRemapping; /** * Operations that define the behavior of the section. @@ -1361,6 +1383,12 @@ export interface SectionTemplate { ops: { [k: string]: DiagramOperation; }; + /** + * JSON Schemas for the template's exposed output ports. + */ + output_schemas?: { + [k: string]: Schema; + }; /** * These are the outputs that the section is exposing so you can connect * them into siblings of the section. diff --git a/diagram-editor/frontend/use-responsive-edit-popover-position.ts b/diagram-editor/frontend/use-responsive-edit-popover-position.ts index 9ccb7248..ec7e2cd0 100644 --- a/diagram-editor/frontend/use-responsive-edit-popover-position.ts +++ b/diagram-editor/frontend/use-responsive-edit-popover-position.ts @@ -20,9 +20,9 @@ function useViewportWidth(): number { return viewportWidth; } -export function useDiagramSidePanelWidth(): number { +export function useDiagramSidePanelWidth(open: boolean): number { const { - state: { open, expanded, width }, + state: { expanded, width }, } = useDiagramSidePanel(); const viewportWidth = useViewportWidth(); diff --git a/diagram-editor/frontend/utils/compatibility.ts b/diagram-editor/frontend/utils/compatibility.ts index 74534b22..3a2b8a5d 100644 --- a/diagram-editor/frontend/utils/compatibility.ts +++ b/diagram-editor/frontend/utils/compatibility.ts @@ -283,12 +283,15 @@ function portRefsForEdge( focusPorts, sourcePort: templateSection && - (sourceNode.type === 'sectionInput' || + ((sourceNode.type === 'sectionInput' && + sourceNode.data.schema === undefined) || sourceNode.type === 'sectionBuffer') ? undefined : sourcePort, targetPort: - templateSection && targetNode.type === 'sectionOutput' + templateSection && + targetNode.type === 'sectionOutput' && + targetNode.data.schema === undefined ? undefined : targetPort, }; @@ -345,6 +348,7 @@ export function buildCompatibilityRequest( graph.registry, nodeManager, edges, + graph.templates[graph.templateId], ), }, script_environments: cloneJson(graph.diagramProperties) diff --git a/diagram-editor/frontend/utils/export-diagram.ts b/diagram-editor/frontend/utils/export-diagram.ts index 1138e0aa..190b7d02 100644 --- a/diagram-editor/frontend/utils/export-diagram.ts +++ b/diagram-editor/frontend/utils/export-diagram.ts @@ -553,6 +553,7 @@ export function exportTemplate( registry: DiagramElementMetadata, nodeManager: NodeManager, edges: DiagramEditorEdge[], + source?: SectionTemplate, ): SectionTemplate { nodeManager = new NodeManager(JSON.parse(JSON.stringify(nodeManager.nodes))); const fakeRoot: SubOperations = { @@ -560,11 +561,14 @@ export function exportTemplate( ops: {}, }; const template = { + ...source, + input_schemas: undefined as SectionTemplate['input_schemas'], + output_schemas: undefined as SectionTemplate['output_schemas'], inputs: {} as Record, outputs: [] as string[], buffers: {} as Record, ops: fakeRoot.ops, - } satisfies Required; + } satisfies SectionTemplate; syncEdges(registry, nodeManager, fakeRoot, edges); @@ -583,8 +587,16 @@ export function exportTemplate( } } else if (node.type === 'sectionInput') { template.inputs[node.data.remappedId] = node.data.targetId; + if (node.data.schema !== undefined) { + template.input_schemas ??= {}; + template.input_schemas[node.data.remappedId] = node.data.schema; + } } else if (node.type === 'sectionOutput') { template.outputs.push(node.data.outputId); + if (node.data.schema !== undefined) { + template.output_schemas ??= {}; + template.output_schemas[node.data.outputId] = node.data.schema; + } } else if (node.type === 'sectionBuffer') { template.buffers[node.data.remappedId] = node.data.targetId; } diff --git a/diagram-editor/frontend/utils/load-diagram.ts b/diagram-editor/frontend/utils/load-diagram.ts index 709b1c76..6559f87e 100644 --- a/diagram-editor/frontend/utils/load-diagram.ts +++ b/diagram-editor/frontend/utils/load-diagram.ts @@ -234,5 +234,12 @@ export function loadTemplate(template: SectionTemplate): Graph { } } + for (const port of initialNodes) { + if (port.type === 'sectionInput') { + port.data.schema = template.input_schemas?.[port.data.remappedId]; + } else if (port.type === 'sectionOutput') { + port.data.schema = template.output_schemas?.[port.data.outputId]; + } + } return buildGraph(stubDiagram, { nodes: initialNodes, edges: [] }); } diff --git a/diagram-editor/frontend/utils/schema-types.ts b/diagram-editor/frontend/utils/schema-types.ts new file mode 100644 index 00000000..39861efd --- /dev/null +++ b/diagram-editor/frontend/utils/schema-types.ts @@ -0,0 +1,159 @@ +import { + type FieldTemplateProps, + findSchemaDefinition, + guessType, + type RJSFSchema, +} from '@rjsf/utils'; + +type Schema = RJSFSchema | boolean; + +export function pointerSegment(name: string) { + return name.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +export function fieldPointer(path: (string | number)[]) { + return path.map((key) => `/${pointerSegment(String(key))}`).join(''); +} + +export function withinField(pointer: string, field: string) { + return pointer === field || pointer.startsWith(`${field}/`); +} + +function resolve(schema: Schema, root: RJSFSchema) { + if (typeof schema === 'boolean') return undefined; + try { + return schema.$ref ? findSchemaDefinition(schema.$ref, root) : schema; + } catch { + return undefined; + } +} + +function choices(schema: RJSFSchema) { + return 'const' in schema ? [schema.const] : schema.enum; +} + +export function schemaDocument( + schema: object | boolean | null | undefined, + definitions?: Record, +) { + return { + schemas: definitions, + $defs: definitions, + definitions, + ...(typeof schema === 'object' && schema), + } as RJSFSchema; +} + +// An unknown branch may accept additional types, so don't infer a mismatch from it. +export function schemaTypes( + schema: Schema, + root: RJSFSchema, + refs: string[] = [], +): string[] { + if (typeof schema === 'boolean') return []; + if (schema.$ref) { + if (refs.includes(schema.$ref)) return []; + const resolved = resolve(schema, root); + return resolved ? schemaTypes(resolved, root, [...refs, schema.$ref]) : []; + } + const values = choices(schema); + if (values) { + return [ + ...new Set( + values.map((v) => (Number.isInteger(v) ? 'integer' : guessType(v))), + ), + ]; + } + if (schema.type) + return Array.isArray(schema.type) ? schema.type : [schema.type]; + const branches = (schema.anyOf ?? schema.oneOf)?.map((s) => + schemaTypes(s, root, refs), + ); + return branches?.every((types) => types.length) + ? [...new Set(branches.flat())] + : []; +} + +function numericWarning(schema: RJSFSchema, dest: RJSFSchema, types: string[]) { + // Other source constraints may narrow the range beyond its declared bounds. + if ( + !schema.type || + !types.some((t) => t === 'number' || t === 'integer') || + (['multipleOf', 'anyOf', 'oneOf', 'allOf', 'not', 'if'] as const).some( + (key) => schema[key], + ) + ) + return; + const integer = !types.includes('number'); + const lower = schema.exclusiveMinimum ?? -Infinity, + upper = schema.exclusiveMaximum ?? Infinity; + const min = integer + ? Math.max(Math.ceil(schema.minimum ?? -Infinity), Math.floor(lower) + 1) + : (schema.minimum ?? -Infinity); + const max = integer + ? Math.min(Math.floor(schema.maximum ?? Infinity), Math.ceil(upper) - 1) + : (schema.maximum ?? Infinity); + if (dest.minimum !== undefined && min < dest.minimum && lower < dest.minimum) + return `Minimum ${dest.minimum} expected`; + if (dest.maximum !== undefined && max > dest.maximum && upper > dest.maximum) + return `Maximum ${dest.maximum} expected`; + if ( + dest.exclusiveMinimum !== undefined && + min <= dest.exclusiveMinimum && + lower < dest.exclusiveMinimum + ) + return `Greater than ${dest.exclusiveMinimum} expected`; + if ( + dest.exclusiveMaximum !== undefined && + max >= dest.exclusiveMaximum && + upper > dest.exclusiveMaximum + ) + return `Less than ${dest.exclusiveMaximum} expected`; +} + +export function bindingProperties( + root: RJSFSchema, + field?: FieldTemplateProps, +) { + const target = field && resolve(field.schema, field.registry.rootSchema); + const expected = field + ? schemaTypes(field.schema, field.registry.rootSchema) + : []; + const accepted = new Set(expected); + if (accepted.has('number')) accepted.add('integer'); + + function warningFor(schema: Schema, types: string[]) { + if (!field) return; + const source = resolve(schema, root); + if (!source) return; + const values = choices(source); + if (values) { + const validator = field.registry.schemaUtils.getValidator(); + for (const value of values) { + if ( + validator.isValid(source, value, root) && + !validator.isValid(field.schema, value, field.registry.rootSchema) + ) + return `${JSON.stringify(value)} is outside the expected values`; + } + return; + } + if (accepted.size && types.some((type) => !accepted.has(type))) + return `${expected.join(' | ')} expected`; + if (target) return numericWarning(source, target, types); + } + + return Object.entries(root.properties ?? {}).map(([name, schema]) => { + const types = schemaTypes(schema, root); + const ref = typeof schema === 'object' ? schema.$ref : undefined; + const type = + ref?.split('/').at(-1) || + types.join(' | ') || + (schema === false + ? 'never' + : schema === true || !Object.keys(schema).length + ? 'any' + : 'unknown'); + return { name, type, warning: warningFor(schema, types) }; + }); +} diff --git a/diagram-editor/frontend/utils/update-template-schema.ts b/diagram-editor/frontend/utils/update-template-schema.ts new file mode 100644 index 00000000..02e0433e --- /dev/null +++ b/diagram-editor/frontend/utils/update-template-schema.ts @@ -0,0 +1,166 @@ +import { isObject } from '@rjsf/utils'; +import { type DiagramEditorNode, isOperationNode } from '../nodes'; +import type { DiagramOperation, SectionTemplate } from '../types/api'; +import { pointerSegment, schemaDocument, withinField } from './schema-types'; + +type Schema = Parameters[0]; + +export function updateTemplateSchema( + templateId: string, + config_schema: SectionTemplate['config_schema'], + rename: { from: string; to: string } | undefined, + editedNodes: DiagramEditorNode[], + mainNodes: DiagramEditorNode[], + templates: Record, + drafts: Record, +) { + const template = templates[templateId]; + const updated = { + ...templates, + [templateId]: { ...template, config_schema }, + }; + const removedNames: string[] = []; + const removedFields: string[] = []; + function compare(before: Schema, after: Schema, parent = '') { + if (before === after) return; + const next = schemaDocument(after); + // References and alternatives can still expose the same nested fields. + if ( + parent && + ((!next.type && !next.properties) || + [ + '$ref', + 'allOf', + 'anyOf', + 'oneOf', + 'if', + 'dependencies', + 'dependentSchemas', + ].some((key) => key in next)) + ) + return; + const fields = new Map(Object.entries(next.properties ?? {})); + for (const [name, field] of Object.entries( + schemaDocument(before).properties ?? {}, + )) { + const pointer = `${parent}/${pointerSegment(name)}`; + const moved = !parent && name === rename?.from; + const replacement = fields.get(moved ? rename.to : name); + if (!parent && (moved || replacement === undefined)) + removedNames.push(name); + if (replacement === undefined) removedFields.push(pointer); + else compare(field, replacement, pointer); + } + } + compare(template.config_schema, config_schema); + if (!removedNames.length && !removedFields.length) + return { edited: editedNodes, main: mainNodes, templates: updated }; + const oldPath = rename ? `/${pointerSegment(rename.from)}` : ''; + const newPath = rename ? `/${pointerSegment(rename.to)}` : ''; + let error: string | undefined; + + function migrate( + op: DiagramOperation, + inside: boolean, + location: string, + nodeId?: string, + ): DiagramOperation { + if (op.type !== 'node' && op.type !== 'script' && op.type !== 'section') + return op; + const instance = op.type === 'section' && op.template === templateId; + if ( + instance && + removedNames.length && + nodeId && + `section:${nodeId}:config` in drafts + ) { + error = `Finish editing the config for “${location}” before changing its properties.`; + return op; + } + const within = (path: string, prefix: string) => + instance && withinField(path, prefix); + const entries = Object.entries(op.config_bindings ?? {}); + const config = instance && isObject(op.config) ? op.config : {}; + const keys = Object.keys(config); + const hasValue = removedNames.some((key) => keys.includes(key)); + const movesValue = rename && keys.includes(rename.from); + if ( + rename && + (movesValue || entries.some(([path]) => within(path, oldPath))) && + (keys.includes(rename.to) || + entries.some(([path]) => within(path, newPath))) + ) { + error = `“${rename.to}” already has a value or binding in “${location}”.`; + return op; + } + let result: DiagramOperation = op; + if (hasValue) { + const rest = { ...config }; + for (const key of removedNames) delete rest[key]; + result = { + ...op, + config: movesValue + ? { ...rest, [rename.to]: config[rename.from] } + : rest, + }; + } + const bindings = new Map(entries); + let changed = false; + for (const [path, property] of entries) { + const sourceMoved = inside && property === rename?.from; + const moved = rename && within(path, oldPath); + const deleted = + (inside && !sourceMoved && removedNames.includes(property)) || + removedFields.some((prefix) => within(path, prefix)); + if (!sourceMoved && !moved && !deleted) continue; + bindings.delete(path); + if (!deleted && rename) + bindings.set( + moved ? newPath + path.slice(oldPath.length) : path, + sourceMoved ? rename.to : property, + ); + changed = true; + } + if (changed) + result = { + ...result, + config_bindings: bindings.size + ? Object.fromEntries(bindings) + : undefined, + }; + return result; + } + + // Open graphs store scope children as separate nodes. Saved templates nest them in ops. + function graph(nodes: DiagramEditorNode[], inside: boolean) { + return nodes.map((node) => { + if (!isOperationNode(node)) return node; + const { op, namespace, opId } = node.data; + const location = [inside && templateId, namespace, opId] + .filter(Boolean) + .join('/'); + const next = migrate(op, inside, location, node.id); + return next === op ? node : { ...node, data: { ...node.data, op: next } }; + }); + } + + function stored(ops: SectionTemplate['ops'], parent: string) { + const result = { ...ops }; + for (const [id, op] of Object.entries(ops)) { + const location = `${parent}/${id}`; + result[id] = + op.type === 'scope' + ? { ...op, ops: stored(op.ops, location) } + : migrate(op, false, location); + } + return result; + } + + const edited = graph(editedNodes, true); + const main = graph(mainNodes, false); + for (const [id, template] of Object.entries(templates)) { + if (id !== templateId) + updated[id] = { ...template, ops: stored(template.ops, id) }; + } + return error ?? { edited, main, templates: updated }; +} diff --git a/diagram-editor/jest-setup.ts b/diagram-editor/jest-setup.ts index 600b9be0..ae9dc577 100644 --- a/diagram-editor/jest-setup.ts +++ b/diagram-editor/jest-setup.ts @@ -1,5 +1,11 @@ import '@testing-library/jest-dom'; +// RJSF clones JSON values with the browser's structuredClone API. +if (!globalThis.structuredClone) { + const { serialize, deserialize } = jest.requireActual('node:v8'); + globalThis.structuredClone = (value) => deserialize(serialize(value)); +} + // jsdom has no layout engine and so no ResizeObserver. if (!globalThis.ResizeObserver) { globalThis.ResizeObserver = class { diff --git a/diagram-editor/jest.config.js b/diagram-editor/jest.config.js index a6804d98..45fd32bb 100644 --- a/diagram-editor/jest.config.js +++ b/diagram-editor/jest.config.js @@ -7,6 +7,10 @@ export default { testEnvironment: 'jsdom', transform: { ...tsJestTransformCfg, + '^.+\\.js$': ['ts-jest', { tsconfig: { allowJs: true }, diagnostics: false }], }, + // Use the same MUI exports as the browser and compile RJSF's ESM dependencies. + moduleNameMapper: { '^@rjsf/mui$': '/node_modules/@rjsf/mui/lib/index.js' }, + transformIgnorePatterns: ['node_modules/(?!\\.pnpm/|@x0k/json-schema-merge/|@rjsf/mui/)'], setupFilesAfterEnv: ['./jest-setup.ts'], }; diff --git a/diagram-editor/package.json b/diagram-editor/package.json index cd65dbaf..04f4a506 100644 --- a/diagram-editor/package.json +++ b/diagram-editor/package.json @@ -32,10 +32,15 @@ "@emotion/styled": "^11.14.0", "@fontsource/roboto": "^5.2.5", "@material-symbols/font-400": "^0.31.9", + "@mui/icons-material": "7.1.0", "@mui/material": "^7.1.0", + "@rjsf/core": "6.11.1", + "@rjsf/mui": "6.11.1", + "@rjsf/utils": "6.11.1", + "@rjsf/validator-ajv8": "6.11.1", "@uiw/react-codemirror": "^4.25.9", "@xyflow/react": "^12.6.1", - "ajv": "^8.17.1", + "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "cel-js": "^0.7.1", "fast-deep-equal": "^3.1.3", diff --git a/diagram-editor/server/api/executor.rs b/diagram-editor/server/api/executor.rs index 427df1c9..1c9a04c1 100644 --- a/diagram-editor/server/api/executor.rs +++ b/diagram-editor/server/api/executor.rs @@ -15,11 +15,15 @@ use bevy_ecs::{prelude::Entity, schedule::IntoScheduleConfigs}; #[cfg(feature = "router")] use crossflow::TracedEventKind; use crossflow::{ - Diagram, DiagramElementRegistry, DiagramError, DiagramErrorCode, DiagramOperation, - InferenceBoundaryConditions, MetadataAccess, Outcome, PortRef, RequestExt, TracedEvent, trace, + Diagram, DiagramElementMetadata, DiagramElementRegistry, DiagramError, DiagramErrorCode, + DiagramOperation, InferenceBoundaryConditions, MetadataAccess, Outcome, PortRef, RequestExt, + TracedEvent, trace, }; use serde::{Deserialize, Serialize}; +use serde_json::Value; use std::{ + borrow::Cow, + cell::OnceCell, collections::HashMap, error::Error, sync::{Arc, Mutex}, @@ -262,11 +266,14 @@ fn check_connections( .flat_map(|connection| connection.ports().cloned()), ) }); + let metadata = OnceCell::new(); let results = request .connections .into_iter() .map(|connection| match &inference { - Ok(inference) => check_connection(registry, connection, inference), + Ok(inference) => { + check_connection(registry, &request.diagram, connection, inference, &metadata) + } Err(error) => CompatibilityResult::terminal( connection.id, CompatibilityStatus::Unknown, @@ -279,8 +286,10 @@ fn check_connections( fn check_connection( registry: &DiagramElementRegistry, + diagram: &Diagram, connection: CompatibilityConnection, inference: &HashMap>>, + metadata: &OnceCell, ) -> CompatibilityResult { let mut focus_ports: Vec<_> = connection.ports().collect(); focus_ports.sort(); @@ -292,6 +301,13 @@ fn check_connection( "No ports were provided for compatibility checking", ); } + let source_declared = declared_port_schema(diagram, connection.source_port.as_ref()); + let target_declared = declared_port_schema(diagram, connection.target_port.as_ref()); + // A declared endpoint does not depend on inference inside its template. + focus_ports.retain(|p| { + !(source_declared.is_some() && Some(*p) == connection.source_port.as_ref() + || target_declared.is_some() && Some(*p) == connection.target_port.as_ref()) + }); let mut unknown = None; for inferred in focus_ports.iter().flat_map(|port| &inference[*port]) { match inferred { @@ -336,30 +352,41 @@ fn check_connection( } } - let port_types = |port: &Option| { + let effective = |port: &Option, declared, source| { + if let Some(schema) = declared { + let messages = metadata.get_or_init(|| registry.metadata()).messages(); + return vec![(PortType::declared(schema, messages, registry, source), true)]; + } port.iter() - .flat_map(|port| &inference[port]) - .filter_map(|result| result.as_ref().ok().copied()) - .collect::>() - }; - let source_types = port_types(&connection.source_port); - let target_types = port_types(&connection.target_port); - let type_name = |message_type| { - registry - .message_type_name(message_type) - .ok() - .map(ToOwned::to_owned) + .flat_map(|p| &inference[p]) + .filter_map(|r| r.as_ref().ok()) + .map(|native| { + let (i, certain) = *native; + ( + PortType { + name: registry.message_type_name(i).ok(), + native_types: Cow::Borrowed(std::slice::from_ref(native)), + schema: registry.message_schema(i).map(|s| s.as_value()), + structural: false, + }, + certain, + ) + }) + .collect() }; + let source_types = effective(&connection.source_port, source_declared, true); + let target_types = effective(&connection.target_port, target_declared, false); + let type_name = |port: &PortType| port.name.map(str::to_owned); // A section output can forward several internal producers. Check each real // type; an unresolved producer must not hide a proven mismatch in another. let mut reason = "All source message types can be delivered to the target".to_string(); - for &(source_type, source_certain) in &source_types { - for &(target_type, target_certain) in &target_types { - if !source_certain || !target_certain { + for (source_type, source_certain) in &source_types { + for (target_type, target_certain) in &target_types { + if !*source_certain || !*target_certain { continue; } - match can_connect_message_types(registry, source_type, target_type) { + match source_type.delivery_to(target_type, registry) { Ok(Some(message)) => { if source_types.len() == 1 && target_types.len() == 1 { reason = message; @@ -385,14 +412,14 @@ fn check_connection( ); } Err(error) => { - unknown.get_or_insert((error.to_string(), false)); + unknown.get_or_insert(error); } } } } - let type_names = |types: &[(usize, bool)]| { - let mut names: Vec<_> = types.iter().filter_map(|(ty, _)| type_name(*ty)).collect(); + let type_names = |types: &[(PortType, bool)]| { + let mut names: Vec<_> = types.iter().filter_map(|(ty, _)| type_name(ty)).collect(); names.sort(); names.dedup(); (!names.is_empty()).then(|| names.join(" | ")) @@ -440,6 +467,149 @@ fn check_connection( ) } +struct PortType<'a> { + name: Option<&'a str>, + // Registry index and whether that representation guarantees the declared schema. + native_types: Cow<'a, [(usize, bool)]>, + schema: Option<&'a Value>, + structural: bool, +} + +impl<'a> PortType<'a> { + fn declared( + schema: &'a Value, + messages: &[crossflow::MessageMetadata], + registry: &DiagramElementRegistry, + source: bool, + ) -> Self { + let reference = schema.get("$ref"); + let types = &schema["type"]; + let types = types + .as_array() + .map_or(std::slice::from_ref(types), Vec::as_slice); + let name = ["title", "type", "$ref"] + .into_iter() + .find_map(|k| schema[k].as_str()) + .unwrap_or("declared schema"); + let mut ids = Vec::new(); + for (i, message) in messages.iter().enumerate() { + let Some(native) = message.schema().as_ref().map(|s| s.as_value()) else { + continue; + }; + // Match a named type by its registry reference, and scalar declarations by + // the native representations that can carry their advertised values. + let matches_type = match reference { + Some(r) => native.get("$ref") == Some(r), + None => { + matches!( + native["type"].as_str(), + Some("boolean" | "integer" | "number" | "string" | "null") + ) && types.contains(&native["type"]) + } + }; + if !matches_type { + continue; + } + let coverage = if native == schema { + Some(true) + } else if source { + registry.message_schemas_compatible(schema, native) + } else { + registry.message_schemas_compatible(native, schema) + }; + if coverage != Some(false) { + ids.push((i, coverage == Some(true))); + } + } + if reference.is_some() && ids.len() > 1 { + // A shared schema reference cannot identify a particular native conversion. + ids.clear(); + } + Self { + name: Some(name), + structural: reference.is_none() || ids.is_empty(), + native_types: Cow::Owned(ids), + schema: Some(schema), + } + } + + fn delivery_to( + &self, + target: &Self, + registry: &DiagramElementRegistry, + ) -> Result, (String, bool)> { + let delivery = |from, to| { + can_connect_message_types(registry, from, to).map_err(|err| (err.to_string(), false)) + }; + let sources = self.native_types.as_ref(); + let targets = target.native_types.as_ref(); + if let Some(&(index, _)) = sources.iter().find(|id| id.1 && targets.contains(id)) { + return delivery(index, index); + } + let mut possible = false; + for &(source, source_certain) in sources { + for &(dest, target_certain) in targets { + if let Some(reason) = delivery(source, dest)? { + if source_certain && target_certain { + return Ok(Some(reason)); + } + possible = true; + } + } + } + let compatible = if self.structural || target.structural { + self.schema + .zip(target.schema) + .and_then(|(s, t)| registry.message_schemas_compatible(s, t)) + } else { + Some(false) + }; + match compatible { + Some(true) => Ok(Some("The source messages satisfy the target schema".into())), + Some(false) if !possible => Ok(None), + _ => Err(( + "Cannot determine whether the port schemas match".into(), + true, + )), + } + } +} + +fn declared_port_schema<'a>(diagram: &'a Diagram, port: Option<&PortRef>) -> Option<&'a Value> { + use crossflow::{ + BuildDiagramOperation, Identifier, OperationName, OperationRef, OutputRef, SectionProvider, + }; + let template = |namespaces: &[OperationName], id: &OperationName| { + let mut ops = diagram.ops.clone(); + for namespace in namespaces { + let parent = ops.get(namespace)?; + ops = parent.child_operations(&diagram.templates).ok()??; + } + let DiagramOperation::Section(section) = ops.get(id)?.as_ref() else { + return None; + }; + let SectionProvider::Template(id) = §ion.provider else { + return None; + }; + diagram.templates.get(id) + }; + let schema = match port? { + PortRef::Input(OperationRef::Named(port)) => { + let section = template(&port.namespaces, port.exposed_namespace.as_ref()?)?; + section.input_schemas.get(&port.name) + } + PortRef::Output(OutputRef::Named(port)) => match &port.key[..] { + [Identifier::Name(key), Identifier::Name(name)] if key.as_ref() == "connect" => { + let section = template(&port.namespaces, &port.operation)?; + section.output_schemas.get(name) + } + _ => None, + }, + _ => return None, + }?; + Some(schema.as_value()) +} + fn is_missing_context_error(error: &DiagramError) -> bool { matches!( &error.code, diff --git a/diagram-editor/wasm/src/executor.rs b/diagram-editor/wasm/src/executor.rs index 8ccbcf0d..186dc3c4 100644 --- a/diagram-editor/wasm/src/executor.rs +++ b/diagram-editor/wasm/src/executor.rs @@ -113,6 +113,7 @@ mod tests { let add_op = Arc::new(DiagramOperation::Node(NodeSchema { builder: "add3".into(), config: serde_json::Value::Null.into(), + config_bindings: Default::default(), next: NextOperation::Builtin { builtin: crossflow::BuiltinTarget::Terminate, }, @@ -141,6 +142,7 @@ mod tests { let add_op = Arc::new(DiagramOperation::Node(NodeSchema { builder: "add3".into(), config: serde_json::Value::Null.into(), + config_bindings: Default::default(), next: NextOperation::Builtin { builtin: crossflow::BuiltinTarget::Terminate, }, diff --git a/diagram.schema.json b/diagram.schema.json index 2fee07e4..04b12030 100644 --- a/diagram.schema.json +++ b/diagram.schema.json @@ -654,6 +654,13 @@ "type": "string" }, "config": true, + "config_bindings": { + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -733,6 +740,12 @@ } ] }, + "Schema": { + "type": [ + "object", + "boolean" + ] + }, "ScopeSchema": { "description": "Create a scope which will function like its own encapsulated workflow\nwithin the paren workflow. Each message that enters a scope will trigger\na new independent session for that scope to begin running with the incoming\nmessage itself being the input message of the scope. When multiple sessions\nfor the same scope are running, they cannot see or interfere with each other.\n\nOnce a session terminates, the scope will send the terminating message as\nits output. Scopes can use the `stream_out` operation to stream messages out\nto the parent workflow while running.\n\nScopes have two common uses:\n* isolate - Prevent simultaneous runs of the same workflow components\n (especially buffers) from interfering with each other.\n* race - Run multiple branches simultaneously inside the scope and race\n them against each ohter. The first branch that reaches the scope's\n terminate operation \"wins\" the race, and only its output will continue\n on in the parent workflow. All other branches will be disposed.\n\n# Examples\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"start\": \"approach_door\",\n \"ops\": {\n \"approach_door\": {\n \"type\": \"scope\",\n \"start\": \"begin\",\n \"ops\": {\n \"begin\": {\n \"type\": \"fork_clone\",\n \"next\": [\n \"move_to_door\",\n \"detect_door_proximity\"\n ]\n },\n \"move_to_door\": {\n \"type\": \"node\",\n \"builder\": \"move\",\n \"config\": {\n \"place\": \"L1_north_lobby_outside\"\n },\n \"next\": { \"builtin\" : \"terminate\" }\n },\n \"detect_proximity\": {\n \"type\": \"node\",\n \"builder\": \"detect_proximity\",\n \"config\": {\n \"type\": \"door\",\n \"name\": \"L1_north_lobby\"\n },\n \"next\": { \"builtin\" : \"terminate\" }\n }\n },\n \"next\": { \"builtin\" : \"try_open_door\" }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```", "type": "object", @@ -844,6 +857,13 @@ "config": { "description": "Configured data to pass into the function that `run` refers to. This will\nbe passed in as a keyword argument named `config`." }, + "config_bindings": { + "description": "JSON pointers within config linked to properties of the enclosing template.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, "display_text": { "description": "Override for text that should be displayed for an operation within an\neditor.", "type": [ @@ -909,8 +929,12 @@ "description": "Connect the request to a registered section.\n\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"builder\": \"my_section_builder\",\n \"connect\": {\n \"my_section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```\n\nCustom sections can also be created via templates\n```\n# crossflow::Diagram::from_json_str(r#\"\n{\n \"version\": \"0.1.0\",\n \"templates\": {\n \"my_template\": {\n \"inputs\": [\"section_input\"],\n \"outputs\": [\"section_output\"],\n \"buffers\": [],\n \"ops\": {\n \"section_input\": {\n \"type\": \"node\",\n \"builder\": \"my_node\",\n \"next\": \"section_output\"\n }\n }\n }\n },\n \"start\": \"section_op\",\n \"ops\": {\n \"section_op\": {\n \"type\": \"section\",\n \"template\": \"my_template\",\n \"connect\": {\n \"section_output\": { \"builtin\": \"terminate\" }\n }\n }\n }\n}\n# \"#)?;\n# Ok::<_, serde_json::Error>(())\n```", "type": "object", "properties": { - "config": { - "default": null + "config": true, + "config_bindings": { + "type": "object", + "additionalProperties": { + "type": "string" + } }, "connect": { "type": "object", @@ -977,6 +1001,24 @@ "$ref": "#/$defs/InputRemapping", "default": [] }, + "config_schema": { + "description": "The JSON Schema of a section instance's configuration.", + "anyOf": [ + { + "$ref": "#/$defs/Schema" + }, + { + "type": "null" + } + ] + }, + "input_schemas": { + "description": "JSON Schemas for the template's exposed input ports.", + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/Schema" + } + }, "inputs": { "description": "These are the inputs that the section is exposing for its sibling\noperations to send outputs into.", "$ref": "#/$defs/InputRemapping", @@ -989,6 +1031,13 @@ "$ref": "#/$defs/DiagramOperation" } }, + "output_schemas": { + "description": "JSON Schemas for the template's exposed output ports.", + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/Schema" + } + }, "outputs": { "description": "These are the outputs that the section is exposing so you can connect\nthem into siblings of the section.", "type": "array", diff --git a/handbook/src/diagram-section-templates.md b/handbook/src/diagram-section-templates.md index 7dc4c94a..974ed360 100644 --- a/handbook/src/diagram-section-templates.md +++ b/handbook/src/diagram-section-templates.md @@ -13,7 +13,7 @@ Whereas section builders have static message types for their inputs and outputs, ### Section Template Schema -The [`SectionTemplate`][SectionTemplate] schema consists of four fields: +The [`SectionTemplate`][SectionTemplate] schema describes the graph and its interface: * [`"inputs"`][SectionTemplate::inputs]: an [input remapping] that says which input slots inside the section should be exposed to operations that are outside of the section. These are similar to the `InputSlot<_>` fields of a [section builder](./diagram-section-builders.md#closure). @@ -22,6 +22,24 @@ The [`SectionTemplate`][SectionTemplate] schema consists of four fields: None of the operations inside `"ops"` can use any of these names as a key. * [`"ops"`][SectionTemplate::ops]: a dictionary of operation instances that exist inside this section, along with information about how they connect to each other. The syntax of this section is exactly the same as the `"ops"` section of regular [diagrams](./diagram-syntax.md#operations) and scope operations. +* `config_schema` is an optional JSON Schema for the configuration supplied by each instance. +* `input_schemas` and `output_schemas` optionally declare schemas by exposed port name. The editor uses these declarations to check connections. Ports without declarations use the existing type inference. + +### Configuring an Instance + +For example, a template can expose a required integer named `factor` through this configuration schema. + +```json +{ + "type": "object", + "properties": { "factor": { "type": "integer" } }, + "required": ["factor"] +} +``` + +Bindings refer to names in the configuration schema’s top-level `properties`. A property can itself use a registered type or alternatives. In the editor, add `factor` in the Template panel. Open the multiply node inside the template and use the link beside its numeric config to select `factor`. The editor saves `"config_bindings": { "": "factor" }` on that node. The empty JSON Pointer addresses its entire numeric config. A pointer such as `"/scale"` addresses a field inside an object config. + +Give one section instance `"config": { "factor": 3 }` and another `"config": { "factor": 5 }`. The same template now multiplies an input of 2 by 3 or 5, producing 6 or 10. The executor validates each instance when building the diagram. For an omitted optional property it uses the property's declared default, or keeps the node's own value if there is no default. ### Referencing Section Templates diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 52e36600..8df885fb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -47,9 +47,24 @@ importers: '@material-symbols/font-400': specifier: ^0.31.9 version: 0.31.9 + '@mui/icons-material': + specifier: 7.1.0 + version: 7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0) '@mui/material': specifier: ^7.1.0 version: 7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + '@rjsf/core': + specifier: 6.11.1 + version: 6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0) + '@rjsf/mui': + specifier: 6.11.1 + version: 6.11.1(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/icons-material@7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@rjsf/core@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0))(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0) + '@rjsf/utils': + specifier: 6.11.1 + version: 6.11.1(react@19.1.0) + '@rjsf/validator-ajv8': + specifier: 6.11.1 + version: 6.11.1(@rjsf/utils@6.11.1(react@19.1.0)) '@uiw/react-codemirror': specifier: ^4.25.9 version: 4.25.9(@babel/runtime@7.27.6)(@codemirror/autocomplete@6.20.1)(@codemirror/language@6.12.3)(@codemirror/lint@6.9.5)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.41.1)(codemirror@6.0.2)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) @@ -57,11 +72,11 @@ importers: specifier: ^12.6.1 version: 12.6.4(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) ajv: - specifier: ^8.17.1 - version: 8.17.1 + specifier: ^8.20.0 + version: 8.20.0 ajv-formats: specifier: ^3.0.1 - version: 3.0.1(ajv@8.17.1) + version: 3.0.1(ajv@8.20.0) cel-js: specifier: ^0.7.1 version: 0.7.1 @@ -789,6 +804,17 @@ packages: '@mui/core-downloads-tracker@7.1.0': resolution: {integrity: sha512-E0OqhZv548Qdc0PwWhLVA2zmjJZSTvaL4ZhoswmI8NJEC1tpW2js6LLP827jrW9MEiXYdz3QS6+hask83w74yQ==} + '@mui/icons-material@7.1.0': + resolution: {integrity: sha512-1mUPMAZ+Qk3jfgL5ftRR06ATH/Esi0izHl1z56H+df6cwIlCWG66RXciUqeJCttbOXOQ5y2DCjLZI/4t3Yg3LA==} + engines: {node: '>=14.0.0'} + peerDependencies: + '@mui/material': ^7.1.0 + '@types/react': ^17.0.0 || ^18.0.0 || ^19.0.0 + react: ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@mui/material@7.1.0': resolution: {integrity: sha512-ahUJdrhEv+mCp4XHW+tHIEYzZMSRLg8z4AjUOsj44QpD1ZaMxQoVOG2xiHvLFdcsIPbgSRx1bg1eQSheHBgvtg==} engines: {node: '>=14.0.0'} @@ -884,6 +910,37 @@ packages: '@popperjs/core@2.11.8': resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==} + '@rjsf/core@6.11.1': + resolution: {integrity: sha512-2kH39lspUUQf552l+vSTj9vnwdv1gSOyDKqSDmFuTo16+92zbJ381knrQpk3KKowjp/sbxu4qPiBptgXH6i4UQ==} + engines: {node: '>=20'} + peerDependencies: + '@rjsf/utils': ^6.11.1 + react: '>=18' + + '@rjsf/mui@6.11.1': + resolution: {integrity: sha512-CzPi4qel4xfCN0uJvfPSHNW1tnl1kKDT+oRz3YHs7fyd/GcKabr3iyJxLXnDWdSCVAiqUYFjc/A8wh7cZ2nH1w==} + engines: {node: '>=20'} + peerDependencies: + '@emotion/react': ^11.7.0 + '@emotion/styled': ^11.6.0 + '@mui/icons-material': ^7.0.0 || ^9.0.0 + '@mui/material': ^7.0.0 || ^9.0.0 + '@rjsf/core': ^6.11.1 + '@rjsf/utils': ^6.11.1 + react: '>=18' + + '@rjsf/utils@6.11.1': + resolution: {integrity: sha512-rHQ4jNkhws3YUjvM/6RyW78l0mVfnt6w2j3/giUcS5F0cendCLYykFuSnE2fQxBwmknv4ANMOugwXOgcIbfvnA==} + engines: {node: '>=20'} + peerDependencies: + react: '>=18' + + '@rjsf/validator-ajv8@6.11.1': + resolution: {integrity: sha512-LV7ibrep/kaRzkwzhLAmJY9SHOIZuX9fQO+0VCfm0FOGXneGU9xQEJvHft7R84uqtDTTQZqRq40HcQjqY0rsyw==} + engines: {node: '>=20'} + peerDependencies: + '@rjsf/utils': ^6.11.1 + '@rollup/pluginutils@5.1.4': resolution: {integrity: sha512-USm05zrsFxYLPdWWq+K3STlWiT/3ELn3RcV5hJMghpeAIhxfsUIg6mt12CBJBInWMV4VneoV7SfGv8xIwo2qNQ==} engines: {node: '>=14.0.0'} @@ -1396,6 +1453,9 @@ packages: '@webassemblyjs/wast-printer@1.14.1': resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==} + '@x0k/json-schema-merge@1.2.0': + resolution: {integrity: sha512-PeMfO7U8RrH4NfyxRPh0E9DN32FSFl7JsyG/IOI87YgQomK6kfNat2ETHCEX3S41AsoEfRTxiScUNkrd0mgbyw==} + '@xtuc/ieee754@1.2.0': resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} @@ -1457,8 +1517,8 @@ packages: peerDependencies: ajv: ^8.8.2 - ajv@8.17.1: - resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} ansi-escapes@4.3.2: resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==} @@ -2028,6 +2088,10 @@ packages: fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + fast-equals@6.4.1: + resolution: {integrity: sha512-qHLxdeRmasP83VXLGXCyUh7D2bo2WFI/IEB+T0WSf3mwuTD2A5F+HQQmeF+UXCfuLPmqUNYcFJjwAN9JabA6+Q==} + engines: {node: '>=6.0.0'} + fast-glob@3.3.3: resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} engines: {node: '>=8.6.0'} @@ -2041,6 +2105,9 @@ packages: fast-uri@3.0.6: resolution: {integrity: sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==} + fast-uri@4.2.3: + resolution: {integrity: sha512-I1PXwP5eAhlNlcdpjt9CgB59op2ZvZfxw+BkqGFVIUOgNpCVTcTqp3HhTX7brxj5vsip+nSY4nTvff+eIA76hg==} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -2558,6 +2625,10 @@ packages: jsonfile@6.1.0: resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==} + jsonpointer@5.0.1: + resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} + engines: {node: '>=0.10.0'} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -2631,6 +2702,24 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + markdown-to-jsx@9.10.6: + resolution: {integrity: sha512-vvd4cMAAK6RDCzklzRYykG8Tos1Wyid8IoxenyiSAnGb1JIX2fTzn6MuU5QBu9Kb4BdjOCnKlbs84NQRVsaaVA==} + engines: {node: '>= 18'} + peerDependencies: + react: '>= 16.0.0' + react-native: '*' + solid-js: '>=1.0.0' + vue: '>=3.0.0' + peerDependenciesMeta: + react: + optional: true + react-native: + optional: true + solid-js: + optional: true + vue: + optional: true + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -4284,6 +4373,14 @@ snapshots: '@mui/core-downloads-tracker@7.1.0': {} + '@mui/icons-material@7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0)': + dependencies: + '@babel/runtime': 7.27.6 + '@mui/material': 7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + react: 19.1.0 + optionalDependencies: + '@types/react': 19.1.5 + '@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)': dependencies: '@babel/runtime': 7.27.1 @@ -4377,6 +4474,41 @@ snapshots: '@popperjs/core@2.11.8': {} + '@rjsf/core@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0)': + dependencies: + '@rjsf/utils': 6.11.1(react@19.1.0) + markdown-to-jsx: 9.10.6(react@19.1.0) + react: 19.1.0 + transitivePeerDependencies: + - react-native + - solid-js + - vue + + '@rjsf/mui@6.11.1(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/icons-material@7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@rjsf/core@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0))(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0)': + dependencies: + '@emotion/react': 11.14.0(@types/react@19.1.5)(react@19.1.0) + '@emotion/styled': 11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0) + '@mui/icons-material': 7.1.0(@mui/material@7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(@types/react@19.1.5)(react@19.1.0) + '@mui/material': 7.1.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@emotion/styled@11.14.0(@emotion/react@11.14.0(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react@19.1.0))(@types/react@19.1.5)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + '@rjsf/core': 6.11.1(@rjsf/utils@6.11.1(react@19.1.0))(react@19.1.0) + '@rjsf/utils': 6.11.1(react@19.1.0) + react: 19.1.0 + + '@rjsf/utils@6.11.1(react@19.1.0)': + dependencies: + '@x0k/json-schema-merge': 1.2.0 + fast-equals: 6.4.1 + fast-uri: 4.2.3 + jsonpointer: 5.0.1 + react: 19.1.0 + react-is: 18.3.1 + + '@rjsf/validator-ajv8@6.11.1(@rjsf/utils@6.11.1(react@19.1.0))': + dependencies: + '@rjsf/utils': 6.11.1(react@19.1.0) + ajv: 8.20.0 + ajv-formats: 2.1.1(ajv@8.20.0) + '@rollup/pluginutils@5.1.4(rollup@4.43.0)': dependencies: '@types/estree': 1.0.8 @@ -4901,6 +5033,10 @@ snapshots: '@webassemblyjs/ast': 1.14.1 '@xtuc/long': 4.2.2 + '@x0k/json-schema-merge@1.2.0': + dependencies: + '@types/json-schema': 7.0.15 + '@xtuc/ieee754@1.2.0': {} '@xtuc/long@4.2.2': {} @@ -4947,20 +5083,20 @@ snapshots: transitivePeerDependencies: - supports-color - ajv-formats@2.1.1(ajv@8.17.1): + ajv-formats@2.1.1(ajv@8.20.0): optionalDependencies: - ajv: 8.17.1 + ajv: 8.20.0 - ajv-formats@3.0.1(ajv@8.17.1): + ajv-formats@3.0.1(ajv@8.20.0): optionalDependencies: - ajv: 8.17.1 + ajv: 8.20.0 - ajv-keywords@5.1.0(ajv@8.17.1): + ajv-keywords@5.1.0(ajv@8.20.0): dependencies: - ajv: 8.17.1 + ajv: 8.20.0 fast-deep-equal: 3.1.3 - ajv@8.17.1: + ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 fast-uri: 3.0.6 @@ -5560,6 +5696,8 @@ snapshots: fast-deep-equal@3.1.3: {} + fast-equals@6.4.1: {} + fast-glob@3.3.3: dependencies: '@nodelib/fs.stat': 2.0.5 @@ -5574,6 +5712,8 @@ snapshots: fast-uri@3.0.6: {} + fast-uri@4.2.3: {} + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -6324,6 +6464,8 @@ snapshots: optionalDependencies: graceful-fs: 4.2.11 + jsonpointer@5.0.1: {} + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -6388,6 +6530,10 @@ snapshots: dependencies: tmpl: 1.0.5 + markdown-to-jsx@9.10.6(react@19.1.0): + optionalDependencies: + react: 19.1.0 + math-intrinsics@1.1.0: {} memfs@4.17.2: @@ -6766,9 +6912,9 @@ snapshots: schema-utils@4.3.2: dependencies: '@types/json-schema': 7.0.15 - ajv: 8.17.1 - ajv-formats: 2.1.1(ajv@8.17.1) - ajv-keywords: 5.1.0(ajv@8.17.1) + ajv: 8.20.0 + ajv-formats: 2.1.1(ajv@8.20.0) + ajv-keywords: 5.1.0(ajv@8.20.0) semver@6.3.1: {} diff --git a/src/diagram/node_schema.rs b/src/diagram/node_schema.rs index 265a5da9..a393faa4 100644 --- a/src/diagram/node_schema.rs +++ b/src/diagram/node_schema.rs @@ -20,9 +20,9 @@ use serde::{Deserialize, Serialize}; use std::{collections::HashMap, sync::Arc}; use super::{ - BuildDiagramOperation, BuildStatus, BuilderContext, BuilderId, DiagramErrorCode, - InferenceContext, JsonMessage, MissingStream, NextOperation, OperationName, Operations, - Templates, TraceInfo, TraceSettings, is_default, + BuildDiagramOperation, BuildStatus, BuilderContext, BuilderId, ConfigBindings, + DiagramErrorCode, InferenceContext, JsonMessage, MissingStream, NextOperation, OperationName, + Operations, Templates, TraceInfo, TraceSettings, is_default, }; /// Create an operation that that takes an input message and produces an @@ -73,6 +73,9 @@ pub struct NodeSchema { pub builder: BuilderId, #[serde(default, skip_serializing_if = "is_default")] pub config: Arc, + /// JSON pointers within config linked to properties of the enclosing template. + #[serde(default, skip_serializing_if = "ConfigBindings::is_empty")] + pub config_bindings: ConfigBindings, pub next: NextOperation, #[serde(default, skip_serializing_if = "is_default")] pub stream_out: HashMap, @@ -86,6 +89,9 @@ impl BuildDiagramOperation for NodeSchema { id: &OperationName, ctx: &mut BuilderContext, ) -> Result { + if !self.config_bindings.is_empty() { + return Err(super::SectionError::UnresolvedConfigBindings.into()); + } let node_registration = ctx.registry.get_node_registration(&self.builder)?; let mut node = node_registration.create_node(ctx.builder, (*self.config).clone())?; diff --git a/src/diagram/registration.rs b/src/diagram/registration.rs index 57566558..d34757c2 100644 --- a/src/diagram/registration.rs +++ b/src/diagram/registration.rs @@ -371,6 +371,51 @@ impl DiagramElementRegistry { self.messages.registration.get::() } + /// JSON schema of a registered message, for comparing it with a declared port. + pub fn message_schema(&self, index: usize) -> Option<&Schema> { + self.messages + .registration + .get_by_index(index) + .ok()? + .schema + .as_ref() + } + + pub(super) fn schema_with_definitions(&self, schema: &JsonMessage) -> JsonMessage { + let mut schema = schema.clone(); + if let Some(object) = schema.as_object_mut() { + object.entry("schemas").or_insert_with(|| { + JsonMessage::Object(self.messages.schema_generator.definitions().clone()) + }); + } + schema + } + + /// Whether all source messages satisfy the target schema. Partially overlapping + /// schemas and cases that cannot be decided statically return `None`. + pub fn message_schemas_compatible( + &self, + source: &JsonMessage, + target: &JsonMessage, + ) -> Option { + use jsonschema::canonical::{Containment, Satisfiability}; + let canonical = |schema| { + jsonschema::canonical::options() + .should_validate_formats(false) + .canonicalize(&self.schema_with_definitions(schema)) + .ok() + }; + let source = canonical(source)?; + let target = canonical(target)?; + if target.covers(&source).ok()? == Containment::Yes { + Some(true) + } else if source.intersect(&target).ok()?.satisfiability() == Satisfiability::No { + Some(false) + } else { + None + } + } + pub fn get_message_operations_by_index( &self, message_index: usize, diff --git a/src/diagram/script_schema.rs b/src/diagram/script_schema.rs index 9bc1afed..d71fb3fb 100644 --- a/src/diagram/script_schema.rs +++ b/src/diagram/script_schema.rs @@ -27,10 +27,11 @@ use std::{ }; use crate::{ - Async, BasicConnect, BuildDiagramOperation, BuildStatus, BuilderContext, ConnectIntoTarget, - DiagramErrorCode, DynInputSlot, DynOutput, DynamicallyNamedStream, InferenceContext, - IntoCallback, JsonMessage, NextOperation, Node, OperationName, Operations, ScriptMessage, - StreamOf, Templates, Text, TraceInfo, TraceSettings, TypeInfo, TypeMismatch, is_default, + Async, BasicConnect, BuildDiagramOperation, BuildStatus, BuilderContext, ConfigBindings, + ConnectIntoTarget, DiagramErrorCode, DynInputSlot, DynOutput, DynamicallyNamedStream, + InferenceContext, IntoCallback, JsonMessage, NextOperation, Node, OperationName, Operations, + ScriptMessage, StreamOf, Templates, Text, TraceInfo, TraceSettings, TypeInfo, TypeMismatch, + is_default, }; #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] @@ -44,6 +45,9 @@ pub struct ScriptSchema { /// be passed in as a keyword argument named `config`. #[serde(default, skip_serializing_if = "is_default")] pub config: Arc, + /// JSON pointers within config linked to properties of the enclosing template. + #[serde(default, skip_serializing_if = "ConfigBindings::is_empty")] + pub config_bindings: ConfigBindings, /// The operation that the final output of this Python operation will be passed to pub next: NextOperation, /// Specify what happens if an error occurs during the script, such as an @@ -70,6 +74,9 @@ impl BuildDiagramOperation for ScriptSchema { id: &OperationName, ctx: &mut BuilderContext, ) -> Result { + if !self.config_bindings.is_empty() { + return Err(super::SectionError::UnresolvedConfigBindings.into()); + } let env = ctx.get_script_environment(&self.environment)?; let script = env.compile(&self.run, &self.config).map_err(|error| { DiagramErrorCode::ScriptCompileError { diff --git a/src/diagram/section_schema.rs b/src/diagram/section_schema.rs index 941b21e0..29c0228f 100644 --- a/src/diagram/section_schema.rs +++ b/src/diagram/section_schema.rs @@ -17,7 +17,7 @@ use std::{collections::HashMap, sync::Arc}; -use schemars::JsonSchema; +use schemars::{JsonSchema, Schema}; use serde::{Deserialize, Serialize}; use crate::{ @@ -26,13 +26,16 @@ use crate::{ use super::{ BuildDiagramOperation, BuildStatus, BuilderContext, BuilderId, DiagramElementRegistry, - DiagramErrorCode, DynInputSlot, DynOutput, MessageRegistrations, NamespacedOperation, - NextOperation, OperationName, OperationRef, Operations, RedirectConnection, Templates, - TraceInfo, TraceSettings, + DiagramErrorCode, DiagramOperation, DynInputSlot, DynOutput, MessageRegistrations, + NamespacedOperation, NextOperation, OperationName, OperationRef, Operations, + RedirectConnection, Templates, TraceInfo, TraceSettings, }; pub use crossflow_derive::Section; +/// Maps JSON pointers in an operation's config to properties of its enclosing template. +pub type ConfigBindings = std::collections::BTreeMap; + #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SectionProvider { @@ -99,8 +102,15 @@ pub enum SectionProvider { pub struct SectionSchema { #[serde(flatten)] pub provider: SectionProvider, - #[serde(default)] - pub config: Arc, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "serde_with::rust::unwrap_or_skip::deserialize" + )] + #[schemars(with = "JsonMessage")] + pub config: Option>, + #[serde(default, skip_serializing_if = "ConfigBindings::is_empty")] + pub config_bindings: ConfigBindings, #[serde(default)] pub connect: HashMap, #[serde(flatten)] @@ -113,13 +123,19 @@ impl BuildDiagramOperation for SectionSchema { id: &OperationName, ctx: &mut BuilderContext, ) -> Result { + if !self.config_bindings.is_empty() { + return Err(SectionError::UnresolvedConfigBindings.into()); + } match &self.provider { SectionProvider::Builder(section_builder) => { let section_registration = ctx.registry.get_section_registration(section_builder)?; let section = section_registration - .create_section(ctx.builder, (*self.config).clone())? + .create_section( + ctx.builder, + self.config.as_deref().cloned().unwrap_or_default(), + )? .into_slots(); // TODO(@mxgrey): Figure out how to automatically trace operations @@ -162,8 +178,9 @@ impl BuildDiagramOperation for SectionSchema { SectionProvider::Template(section_template) => { let section = ctx.templates.get_template(section_template)?; - for (child_id, op) in section.ops.iter() { - ctx.add_child_operation(id, child_id, op, section.ops.clone(), None, None); + let ops = section.configured_ops(self.config.as_deref(), ctx.registry)?; + for (child_id, op) in ops.iter() { + ctx.add_child_operation(id, child_id, op, ops.clone(), None, None); } section @@ -393,6 +410,15 @@ pub struct SectionBuffer { #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct SectionTemplate { + /// The JSON Schema of a section instance's configuration. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config_schema: Option, + /// JSON Schemas for the template's exposed input ports. + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub input_schemas: HashMap, + /// JSON Schemas for the template's exposed output ports. + #[serde(default, skip_serializing_if = "HashMap::is_empty")] + pub output_schemas: HashMap, /// These are the inputs that the section is exposing for its sibling /// operations to send outputs into. #[serde(default)] @@ -409,6 +435,98 @@ pub struct SectionTemplate { pub ops: Operations, } +impl SectionTemplate { + fn configured_ops( + &self, + config: Option<&JsonMessage>, + registry: &DiagramElementRegistry, + ) -> Result { + let Some(schema) = &self.config_schema else { + // Unresolved bindings, including those outside a template, fail when built. + return Ok(self.ops.clone()); + }; + let schema = registry.schema_with_definitions(schema.as_value()); + let validator = jsonschema::draft202012::options() + .should_validate_formats(false) + .build(&schema) + .map_err(|e| SectionError::InvalidConfig(e.to_string()))?; + let mut values = config.cloned().unwrap_or_else(|| serde_json::json!({})); + let properties = &schema["properties"]; + if let (Some(properties), Some(values)) = (properties.as_object(), values.as_object_mut()) { + let required = schema["required"].as_array(); + for (key, property) in properties { + if let Some(default) = property.get("default") + && !required.is_some_and(|keys| keys.iter().any(|k| k == key)) + { + values.entry(key).or_insert_with(|| default.clone()); + } + } + } + validator + .validate(&values) + .map_err(|e| SectionError::InvalidConfig(format!("#{}: {e}", e.instance_path())))?; + let mut ops = self.ops.clone(); + bind_config(&mut ops, &values, properties)?; + Ok(ops) + } +} + +fn bind_config( + ops: &mut Operations, + values: &JsonMessage, + properties: &JsonMessage, +) -> Result<(), SectionError> { + for op in Arc::make_mut(ops).values_mut() { + let op = Arc::make_mut(op); + let bindings = match op { + DiagramOperation::Node(node) => &mut node.config_bindings, + DiagramOperation::Script(script) => &mut script.config_bindings, + DiagramOperation::Section(section) => &mut section.config_bindings, + DiagramOperation::Scope(scope) => { + bind_config(&mut scope.ops, values, properties)?; + continue; + } + _ => continue, + }; + for (pointer, name) in std::mem::take(bindings) { + if properties.get(name.as_ref()).is_none() { + return Err(SectionError::UnknownConfigProperty(name)); + } + if let Some(value) = values.get(name.as_ref()) { + let config = match op { + DiagramOperation::Node(node) => &mut node.config, + DiagramOperation::Script(script) => &mut script.config, + DiagramOperation::Section(section) => { + section.config.get_or_insert_with(Default::default) + } + _ => unreachable!(), + }; + set_config_value(Arc::make_mut(config), &pointer, value.clone()) + .ok_or(SectionError::InvalidBinding(pointer))?; + } + } + } + Ok(()) +} + +fn set_config_value(config: &mut JsonMessage, pointer: &str, value: JsonMessage) -> Option<()> { + let mut field = config; + let mut tokens = pointer.split('/'); + if tokens.next() != Some("") { + return None; + } + for token in tokens { + let key = token.replace("~1", "/").replace("~0", "~"); + field = match field { + JsonMessage::Null | JsonMessage::Object(_) => &mut field[key], + JsonMessage::Array(array) => array.get_mut(key.parse::().ok()?)?, + _ => return None, + }; + } + *field = value; + Some(()) +} + /// This defines how sections remap their inner operations (inputs and buffers) /// to expose them to operations that are siblings to the section. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] @@ -474,6 +592,14 @@ impl InputRemapping { pub enum SectionError { #[error("operation has extra output [{0}] that is not in the section")] UnknownOutput(OperationName), + #[error("invalid section configuration: {0}")] + InvalidConfig(String), + #[error("unknown section configuration property [{0}]")] + UnknownConfigProperty(OperationName), + #[error("invalid configuration binding path [{0}]")] + InvalidBinding(String), + #[error("configuration bindings require an enclosing template with a configuration schema")] + UnresolvedConfigBindings, } #[cfg(test)]