feat(ui): improved node parsing (#3584)

- use `swagger-parser` to dereference openapi schema
- tidy vite plugins
- use mantine select for node add menu
This commit is contained in:
blessedcoolant 2023-06-26 17:38:23 +12:00 committed by GitHub
commit 9cfac4175f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 1018 additions and 265 deletions

View File

@ -0,0 +1,14 @@
import react from '@vitejs/plugin-react-swc';
import { visualizer } from 'rollup-plugin-visualizer';
import { PluginOption, UserConfig } from 'vite';
import eslint from 'vite-plugin-eslint';
import tsconfigPaths from 'vite-tsconfig-paths';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
export const commonPlugins: UserConfig['plugins'] = [
react(),
eslint(),
tsconfigPaths(),
visualizer() as unknown as PluginOption,
nodePolyfills(),
];

View File

@ -1,17 +1,9 @@
import react from '@vitejs/plugin-react-swc'; import { UserConfig } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer'; import { commonPlugins } from './common';
import { PluginOption, UserConfig } from 'vite';
import eslint from 'vite-plugin-eslint';
import tsconfigPaths from 'vite-tsconfig-paths';
export const appConfig: UserConfig = { export const appConfig: UserConfig = {
base: './', base: './',
plugins: [ plugins: [...commonPlugins],
react(),
eslint(),
tsconfigPaths(),
visualizer() as unknown as PluginOption,
],
build: { build: {
chunkSizeWarningLimit: 1500, chunkSizeWarningLimit: 1500,
}, },

View File

@ -1,19 +1,13 @@
import react from '@vitejs/plugin-react-swc';
import path from 'path'; import path from 'path';
import { visualizer } from 'rollup-plugin-visualizer'; import { UserConfig } from 'vite';
import { PluginOption, UserConfig } from 'vite';
import dts from 'vite-plugin-dts'; import dts from 'vite-plugin-dts';
import eslint from 'vite-plugin-eslint';
import tsconfigPaths from 'vite-tsconfig-paths';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'; import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
import { commonPlugins } from './common';
export const packageConfig: UserConfig = { export const packageConfig: UserConfig = {
base: './', base: './',
plugins: [ plugins: [
react(), ...commonPlugins,
eslint(),
tsconfigPaths(),
visualizer() as unknown as PluginOption,
dts({ dts({
insertTypesEntry: true, insertTypesEntry: true,
}), }),

View File

@ -53,6 +53,7 @@
] ]
}, },
"dependencies": { "dependencies": {
"@apidevtools/swagger-parser": "^10.1.0",
"@chakra-ui/anatomy": "^2.1.1", "@chakra-ui/anatomy": "^2.1.1",
"@chakra-ui/icons": "^2.0.19", "@chakra-ui/icons": "^2.0.19",
"@chakra-ui/react": "^2.7.1", "@chakra-ui/react": "^2.7.1",
@ -154,6 +155,7 @@
"vite-plugin-css-injected-by-js": "^3.1.1", "vite-plugin-css-injected-by-js": "^3.1.1",
"vite-plugin-dts": "^2.3.0", "vite-plugin-dts": "^2.3.0",
"vite-plugin-eslint": "^1.8.1", "vite-plugin-eslint": "^1.8.1",
"vite-plugin-node-polyfills": "^0.9.0",
"vite-tsconfig-paths": "^4.2.0", "vite-tsconfig-paths": "^4.2.0",
"yarn": "^1.22.19" "yarn": "^1.22.19"
} }

View File

@ -15,7 +15,7 @@ import { ImageDTO } from 'services/api/types';
import { RootState } from 'app/store/store'; import { RootState } from 'app/store/store';
import { canvasSelector } from 'features/canvas/store/canvasSelectors'; import { canvasSelector } from 'features/canvas/store/canvasSelectors';
import { controlNetSelector } from 'features/controlNet/store/controlNetSlice'; import { controlNetSelector } from 'features/controlNet/store/controlNetSlice';
import { nodesSelecter } from 'features/nodes/store/nodesSlice'; import { nodesSelector } from 'features/nodes/store/nodesSlice';
import { generationSelector } from 'features/parameters/store/generationSelectors'; import { generationSelector } from 'features/parameters/store/generationSelectors';
import { some } from 'lodash-es'; import { some } from 'lodash-es';
@ -30,7 +30,7 @@ export const selectImageUsage = createSelector(
[ [
generationSelector, generationSelector,
canvasSelector, canvasSelector,
nodesSelecter, nodesSelector,
controlNetSelector, controlNetSelector,
(state: RootState, image_name?: string) => image_name, (state: RootState, image_name?: string) => image_name,
], ],

View File

@ -1,6 +1,7 @@
import { AnyAction } from '@reduxjs/toolkit'; import { AnyAction } from '@reduxjs/toolkit';
import { isAnyGraphBuilt } from 'features/nodes/store/actions'; import { isAnyGraphBuilt } from 'features/nodes/store/actions';
import { forEach } from 'lodash-es'; import { nodeTemplatesBuilt } from 'features/nodes/store/nodesSlice';
import { receivedOpenAPISchema } from 'services/api/thunks/schema';
import { Graph } from 'services/api/types'; import { Graph } from 'services/api/types';
export const actionSanitizer = <A extends AnyAction>(action: A): A => { export const actionSanitizer = <A extends AnyAction>(action: A): A => {
@ -8,17 +9,6 @@ export const actionSanitizer = <A extends AnyAction>(action: A): A => {
if (action.payload.nodes) { if (action.payload.nodes) {
const sanitizedNodes: Graph['nodes'] = {}; const sanitizedNodes: Graph['nodes'] = {};
// Sanitize nodes as needed
forEach(action.payload.nodes, (node, key) => {
// Don't log the whole freaking dataURL
if (node.type === 'dataURL_image') {
const { dataURL, ...rest } = node;
sanitizedNodes[key] = { ...rest, dataURL: '<dataURL>' };
} else {
sanitizedNodes[key] = { ...node };
}
});
return { return {
...action, ...action,
payload: { ...action.payload, nodes: sanitizedNodes }, payload: { ...action.payload, nodes: sanitizedNodes },
@ -26,5 +16,19 @@ export const actionSanitizer = <A extends AnyAction>(action: A): A => {
} }
} }
if (receivedOpenAPISchema.fulfilled.match(action)) {
return {
...action,
payload: '<OpenAPI schema omitted>',
};
}
if (nodeTemplatesBuilt.match(action)) {
return {
...action,
payload: '<Node templates omitted>',
};
}
return action; return action;
}; };

View File

@ -82,6 +82,7 @@ import {
addImageRemovedFromBoardFulfilledListener, addImageRemovedFromBoardFulfilledListener,
addImageRemovedFromBoardRejectedListener, addImageRemovedFromBoardRejectedListener,
} from './listeners/imageRemovedFromBoard'; } from './listeners/imageRemovedFromBoard';
import { addReceivedOpenAPISchemaListener } from './listeners/receivedOpenAPISchema';
export const listenerMiddleware = createListenerMiddleware(); export const listenerMiddleware = createListenerMiddleware();
@ -205,3 +206,6 @@ addImageAddedToBoardRejectedListener();
addImageRemovedFromBoardFulfilledListener(); addImageRemovedFromBoardFulfilledListener();
addImageRemovedFromBoardRejectedListener(); addImageRemovedFromBoardRejectedListener();
addBoardIdSelectedListener(); addBoardIdSelectedListener();
// Node schemas
addReceivedOpenAPISchemaListener();

View File

@ -0,0 +1,35 @@
import { receivedOpenAPISchema } from 'services/api/thunks/schema';
import { startAppListening } from '..';
import { log } from 'app/logging/useLogger';
import { parseSchema } from 'features/nodes/util/parseSchema';
import { nodeTemplatesBuilt } from 'features/nodes/store/nodesSlice';
import { size } from 'lodash-es';
const schemaLog = log.child({ namespace: 'schema' });
export const addReceivedOpenAPISchemaListener = () => {
startAppListening({
actionCreator: receivedOpenAPISchema.fulfilled,
effect: (action, { dispatch, getState }) => {
const schemaJSON = action.payload;
schemaLog.info({ data: { schemaJSON } }, 'Dereferenced OpenAPI schema');
const nodeTemplates = parseSchema(schemaJSON);
schemaLog.info(
{ data: { nodeTemplates } },
`Built ${size(nodeTemplates)} node templates`
);
dispatch(nodeTemplatesBuilt(nodeTemplates));
},
});
startAppListening({
actionCreator: receivedOpenAPISchema.rejected,
effect: (action, { dispatch, getState }) => {
schemaLog.error('Problem dereferencing OpenAPI Schema');
},
});
};

View File

@ -3,7 +3,7 @@ import { startAppListening } from '..';
import { createSelector } from '@reduxjs/toolkit'; import { createSelector } from '@reduxjs/toolkit';
import { generationSelector } from 'features/parameters/store/generationSelectors'; import { generationSelector } from 'features/parameters/store/generationSelectors';
import { canvasSelector } from 'features/canvas/store/canvasSelectors'; import { canvasSelector } from 'features/canvas/store/canvasSelectors';
import { nodesSelecter } from 'features/nodes/store/nodesSlice'; import { nodesSelector } from 'features/nodes/store/nodesSlice';
import { controlNetSelector } from 'features/controlNet/store/controlNetSlice'; import { controlNetSelector } from 'features/controlNet/store/controlNetSlice';
import { forEach, uniqBy } from 'lodash-es'; import { forEach, uniqBy } from 'lodash-es';
import { imageUrlsReceived } from 'services/api/thunks/image'; import { imageUrlsReceived } from 'services/api/thunks/image';
@ -16,7 +16,7 @@ const selectAllUsedImages = createSelector(
[ [
generationSelector, generationSelector,
canvasSelector, canvasSelector,
nodesSelecter, nodesSelector,
controlNetSelector, controlNetSelector,
selectImagesEntities, selectImagesEntities,
], ],

View File

@ -27,7 +27,6 @@ const IAIMantineMultiSelect = (props: IAIMultiSelectProps) => {
borderWidth: '2px', borderWidth: '2px',
borderColor: 'var(--invokeai-colors-base-800)', borderColor: 'var(--invokeai-colors-base-800)',
color: 'var(--invokeai-colors-base-100)', color: 'var(--invokeai-colors-base-100)',
padding: 10,
paddingRight: 24, paddingRight: 24,
fontWeight: 600, fontWeight: 600,
'&:hover': { borderColor: 'var(--invokeai-colors-base-700)' }, '&:hover': { borderColor: 'var(--invokeai-colors-base-700)' },

View File

@ -34,6 +34,10 @@ const IAIMantineSelect = (props: IAISelectProps) => {
'&:focus': { '&:focus': {
borderColor: 'var(--invokeai-colors-accent-600)', borderColor: 'var(--invokeai-colors-accent-600)',
}, },
'&:disabled': {
backgroundColor: 'var(--invokeai-colors-base-700)',
color: 'var(--invokeai-colors-base-400)',
},
}, },
dropdown: { dropdown: {
backgroundColor: 'var(--invokeai-colors-base-800)', backgroundColor: 'var(--invokeai-colors-base-800)',
@ -64,7 +68,7 @@ const IAIMantineSelect = (props: IAISelectProps) => {
}, },
}, },
rightSection: { rightSection: {
width: 24, width: 32,
}, },
})} })}
{...rest} {...rest}

View File

@ -1,28 +1,41 @@
import 'reactflow/dist/style.css'; import 'reactflow/dist/style.css';
import { memo, useCallback } from 'react'; import { useCallback, forwardRef } from 'react';
import { import { Flex, Text } from '@chakra-ui/react';
Tooltip,
Menu,
MenuButton,
MenuList,
MenuItem,
} from '@chakra-ui/react';
import { FaEllipsisV } from 'react-icons/fa';
import { useAppDispatch, useAppSelector } from 'app/store/storeHooks'; import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';
import { nodeAdded } from '../store/nodesSlice'; import { nodeAdded, nodesSelector } from '../store/nodesSlice';
import { map } from 'lodash-es'; import { map } from 'lodash-es';
import { RootState } from 'app/store/store';
import { useBuildInvocation } from '../hooks/useBuildInvocation'; import { useBuildInvocation } from '../hooks/useBuildInvocation';
import { AnyInvocationType } from 'services/events/types'; import { AnyInvocationType } from 'services/events/types';
import IAIIconButton from 'common/components/IAIIconButton';
import { useAppToaster } from 'app/components/Toaster'; import { useAppToaster } from 'app/components/Toaster';
import { createSelector } from '@reduxjs/toolkit';
import { defaultSelectorOptions } from 'app/store/util/defaultMemoizeOptions';
import IAIMantineMultiSelect from 'common/components/IAIMantineMultiSelect';
type NodeTemplate = {
label: string;
value: string;
description: string;
};
const selector = createSelector(
nodesSelector,
(nodes) => {
const data: NodeTemplate[] = map(nodes.invocationTemplates, (template) => {
return {
label: template.title,
value: template.type,
description: template.description,
};
});
return { data };
},
defaultSelectorOptions
);
const AddNodeMenu = () => { const AddNodeMenu = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const { data } = useAppSelector(selector);
const invocationTemplates = useAppSelector(
(state: RootState) => state.nodes.invocationTemplates
);
const buildInvocation = useBuildInvocation(); const buildInvocation = useBuildInvocation();
@ -46,23 +59,52 @@ const AddNodeMenu = () => {
); );
return ( return (
<Menu isLazy> <Flex sx={{ gap: 2, alignItems: 'center' }}>
<MenuButton <IAIMantineMultiSelect
as={IAIIconButton} selectOnBlur={false}
aria-label="Add Node" placeholder="Add Node"
icon={<FaEllipsisV />} value={[]}
data={data}
maxDropdownHeight={400}
nothingFound="No matching nodes"
itemComponent={SelectItem}
filter={(value, selected, item: NodeTemplate) =>
item.label.toLowerCase().includes(value.toLowerCase().trim()) ||
item.value.toLowerCase().includes(value.toLowerCase().trim()) ||
item.description.toLowerCase().includes(value.toLowerCase().trim())
}
onChange={(v) => {
v[0] && addNode(v[0] as AnyInvocationType);
}}
sx={{
width: '18rem',
}}
/> />
<MenuList overflowY="scroll" height={400}> </Flex>
{map(invocationTemplates, ({ title, description, type }, key) => {
return (
<Tooltip key={key} label={description} placement="end" hasArrow>
<MenuItem onClick={() => addNode(type)}>{title}</MenuItem>
</Tooltip>
);
})}
</MenuList>
</Menu>
); );
}; };
export default memo(AddNodeMenu); interface ItemProps extends React.ComponentPropsWithoutRef<'div'> {
value: string;
label: string;
description: string;
}
const SelectItem = forwardRef<HTMLDivElement, ItemProps>(
({ label, description, ...others }: ItemProps, ref) => {
return (
<div ref={ref} {...others}>
<div>
<Text>{label}</Text>
<Text size="xs" color="base.600">
{description}
</Text>
</div>
</div>
);
}
);
SelectItem.displayName = 'SelectItem';
export default AddNodeMenu;

View File

@ -1,10 +1,10 @@
import { memo } from 'react'; import { memo } from 'react';
import { Panel } from 'reactflow'; import { Panel } from 'reactflow';
import NodeSearch from '../search/NodeSearch'; import AddNodeMenu from '../AddNodeMenu';
const TopLeftPanel = () => ( const TopLeftPanel = () => (
<Panel position="top-left"> <Panel position="top-left">
<NodeSearch /> <AddNodeMenu />
</Panel> </Panel>
); );

View File

@ -14,9 +14,6 @@ import {
import { ImageField } from 'services/api/types'; import { ImageField } from 'services/api/types';
import { receivedOpenAPISchema } from 'services/api/thunks/schema'; import { receivedOpenAPISchema } from 'services/api/thunks/schema';
import { InvocationTemplate, InvocationValue } from '../types/types'; import { InvocationTemplate, InvocationValue } from '../types/types';
import { parseSchema } from '../util/parseSchema';
import { log } from 'app/logging/useLogger';
import { size } from 'lodash-es';
import { RgbaColor } from 'react-colorful'; import { RgbaColor } from 'react-colorful';
import { RootState } from 'app/store/store'; import { RootState } from 'app/store/store';
@ -78,25 +75,17 @@ const nodesSlice = createSlice({
shouldShowGraphOverlayChanged: (state, action: PayloadAction<boolean>) => { shouldShowGraphOverlayChanged: (state, action: PayloadAction<boolean>) => {
state.shouldShowGraphOverlay = action.payload; state.shouldShowGraphOverlay = action.payload;
}, },
parsedOpenAPISchema: (state, action: PayloadAction<OpenAPIV3.Document>) => { nodeTemplatesBuilt: (
try { state,
const parsedSchema = parseSchema(action.payload); action: PayloadAction<Record<string, InvocationTemplate>>
) => {
// TODO: Achtung! Side effect in a reducer! state.invocationTemplates = action.payload;
log.info(
{ namespace: 'schema', nodes: parsedSchema },
`Parsed ${size(parsedSchema)} nodes`
);
state.invocationTemplates = parsedSchema;
} catch (err) {
console.error(err);
}
}, },
nodeEditorReset: () => { nodeEditorReset: () => {
return { ...initialNodesState }; return { ...initialNodesState };
}, },
}, },
extraReducers(builder) { extraReducers: (builder) => {
builder.addCase(receivedOpenAPISchema.fulfilled, (state, action) => { builder.addCase(receivedOpenAPISchema.fulfilled, (state, action) => {
state.schema = action.payload; state.schema = action.payload;
}); });
@ -112,10 +101,10 @@ export const {
connectionStarted, connectionStarted,
connectionEnded, connectionEnded,
shouldShowGraphOverlayChanged, shouldShowGraphOverlayChanged,
parsedOpenAPISchema, nodeTemplatesBuilt,
nodeEditorReset, nodeEditorReset,
} = nodesSlice.actions; } = nodesSlice.actions;
export default nodesSlice.reducer; export default nodesSlice.reducer;
export const nodesSelecter = (state: RootState) => state.nodes; export const nodesSelector = (state: RootState) => state.nodes;

View File

@ -34,12 +34,10 @@ export type InvocationTemplate = {
* Array of invocation inputs * Array of invocation inputs
*/ */
inputs: Record<string, InputFieldTemplate>; inputs: Record<string, InputFieldTemplate>;
// inputs: InputField[];
/** /**
* Array of the invocation outputs * Array of the invocation outputs
*/ */
outputs: Record<string, OutputFieldTemplate>; outputs: Record<string, OutputFieldTemplate>;
// outputs: OutputField[];
}; };
export type FieldUIConfig = { export type FieldUIConfig = {
@ -335,7 +333,7 @@ export type TypeHints = {
}; };
export type InvocationSchemaExtra = { export type InvocationSchemaExtra = {
output: OpenAPIV3.ReferenceObject; // the output of the invocation output: OpenAPIV3.SchemaObject; // the output of the invocation
ui?: { ui?: {
tags?: string[]; tags?: string[];
type_hints?: TypeHints; type_hints?: TypeHints;

View File

@ -349,21 +349,11 @@ export const getFieldType = (
if (typeHints && name in typeHints) { if (typeHints && name in typeHints) {
rawFieldType = typeHints[name]; rawFieldType = typeHints[name];
} else if (!schemaObject.type) { } else if (!schemaObject.type && schemaObject.allOf) {
// if schemaObject has no type, then it should have one of allOf, anyOf, oneOf // if schemaObject has no type, then it should have one of allOf
if (schemaObject.allOf) { rawFieldType =
rawFieldType = refObjectToFieldType( (schemaObject.allOf[0] as OpenAPIV3.SchemaObject).title ??
schemaObject.allOf![0] as OpenAPIV3.ReferenceObject 'Missing Field Type';
);
} else if (schemaObject.anyOf) {
rawFieldType = refObjectToFieldType(
schemaObject.anyOf![0] as OpenAPIV3.ReferenceObject
);
} else if (schemaObject.oneOf) {
rawFieldType = refObjectToFieldType(
schemaObject.oneOf![0] as OpenAPIV3.ReferenceObject
);
}
} else if (schemaObject.enum) { } else if (schemaObject.enum) {
rawFieldType = 'enum'; rawFieldType = 'enum';
} else if (schemaObject.type) { } else if (schemaObject.type) {

View File

@ -5,33 +5,48 @@ import {
InputFieldTemplate, InputFieldTemplate,
InvocationSchemaObject, InvocationSchemaObject,
InvocationTemplate, InvocationTemplate,
isInvocationSchemaObject,
OutputFieldTemplate, OutputFieldTemplate,
} from '../types/types'; } from '../types/types';
import { import { buildInputFieldTemplate, getFieldType } from './fieldTemplateBuilders';
buildInputFieldTemplate, import { O } from 'ts-toolbelt';
buildOutputFieldTemplates,
} from './fieldTemplateBuilders'; // recursively exclude all properties of type U from T
type DeepExclude<T, U> = T extends U
? never
: T extends object
? {
[K in keyof T]: DeepExclude<T[K], U>;
}
: T;
// The schema from swagger-parser is dereferenced, and we know `components` and `components.schemas` exist
type DereferencedOpenAPIDocument = DeepExclude<
O.Required<OpenAPIV3.Document, 'schemas' | 'components', 'deep'>,
OpenAPIV3.ReferenceObject
>;
const RESERVED_FIELD_NAMES = ['id', 'type', 'is_intermediate']; const RESERVED_FIELD_NAMES = ['id', 'type', 'is_intermediate'];
const invocationDenylist = ['Graph', 'InvocationMeta']; const invocationDenylist = ['Graph', 'InvocationMeta'];
export const parseSchema = (openAPI: OpenAPIV3.Document) => { const nodeFilter = (
// filter out non-invocation schemas, plus some tricky invocations for now schema: DereferencedOpenAPIDocument['components']['schemas'][string],
const filteredSchemas = filter( key: string
openAPI.components!.schemas, ) =>
(schema, key) =>
key.includes('Invocation') && key.includes('Invocation') &&
!key.includes('InvocationOutput') && !key.includes('InvocationOutput') &&
!invocationDenylist.some((denylistItem) => key.includes(denylistItem)) !invocationDenylist.some((denylistItem) => key.includes(denylistItem));
) as (OpenAPIV3.ReferenceObject | InvocationSchemaObject)[];
export const parseSchema = (openAPI: DereferencedOpenAPIDocument) => {
// filter out non-invocation schemas, plus some tricky invocations for now
const filteredSchemas = filter(openAPI.components.schemas, nodeFilter);
const invocations = filteredSchemas.reduce< const invocations = filteredSchemas.reduce<
Record<string, InvocationTemplate> Record<string, InvocationTemplate>
>((acc, schema) => { >((acc, s) => {
// only want SchemaObjects // cast to InvocationSchemaObject, we know the shape
if (isInvocationSchemaObject(schema)) { const schema = s as InvocationSchemaObject;
const type = schema.properties.type.default; const type = schema.properties.type.default;
const title = schema.ui?.title ?? schema.title.replace('Invocation', ''); const title = schema.ui?.title ?? schema.title.replace('Invocation', '');
@ -41,10 +56,8 @@ export const parseSchema = (openAPI: OpenAPIV3.Document) => {
const inputs: Record<string, InputFieldTemplate> = {}; const inputs: Record<string, InputFieldTemplate> = {};
if (type === 'collect') { if (type === 'collect') {
const itemProperty = schema.properties[ // Special handling for the Collect node
'item' const itemProperty = schema.properties['item'] as InvocationSchemaObject;
] as InvocationSchemaObject;
// Handle the special Collect node
inputs.item = { inputs.item = {
type: 'item', type: 'item',
name: 'item', name: 'item',
@ -55,6 +68,7 @@ export const parseSchema = (openAPI: OpenAPIV3.Document) => {
default: undefined, default: undefined,
}; };
} else if (type === 'iterate') { } else if (type === 'iterate') {
// Special handling for the Iterate node
const itemProperty = schema.properties[ const itemProperty = schema.properties[
'collection' 'collection'
] as InvocationSchemaObject; ] as InvocationSchemaObject;
@ -91,16 +105,12 @@ export const parseSchema = (openAPI: OpenAPIV3.Document) => {
); );
} }
const rawOutput = (schema as InvocationSchemaObject).output;
let outputs: Record<string, OutputFieldTemplate>; let outputs: Record<string, OutputFieldTemplate>;
// some special handling is needed for collect, iterate and range nodes
if (type === 'iterate') { if (type === 'iterate') {
// this is guaranteed to be a SchemaObject // Special handling for the Iterate node output
const iterationOutput = openAPI.components!.schemas![ const iterationOutput =
'IterateInvocationOutput' openAPI.components.schemas['IterateInvocationOutput'];
] as OpenAPIV3.SchemaObject;
outputs = { outputs = {
item: { item: {
@ -111,7 +121,25 @@ export const parseSchema = (openAPI: OpenAPIV3.Document) => {
}, },
}; };
} else { } else {
outputs = buildOutputFieldTemplates(rawOutput, openAPI, typeHints); // All other node outputs
outputs = reduce(
schema.output.properties as OpenAPIV3.SchemaObject,
(outputsAccumulator, property, propertyName) => {
if (!['type', 'id'].includes(propertyName)) {
const fieldType = getFieldType(property, propertyName, typeHints);
outputsAccumulator[propertyName] = {
name: propertyName,
title: property.title ?? '',
description: property.description ?? '',
type: fieldType,
};
}
return outputsAccumulator;
},
{} as Record<string, OutputFieldTemplate>
);
} }
const invocation: InvocationTemplate = { const invocation: InvocationTemplate = {
@ -124,7 +152,6 @@ export const parseSchema = (openAPI: OpenAPIV3.Document) => {
}; };
Object.assign(acc, { [type]: invocation }); Object.assign(acc, { [type]: invocation });
}
return acc; return acc;
}, {}); }, {});

View File

@ -4,7 +4,6 @@ import * as InvokeAI from 'app/types/invokeai';
import { InvokeLogLevel } from 'app/logging/useLogger'; import { InvokeLogLevel } from 'app/logging/useLogger';
import { userInvoked } from 'app/store/actions'; import { userInvoked } from 'app/store/actions';
import { parsedOpenAPISchema } from 'features/nodes/store/nodesSlice';
import { TFuncKey, t } from 'i18next'; import { TFuncKey, t } from 'i18next';
import { LogLevelName } from 'roarr'; import { LogLevelName } from 'roarr';
import { import {
@ -26,6 +25,7 @@ import {
} from 'services/api/thunks/session'; } from 'services/api/thunks/session';
import { makeToast } from '../../../app/components/Toaster'; import { makeToast } from '../../../app/components/Toaster';
import { LANGUAGES } from '../components/LanguagePicker'; import { LANGUAGES } from '../components/LanguagePicker';
import { nodeTemplatesBuilt } from 'features/nodes/store/nodesSlice';
export type CancelStrategy = 'immediate' | 'scheduled'; export type CancelStrategy = 'immediate' | 'scheduled';
@ -382,7 +382,7 @@ export const systemSlice = createSlice({
/** /**
* OpenAPI schema was parsed * OpenAPI schema was parsed
*/ */
builder.addCase(parsedOpenAPISchema, (state) => { builder.addCase(nodeTemplatesBuilt, (state) => {
state.wasSchemaParsed = true; state.wasSchemaParsed = true;
}); });

View File

@ -2917,7 +2917,7 @@ export type components = {
/** ModelsList */ /** ModelsList */
ModelsList: { ModelsList: {
/** Models */ /** Models */
models: (components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"])[]; models: (components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"])[];
}; };
/** /**
* MultiplyInvocation * MultiplyInvocation
@ -4177,18 +4177,18 @@ export type components = {
*/ */
image?: components["schemas"]["ImageField"]; image?: components["schemas"]["ImageField"];
}; };
/**
* StableDiffusion2ModelFormat
* @description An enumeration.
* @enum {string}
*/
StableDiffusion2ModelFormat: "checkpoint" | "diffusers";
/** /**
* StableDiffusion1ModelFormat * StableDiffusion1ModelFormat
* @description An enumeration. * @description An enumeration.
* @enum {string} * @enum {string}
*/ */
StableDiffusion1ModelFormat: "checkpoint" | "diffusers"; StableDiffusion1ModelFormat: "checkpoint" | "diffusers";
/**
* StableDiffusion2ModelFormat
* @description An enumeration.
* @enum {string}
*/
StableDiffusion2ModelFormat: "checkpoint" | "diffusers";
}; };
responses: never; responses: never;
parameters: never; parameters: never;

View File

@ -1,20 +1,45 @@
import SwaggerParser from '@apidevtools/swagger-parser';
import { createAsyncThunk } from '@reduxjs/toolkit'; import { createAsyncThunk } from '@reduxjs/toolkit';
import { log } from 'app/logging/useLogger'; import { log } from 'app/logging/useLogger';
import { parsedOpenAPISchema } from 'features/nodes/store/nodesSlice';
import { OpenAPIV3 } from 'openapi-types'; import { OpenAPIV3 } from 'openapi-types';
const schemaLog = log.child({ namespace: 'schema' }); const schemaLog = log.child({ namespace: 'schema' });
function getCircularReplacer() {
const ancestors: Record<string, any>[] = [];
return function (key: string, value: any) {
if (typeof value !== 'object' || value === null) {
return value;
}
// `this` is the object that value is contained in,
// i.e., its direct parent.
// @ts-ignore
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) {
return '[Circular]';
}
ancestors.push(value);
return value;
};
}
export const receivedOpenAPISchema = createAsyncThunk( export const receivedOpenAPISchema = createAsyncThunk(
'nodes/receivedOpenAPISchema', 'nodes/receivedOpenAPISchema',
async (_, { dispatch }): Promise<OpenAPIV3.Document> => { async (_, { dispatch, rejectWithValue }) => {
const response = await fetch(`openapi.json`); try {
const openAPISchema = await response.json(); const dereferencedSchema = (await SwaggerParser.dereference(
'openapi.json'
)) as OpenAPIV3.Document;
schemaLog.info({ openAPISchema }, 'Received OpenAPI schema'); const schemaJSON = JSON.parse(
JSON.stringify(dereferencedSchema, getCircularReplacer())
);
dispatch(parsedOpenAPISchema(openAPISchema as OpenAPIV3.Document)); return schemaJSON;
} catch (error) {
return openAPISchema; return rejectWithValue({ error });
}
} }
); );

View File

@ -1,7 +1,14 @@
import { O } from 'ts-toolbelt';
import { components } from './schema'; import { components } from './schema';
type schemas = components['schemas']; type schemas = components['schemas'];
/**
* Helper type to extract the invocation type from the schema.
* Also flags the `type` property as required.
*/
type Invocation<T extends keyof schemas> = O.Required<schemas[T], 'type'>;
/** /**
* Types from the API, re-exported from the types generated by `openapi-typescript`. * Types from the API, re-exported from the types generated by `openapi-typescript`.
*/ */
@ -31,42 +38,42 @@ export type Edge = schemas['Edge'];
export type GraphExecutionState = schemas['GraphExecutionState']; export type GraphExecutionState = schemas['GraphExecutionState'];
// General nodes // General nodes
export type CollectInvocation = schemas['CollectInvocation']; export type CollectInvocation = Invocation<'CollectInvocation'>;
export type IterateInvocation = schemas['IterateInvocation']; export type IterateInvocation = Invocation<'IterateInvocation'>;
export type RangeInvocation = schemas['RangeInvocation']; export type RangeInvocation = Invocation<'RangeInvocation'>;
export type RandomRangeInvocation = schemas['RandomRangeInvocation']; export type RandomRangeInvocation = Invocation<'RandomRangeInvocation'>;
export type RangeOfSizeInvocation = schemas['RangeOfSizeInvocation']; export type RangeOfSizeInvocation = Invocation<'RangeOfSizeInvocation'>;
export type InpaintInvocation = schemas['InpaintInvocation']; export type InpaintInvocation = Invocation<'InpaintInvocation'>;
export type ImageResizeInvocation = schemas['ImageResizeInvocation']; export type ImageResizeInvocation = Invocation<'ImageResizeInvocation'>;
export type RandomIntInvocation = schemas['RandomIntInvocation']; export type RandomIntInvocation = Invocation<'RandomIntInvocation'>;
export type CompelInvocation = schemas['CompelInvocation']; export type CompelInvocation = Invocation<'CompelInvocation'>;
// ControlNet Nodes // ControlNet Nodes
export type ControlNetInvocation = schemas['ControlNetInvocation']; export type ControlNetInvocation = Invocation<'ControlNetInvocation'>;
export type CannyImageProcessorInvocation = export type CannyImageProcessorInvocation =
schemas['CannyImageProcessorInvocation']; Invocation<'CannyImageProcessorInvocation'>;
export type ContentShuffleImageProcessorInvocation = export type ContentShuffleImageProcessorInvocation =
schemas['ContentShuffleImageProcessorInvocation']; Invocation<'ContentShuffleImageProcessorInvocation'>;
export type HedImageProcessorInvocation = export type HedImageProcessorInvocation =
schemas['HedImageProcessorInvocation']; Invocation<'HedImageProcessorInvocation'>;
export type LineartAnimeImageProcessorInvocation = export type LineartAnimeImageProcessorInvocation =
schemas['LineartAnimeImageProcessorInvocation']; Invocation<'LineartAnimeImageProcessorInvocation'>;
export type LineartImageProcessorInvocation = export type LineartImageProcessorInvocation =
schemas['LineartImageProcessorInvocation']; Invocation<'LineartImageProcessorInvocation'>;
export type MediapipeFaceProcessorInvocation = export type MediapipeFaceProcessorInvocation =
schemas['MediapipeFaceProcessorInvocation']; Invocation<'MediapipeFaceProcessorInvocation'>;
export type MidasDepthImageProcessorInvocation = export type MidasDepthImageProcessorInvocation =
schemas['MidasDepthImageProcessorInvocation']; Invocation<'MidasDepthImageProcessorInvocation'>;
export type MlsdImageProcessorInvocation = export type MlsdImageProcessorInvocation =
schemas['MlsdImageProcessorInvocation']; Invocation<'MlsdImageProcessorInvocation'>;
export type NormalbaeImageProcessorInvocation = export type NormalbaeImageProcessorInvocation =
schemas['NormalbaeImageProcessorInvocation']; Invocation<'NormalbaeImageProcessorInvocation'>;
export type OpenposeImageProcessorInvocation = export type OpenposeImageProcessorInvocation =
schemas['OpenposeImageProcessorInvocation']; Invocation<'OpenposeImageProcessorInvocation'>;
export type PidiImageProcessorInvocation = export type PidiImageProcessorInvocation =
schemas['PidiImageProcessorInvocation']; Invocation<'PidiImageProcessorInvocation'>;
export type ZoeDepthImageProcessorInvocation = export type ZoeDepthImageProcessorInvocation =
schemas['ZoeDepthImageProcessorInvocation']; Invocation<'ZoeDepthImageProcessorInvocation'>;
// Node Outputs // Node Outputs
export type ImageOutput = schemas['ImageOutput']; export type ImageOutput = schemas['ImageOutput'];

View File

@ -9,6 +9,7 @@
"vite.config.ts", "vite.config.ts",
"./config/vite.app.config.ts", "./config/vite.app.config.ts",
"./config/vite.package.config.ts", "./config/vite.package.config.ts",
"./config/vite.common.config.ts" "./config/vite.common.config.ts",
"./config/common.ts"
] ]
} }

File diff suppressed because it is too large Load Diff