@flowdrop/flowdrop 2.14.0 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,44 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.15.0] - 2026-10-16
9
+
10
+ ### Added
11
+
12
+ - **`runCommand` on the object `mountFlowDropApp` and `mountWorkflowEditor` return** (#53).
13
+ `await app.runCommand('layout auto')` runs one Command Console command (a line, or a parsed
14
+ `Command`) against the mount's workflow and resolves with its `CommandResult`. It waits for the
15
+ workflow to load, so it can be called right after mounting, and it is one undo step like the
16
+ console. `{ baseline: true }` makes the result the workflow's clean starting point (not dirty,
17
+ undo history cleared) and is refused with `code: 'DIRTY'` when there are unsaved changes; it does not
18
+ call `onDirtyStateChange` or `onWorkflowChange`, and `undo`/`redo` cannot run as a baseline. A `Command`
19
+ object is checked before it runs: an unknown type or a missing or mistyped field resolves with
20
+ `code: 'INVALID_ARGUMENT'`. The promise never rejects (a command that throws resolves with
21
+ `code: 'INTERNAL_ERROR'`). Works on read-only mounts. A command's UI actions (select, open config, fit/zoom/pan) are applied by the
22
+ `mountFlowDropApp` shell and dropped by `mountWorkflowEditor`.
23
+ - **`onExternalEdit` event handler** (#55). A node's `externalEditLink` can now be handled by the host
24
+ instead of navigating away: the handler receives copies of `(node, link)` and resolves with the node's new config
25
+ (it replaces the config, as one undo step, and is copied) or with nothing to leave the node as it is.
26
+ Field edits still pending in the form are committed before the handler is called. It covers every
27
+ place the link opens: the inspector row ("Runs … ↗"), the form buttons and the empty state. The link
28
+ keeps its `href`, so middle-click and "copy link" still work. `ConfigForm` takes the same `onExternalEdit`
29
+ prop. While the editor is read-only or locked the handler is still called but its result is not written.
30
+ Without the handler nothing changes.
31
+ - **`Command`, `CommandResult`, `CommandErrorCode`, `ConfigValues` and `ExternalEditLink` types** are
32
+ exported from the main entry and `./editor` too, so hosts can type `runCommand` and `onExternalEdit`
33
+ without importing `./core`.
34
+
35
+ ### Deprecated
36
+
37
+ - **`ExternalEditLink.callbackUrlParam`.** It never had any effect, because nothing passes a callback URL.
38
+ Use `onExternalEdit` to get the config back from the host's form.
39
+
40
+ ### Fixed
41
+
42
+ - **`mountFlowDropApp` passes `workflowSettingsSchema` on to the editor** (#54). The option existed on
43
+ `App` but the mount function dropped it, so hosts mounting through the public API (the IIFE build
44
+ included) could not add their own Workflow Settings fields. Their values are stored in `workflow.config`.
45
+
8
46
  ## [2.14.0] - 2026-10-16
9
47
 
10
48
  ### Added
@@ -187,11 +187,15 @@ export type ParseResult = {
187
187
  error: string;
188
188
  input: string;
189
189
  };
190
- export type CommandErrorCode = 'NODE_NOT_FOUND' | 'NODE_TYPE_NOT_FOUND' | 'PORT_NOT_FOUND' | 'EDGE_NOT_FOUND' | 'INVALID_CONNECTION' | 'CYCLE_DETECTED' | 'NO_WORKFLOW' | 'PARSE_ERROR'
190
+ export type CommandErrorCode = 'NODE_NOT_FOUND' | 'NODE_TYPE_NOT_FOUND' | 'PORT_NOT_FOUND' | 'EDGE_NOT_FOUND' | 'INVALID_CONNECTION' | 'CYCLE_DETECTED' | 'NO_WORKFLOW'
191
+ /** `runCommand({ baseline: true })` on a workflow with unsaved changes: nothing was run. */
192
+ | 'DIRTY' | 'PARSE_ERROR'
191
193
  /** An argument is out of range, e.g. a layout gap that is not a multiple of the grid. */
192
194
  | 'INVALID_ARGUMENT'
193
195
  /** The graph is past what the command takes on, e.g. too many nodes to tidy at once. */
194
- | 'TOO_LARGE' | 'UNKNOWN_COMMAND' | 'CONFIG_KEY_NOT_FOUND'
196
+ | 'TOO_LARGE' | 'UNKNOWN_COMMAND'
197
+ /** The command threw instead of returning a result (a bug, not bad input): see the console. */
198
+ | 'INTERNAL_ERROR' | 'CONFIG_KEY_NOT_FOUND'
195
199
  /** search_types with a blank query — use list_types for the whole catalog. */
196
200
  | 'EMPTY_QUERY' | 'CONFIG_VALIDATION_ERROR' | 'UNDO_UNAVAILABLE' | 'REDO_UNAVAILABLE'
197
201
  /** A Console `session` command refused: busy, wrong input mode, nothing to act on. */
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Where the mount API's `runCommand` sends a command's UI actions (select a
3
+ * node, open its config panel, fit/zoom/pan the canvas).
4
+ *
5
+ * The editor shell (`App`) registers its handler for its instance while it is
6
+ * mounted. Kept off `FlowDropInstance` on purpose: it is internal, not
7
+ * exported from any entry point, so hosts cannot replace it.
8
+ *
9
+ * @module commands/uiActionTarget
10
+ */
11
+ import type { FlowDropInstance } from '../stores/instanceContainer.svelte.js';
12
+ import type { UIAction } from './types.js';
13
+ type UIActionHandler = (action: UIAction) => void;
14
+ /**
15
+ * Make `handler` the instance's UI-action target. The returned release only
16
+ * clears it while `handler` is still the target, so a shell mounted later
17
+ * keeps its own registration when an earlier one goes away.
18
+ */
19
+ export declare function provideUIActionTarget(instance: FlowDropInstance, handler: UIActionHandler): () => void;
20
+ /** Hand `action` to the instance's target; dropped when there is none. */
21
+ export declare function dispatchUIAction(instance: FlowDropInstance, action: UIAction): void;
22
+ /** Whether a shell has registered a target for the instance (for tests). */
23
+ export declare function hasUIActionTarget(instance: FlowDropInstance): boolean;
24
+ export {};
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Where the mount API's `runCommand` sends a command's UI actions (select a
3
+ * node, open its config panel, fit/zoom/pan the canvas).
4
+ *
5
+ * The editor shell (`App`) registers its handler for its instance while it is
6
+ * mounted. Kept off `FlowDropInstance` on purpose: it is internal, not
7
+ * exported from any entry point, so hosts cannot replace it.
8
+ *
9
+ * @module commands/uiActionTarget
10
+ */
11
+ const targets = new WeakMap();
12
+ /**
13
+ * Make `handler` the instance's UI-action target. The returned release only
14
+ * clears it while `handler` is still the target, so a shell mounted later
15
+ * keeps its own registration when an earlier one goes away.
16
+ */
17
+ export function provideUIActionTarget(instance, handler) {
18
+ targets.set(instance, handler);
19
+ return () => {
20
+ if (targets.get(instance) === handler)
21
+ targets.delete(instance);
22
+ };
23
+ }
24
+ /** Hand `action` to the instance's target; dropped when there is none. */
25
+ export function dispatchUIAction(instance, action) {
26
+ targets.get(instance)?.(action);
27
+ }
28
+ /** Whether a shell has registered a target for the instance (for tests). */
29
+ export function hasUIActionTarget(instance) {
30
+ return targets.has(instance);
31
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Shape check for a `Command` object handed in from outside the editor (the
3
+ * mount API's `runCommand`). The parser only ever builds well-formed commands;
4
+ * a host writing the object by hand, from plain JavaScript, may not, and the
5
+ * executor trusts the shape.
6
+ *
7
+ * @module commands/validate
8
+ */
9
+ /**
10
+ * Check that `value` is a `Command` the executor can run: a known `type`, its
11
+ * required fields present and every field it names of the right kind.
12
+ * Returns the problem, or null when the command is well formed. Fields the
13
+ * command does not define are ignored.
14
+ */
15
+ export declare function validateCommand(value: unknown): string | null;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Shape check for a `Command` object handed in from outside the editor (the
3
+ * mount API's `runCommand`). The parser only ever builds well-formed commands;
4
+ * a host writing the object by hand, from plain JavaScript, may not, and the
5
+ * executor trusts the shape.
6
+ *
7
+ * @module commands/validate
8
+ */
9
+ const NODE_ID = { nodeId: 'string' };
10
+ const GAPS = { gapX: 'number', gapY: 'number' };
11
+ const PORTS = {
12
+ sourceNodeId: 'string',
13
+ sourcePort: 'string',
14
+ targetNodeId: 'string',
15
+ targetPort: 'string'
16
+ };
17
+ /** One entry per command type, so a new command cannot be added without its rules. */
18
+ const RULES = {
19
+ add_node: { required: { nodeTypeId: 'string' }, optional: { position: 'point' } },
20
+ delete_node: { required: NODE_ID },
21
+ rename_node: { required: { ...NODE_ID, label: 'string' } },
22
+ set_config: {
23
+ required: { ...NODE_ID, key: 'string', value: 'string' },
24
+ optional: { strict: 'boolean' }
25
+ },
26
+ get_config: { required: NODE_ID, optional: { key: 'string' } },
27
+ connect: { required: PORTS },
28
+ disconnect_ports: { required: PORTS },
29
+ disconnect_node: { required: NODE_ID },
30
+ list_nodes: {},
31
+ list_edges: {},
32
+ list_types: {},
33
+ describe_type: { required: { nodeTypeId: 'string' } },
34
+ search_types: { required: { query: 'string' } },
35
+ info: { required: NODE_ID },
36
+ undo: {},
37
+ redo: {},
38
+ config_open: { required: NODE_ID },
39
+ select_node: { required: NODE_ID },
40
+ help: { optional: { command: 'string' } },
41
+ clear: { optional: { all: 'boolean' } },
42
+ swap_node: { required: { ...NODE_ID, newTypeId: 'string' } },
43
+ move_node: { required: { ...NODE_ID, position: 'point' } },
44
+ auto_layout: { optional: { direction: ['horizontal', 'vertical'] } },
45
+ beautify_layout: { optional: { dryRun: 'boolean', ...GAPS } },
46
+ inspect_node_layout: { required: NODE_ID, optional: GAPS },
47
+ beautify_node: {
48
+ required: NODE_ID,
49
+ optional: {
50
+ strategy: ['column', 'ports', 'align', 'clear', 'all'],
51
+ dryRun: 'boolean',
52
+ ...GAPS
53
+ }
54
+ },
55
+ canvas_fit_view: {},
56
+ canvas_zoom_in: {},
57
+ canvas_zoom_out: {},
58
+ canvas_zoom_to: { required: { level: 'number' } },
59
+ canvas_pan_to: { required: { position: 'point' } },
60
+ canvas_reset_view: {}
61
+ };
62
+ const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
63
+ function matches(value, kind) {
64
+ if (Array.isArray(kind))
65
+ return typeof value === 'string' && kind.includes(value);
66
+ switch (kind) {
67
+ case 'string':
68
+ return typeof value === 'string';
69
+ case 'number':
70
+ return isFiniteNumber(value);
71
+ case 'boolean':
72
+ return typeof value === 'boolean';
73
+ case 'point': {
74
+ const point = value;
75
+ return (typeof point === 'object' &&
76
+ point !== null &&
77
+ isFiniteNumber(point.x) &&
78
+ isFiniteNumber(point.y));
79
+ }
80
+ }
81
+ return false;
82
+ }
83
+ function describe(kind) {
84
+ if (Array.isArray(kind))
85
+ return `one of ${kind.map((k) => `"${k}"`).join(', ')}`;
86
+ return kind === 'point' ? 'an { x, y } object of numbers' : `a ${kind}`;
87
+ }
88
+ /**
89
+ * Check that `value` is a `Command` the executor can run: a known `type`, its
90
+ * required fields present and every field it names of the right kind.
91
+ * Returns the problem, or null when the command is well formed. Fields the
92
+ * command does not define are ignored.
93
+ */
94
+ export function validateCommand(value) {
95
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
96
+ return 'A command is a console line or a Command object.';
97
+ }
98
+ const command = value;
99
+ const type = command.type;
100
+ if (typeof type !== 'string' || !Object.hasOwn(RULES, type)) {
101
+ return `Unknown command type: ${JSON.stringify(type)}.`;
102
+ }
103
+ const rules = RULES[type];
104
+ for (const [field, kind] of Object.entries(rules.required ?? {})) {
105
+ if (!matches(command[field], kind)) {
106
+ return `${type}: "${field}" must be ${describe(kind)}.`;
107
+ }
108
+ }
109
+ for (const [field, kind] of Object.entries(rules.optional ?? {})) {
110
+ if (command[field] !== undefined && !matches(command[field], kind)) {
111
+ return `${type}: "${field}" must be ${describe(kind)} when given.`;
112
+ }
113
+ }
114
+ return null;
115
+ }
@@ -53,7 +53,13 @@
53
53
  import Navbar from './Navbar.svelte';
54
54
  import DoctorMenu from './DoctorMenu.svelte';
55
55
  import type { NavbarAction, NavbarBranding } from '../types/navbar.js';
56
- import type { NodeMetadata, Workflow, WorkflowNode, ConfigSchema } from '../types/index.js';
56
+ import type {
57
+ NodeMetadata,
58
+ Workflow,
59
+ WorkflowNode,
60
+ ConfigSchema,
61
+ ExternalEditLink
62
+ } from '../types/index.js';
57
63
  import type { InteractiveSwapState, SwapEventContext } from '../utils/nodeSwap.js';
58
64
  import {
59
65
  computeInteractiveState,
@@ -83,6 +89,8 @@
83
89
  initializeTheme
84
90
  } from '../stores/settingsStore.svelte.js';
85
91
  import { logger } from '../utils/logger.js';
92
+ import { runExternalEdit } from '../utils/externalEdit.svelte.js';
93
+ import { provideUIActionTarget } from '../commands/uiActionTarget.js';
86
94
  import { themeScope } from '../utils/themeScope.svelte.js';
87
95
  import {
88
96
  resolveInspectorSurface,
@@ -210,6 +218,8 @@
210
218
  onApiError?: FlowDropEventHandlers['onApiError'];
211
219
  /** Called after a workflow is loaded/imported. */
212
220
  onWorkflowLoad?: FlowDropEventHandlers['onWorkflowLoad'];
221
+ /** Called instead of opening a node's external edit link; resolve with the new config. */
222
+ onExternalEdit?: FlowDropEventHandlers['onExternalEdit'];
213
223
  /** Called before a node swap — return false to cancel. */
214
224
  onBeforeSwap?: FlowDropEventHandlers['onBeforeSwap'];
215
225
  /** Called after a node swap is applied. */
@@ -283,6 +293,7 @@
283
293
  onSaveError,
284
294
  onApiError,
285
295
  onWorkflowLoad,
296
+ onExternalEdit,
286
297
  onBeforeSwap,
287
298
  onAfterSwap,
288
299
  features: propFeatures,
@@ -1128,6 +1139,33 @@
1128
1139
  }
1129
1140
  });
1130
1141
 
1142
+ /**
1143
+ * Hand a node's external edit link to the host (`onExternalEdit`) and write
1144
+ * the config it resolves with. Undefined when the host set no handler, so the
1145
+ * link opens as before.
1146
+ */
1147
+ // Nodes whose host form is open, kept here so reopening the inspector does
1148
+ // not open a second one.
1149
+ const externalEditPending = new Set<string>();
1150
+ const externalEditForConfig = $derived(
1151
+ onExternalEdit
1152
+ ? (node: WorkflowNode, link: ExternalEditLink) =>
1153
+ runExternalEdit({
1154
+ node,
1155
+ link,
1156
+ handler: (n, l) => onExternalEdit(n, l),
1157
+ store: fd.workflow,
1158
+ // Read when the host resolves: the editor may have been locked meanwhile.
1159
+ canWrite: () => canvasEditable,
1160
+ pending: externalEditPending,
1161
+ onWritten: (written) => {
1162
+ workflowEditorRef?.updateNodeData(written.id, written.data);
1163
+ void workflowEditorRef?.refreshEdgePositions(written.id);
1164
+ }
1165
+ })
1166
+ : undefined
1167
+ );
1168
+
1131
1169
  async function saveWorkflow(): Promise<boolean> {
1132
1170
  // Commit any in-flight config edit so the save and its history are
1133
1171
  // consistent (the value itself is already live in the store).
@@ -1660,6 +1698,9 @@
1660
1698
  }
1661
1699
  }
1662
1700
 
1701
+ // Let the mount API's `runCommand` reach this handler for UI actions.
1702
+ $effect(() => provideUIActionTarget(fd, handleConsoleUIAction));
1703
+
1663
1704
  /** Show the Assistant: its tab beside Nodes, or the console group where there is no left slot. */
1664
1705
  function openAssistant(): void {
1665
1706
  if (chatInConsoleGroup) {
@@ -1738,6 +1779,7 @@
1738
1779
  workflowId={fd.workflow.current?.id}
1739
1780
  workflowNodes={fd.workflow.current?.nodes}
1740
1781
  workflowEdges={fd.workflow.current?.edges}
1782
+ onExternalEdit={externalEditForConfig}
1741
1783
  onChange={(updatedConfig, meta) => {
1742
1784
  if (!node.id) return;
1743
1785
  const updatedData = { ...node.data, config: updatedConfig };
@@ -124,6 +124,8 @@ interface Props {
124
124
  onApiError?: FlowDropEventHandlers['onApiError'];
125
125
  /** Called after a workflow is loaded/imported. */
126
126
  onWorkflowLoad?: FlowDropEventHandlers['onWorkflowLoad'];
127
+ /** Called instead of opening a node's external edit link; resolve with the new config. */
128
+ onExternalEdit?: FlowDropEventHandlers['onExternalEdit'];
127
129
  /** Called before a node swap — return false to cancel. */
128
130
  onBeforeSwap?: FlowDropEventHandlers['onBeforeSwap'];
129
131
  /** Called after a node swap is applied. */
@@ -18,6 +18,7 @@
18
18
  WorkflowNode,
19
19
  WorkflowEdge,
20
20
  ConfigEditOptions,
21
+ ExternalEditLink,
21
22
  AuthProvider
22
23
  } from '../types/index.js';
23
24
  import type { UISchemaElement } from '../types/uischema.js';
@@ -107,6 +108,15 @@
107
108
  config: Record<string, unknown>,
108
109
  meta?: { fieldKey?: string; commit?: boolean }
109
110
  ) => void;
111
+ /**
112
+ * Called instead of opening the node's external edit link, when set, with
113
+ * copies of the node and the link, after committing field edits still
114
+ * pending (as a blur would). The host opens its own form; ConfigForm awaits
115
+ * the call (a second click while one is pending is ignored) and logs a
116
+ * rejection. Writing the config the
117
+ * handler resolves with is the caller's job: ConfigForm passes it on as is.
118
+ */
119
+ onExternalEdit?: (node: WorkflowNode, link: ExternalEditLink) => unknown;
110
120
  /** Callback when form is saved */
111
121
  onSave?: (config: Record<string, unknown>) => void;
112
122
  /** Callback when form is cancelled */
@@ -125,6 +135,7 @@
125
135
  authProvider,
126
136
  commitMode = 'blur',
127
137
  onChange,
138
+ onExternalEdit,
128
139
  onSave,
129
140
  onCancel
130
141
  }: Props = $props();
@@ -399,7 +410,8 @@
399
410
  : { name: link.label ?? 'Configure externally' }),
400
411
  title: link.description,
401
412
  href: getExternalEditUrl(),
402
- newTab: link.openInNewTab !== false
413
+ newTab: link.openInNewTab !== false,
414
+ ...(onExternalEdit ? { onActivate: handleExternalEditClick } : {})
403
415
  };
404
416
  });
405
417
 
@@ -418,9 +430,38 @@
418
430
  /**
419
431
  * Handle opening external edit link
420
432
  */
433
+ const externalEditPending = new Set<string>();
434
+
435
+ /** A plain copy of reactive state. Typed as `T`: `Snapshot<WorkflowNode>` is too deep for tsc. */
436
+ const copyOf = <T,>(value: T): T => $state.snapshot(value) as T;
437
+
421
438
  function handleExternalEditClick(): void {
422
439
  if (!node || !configEditOptions?.externalEditLink) return;
423
440
 
441
+ if (onExternalEdit) {
442
+ const link = configEditOptions.externalEditLink;
443
+ const nodeId = node.id;
444
+ // One host form per node at a time.
445
+ if (externalEditPending.has(nodeId)) return;
446
+ externalEditPending.add(nodeId);
447
+ // Commit what is still in the edit buffer first: the host then sees it,
448
+ // and a stale buffered value cannot shadow, and later overwrite, the
449
+ // config the host writes back. A click on a link does not always blur the
450
+ // field (Safari does not focus links).
451
+ if (Object.keys(edits).length > 0) handleFormBlur();
452
+ void (async () => {
453
+ try {
454
+ // Copies: the host must not write into the live workflow behind the editor's back.
455
+ await onExternalEdit(copyOf(node), copyOf(link));
456
+ } catch (error) {
457
+ logger.warn('onExternalEdit failed:', error);
458
+ } finally {
459
+ externalEditPending.delete(nodeId);
460
+ }
461
+ })();
462
+ return;
463
+ }
464
+
424
465
  const url = getExternalEditUrl();
425
466
  const openInNewTab = configEditOptions.externalEditLink.openInNewTab !== false;
426
467
 
@@ -1,4 +1,4 @@
1
- import type { ConfigSchema, WorkflowNode, WorkflowEdge, AuthProvider } from '../types/index.js';
1
+ import type { ConfigSchema, WorkflowNode, WorkflowEdge, ExternalEditLink, AuthProvider } from '../types/index.js';
2
2
  import type { UISchemaElement } from '../types/uischema.js';
3
3
  interface Props {
4
4
  /** Optional workflow node (if provided, schema and values are derived from it) */
@@ -51,6 +51,15 @@ interface Props {
51
51
  fieldKey?: string;
52
52
  commit?: boolean;
53
53
  }) => void;
54
+ /**
55
+ * Called instead of opening the node's external edit link, when set, with
56
+ * copies of the node and the link, after committing field edits still
57
+ * pending (as a blur would). The host opens its own form; ConfigForm awaits
58
+ * the call (a second click while one is pending is ignored) and logs a
59
+ * rejection. Writing the config the
60
+ * handler resolves with is the caller's job: ConfigForm passes it on as is.
61
+ */
62
+ onExternalEdit?: (node: WorkflowNode, link: ExternalEditLink) => unknown;
54
63
  /** Callback when form is saved */
55
64
  onSave?: (config: Record<string, unknown>) => void;
56
65
  /** Callback when form is cancelled */
@@ -17,9 +17,23 @@
17
17
  href: string;
18
18
  /** Open in a new tab */
19
19
  newTab?: boolean;
20
+ /**
21
+ * Handle a plain left click instead of following the link. The href stays,
22
+ * so middle-click, modified clicks and "copy link" work as for any link.
23
+ */
24
+ onActivate?: () => void;
20
25
  }
21
26
 
22
- let { prefix, name, title, href, newTab = true }: Props = $props();
27
+ let { prefix, name, title, href, newTab = true, onActivate }: Props = $props();
28
+
29
+ function handleClick(event: MouseEvent): void {
30
+ if (!onActivate) return;
31
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
32
+ return;
33
+ }
34
+ event.preventDefault();
35
+ onActivate();
36
+ }
23
37
  </script>
24
38
 
25
39
  <div class="external-link-row">
@@ -30,6 +44,7 @@
30
44
  target={newTab ? '_blank' : undefined}
31
45
  rel={newTab ? 'noopener noreferrer' : undefined}
32
46
  title={title ?? name}
47
+ onclick={handleClick}
33
48
  data-testid="external-config-link"
34
49
  >
35
50
  <span class="external-link-row__name">{name}</span>
@@ -8,6 +8,11 @@ interface Props {
8
8
  href: string;
9
9
  /** Open in a new tab */
10
10
  newTab?: boolean;
11
+ /**
12
+ * Handle a plain left click instead of following the link. The href stays,
13
+ * so middle-click, modified clicks and "copy link" work as for any link.
14
+ */
15
+ onActivate?: () => void;
11
16
  }
12
17
  declare const ExternalLinkRow: import("svelte").Component<Props, {}, "">;
13
18
  type ExternalLinkRow = ReturnType<typeof ExternalLinkRow>;
@@ -38,7 +38,7 @@ export type { NodeStatusScope } from '../stores/playgroundStore.svelte.js';
38
38
  export type { RunController, RunControllerOptions } from '../stores/runController.svelte.js';
39
39
  export type { EditorMode, EditorModeStore } from '../stores/editorModeStore.svelte.js';
40
40
  export type { EndpointConfig } from '../config/endpoints.js';
41
- export type { FlowDropMountOptions, MountedFlowDropApp, NavbarAction, NavbarBranding } from '../svelte-app.js';
41
+ export type { FlowDropMountOptions, MountedFlowDropApp, RunCommandOptions, NavbarAction, NavbarBranding } from '../svelte-app.js';
42
42
  export { StaticAuthProvider, CallbackAuthProvider, NoAuthProvider } from '../types/auth.js';
43
43
  export { DEFAULT_FEATURES, mergeFeatures } from '../types/events.js';
44
44
  export { getStatusColor, getStatusIcon, getStatusLabel, getStatusBackgroundColor, getStatusTextColor, createDefaultExecutionInfo, updateExecutionStart, updateExecutionComplete, updateExecutionFailed, resetExecutionInfo, stripExecutionInfo, formatExecutionDuration, formatLastExecuted } from '../utils/nodeStatus.js';
@@ -92,13 +92,13 @@ export type { PortShape } from '../utils/portShape.js';
92
92
  export { default as PortTypeBadge } from '../components/ports/PortTypeBadge.svelte';
93
93
  export { fetchRuntimeConfig, getRuntimeConfig, clearRuntimeConfigCache, initRuntimeConfig } from '../config/runtimeConfig.js';
94
94
  export type { RuntimeConfig } from '../config/runtimeConfig.js';
95
- export type { Workflow, WorkflowNode, WorkflowEdge, NodeMetadata, NodePort, DynamicPort, Branch, ExecutionStatus, ExecutionResult, FlowDropConfig, PortConfig, ConfigSchema, ConfigProperty, ConfigEditOptions } from '../types/index.js';
95
+ export type { Workflow, WorkflowNode, WorkflowEdge, NodeMetadata, NodePort, DynamicPort, Branch, ExecutionStatus, ExecutionResult, FlowDropConfig, PortConfig, ConfigSchema, ConfigProperty, ConfigEditOptions, ConfigValues, ExternalEditLink } from '../types/index.js';
96
96
  export type { WorkflowEditorConfig, EditorFeatures, UIConfig, APIConfig } from '../types/config.js';
97
97
  export type { AuthProvider, StaticAuthConfig, CallbackAuthConfig } from '../types/auth.js';
98
98
  export type { FlowDropEventHandlers, FlowDropFeatures, WorkflowChangeType } from '../types/events.js';
99
99
  export type { EndpointConfig } from '../config/endpoints.js';
100
- export type { UIAction } from '../commands/types.js';
100
+ export type { UIAction, Command, CommandResult, CommandErrorCode } from '../commands/types.js';
101
101
  export type { EditorPlaygroundConfig } from '../types/playground.js';
102
- export type { FlowDropMountOptions, MountedFlowDropApp, NavbarAction, NavbarBranding } from '../svelte-app.js';
102
+ export type { FlowDropMountOptions, MountedFlowDropApp, RunCommandOptions, NavbarAction, NavbarBranding } from '../svelte-app.js';
103
103
  export type { ContextMenuActions, ContextMenuContext, ContextMenuEntry, ContextMenuOptions, ContextMenuTarget } from './contextMenu.js';
104
104
  export type { NodeComponentProps, NodeComponentRegistration, FlowDropPluginConfig, PluginNodeDefinition } from '../registry/index.js';
package/dist/index.d.ts CHANGED
@@ -32,10 +32,11 @@ export { createFlowDropInstance } from './stores/instanceContainer.svelte.js';
32
32
  export { getInstance, provideInstance } from './stores/getInstance.svelte.js';
33
33
  export { createEndpointConfig, defaultEndpointConfig, sessionsEndpoints } from './config/endpoints.js';
34
34
  export { NoAuthProvider, StaticAuthProvider, CallbackAuthProvider } from './types/auth.js';
35
- export type { Workflow, WorkflowNode, WorkflowEdge, NodeMetadata, ConfigSchema } from './types/index.js';
35
+ export type { Workflow, WorkflowNode, WorkflowEdge, NodeMetadata, ConfigSchema, ConfigValues, ExternalEditLink } from './types/index.js';
36
+ export type { Command, CommandResult, CommandErrorCode } from './commands/types.js';
36
37
  export type { EndpointConfig } from './config/endpoints.js';
37
38
  export type { AuthProvider } from './types/auth.js';
38
39
  export type { FlowDropInstance } from './stores/instanceContainer.svelte.js';
39
- export type { FlowDropMountOptions, MountedFlowDropApp } from './svelte-app.js';
40
+ export type { FlowDropMountOptions, MountedFlowDropApp, RunCommandOptions } from './svelte-app.js';
40
41
  export type { FlowDropEventHandlers } from './types/events.js';
41
42
  export type { Messages, MessagesOverride } from './messages/index.js';
@@ -194,6 +194,16 @@ export declare class WorkflowStore {
194
194
  revision?: Workflow['revision'];
195
195
  can?: Workflow['can'];
196
196
  }): void;
197
+ /**
198
+ * Stop calling the dirty-state and workflow-change callbacks until the
199
+ * returned release is called, e.g. while a change is made and then taken as
200
+ * the workflow's new clean state, which the host should not hear about.
201
+ *
202
+ * On release the host hears only what is still true: the dirty state when it
203
+ * differs from the one at muting, and one `'metadata'` change when the
204
+ * workflow is dirty and was replaced meanwhile. Release is idempotent.
205
+ */
206
+ muteCallbacks(): () => void;
197
207
  /**
198
208
  * Set the restoring from history flag.
199
209
  *
@@ -128,6 +128,8 @@ export class WorkflowStore {
128
128
  #onDirtyStateChange = null;
129
129
  /** Callback for workflow changes — set by the App component. */
130
130
  #onWorkflowChange = null;
131
+ /** While above 0 the two callbacks above are not called (see {@link muteCallbacks}). */
132
+ #muted = 0;
131
133
  /**
132
134
  * Whether we're currently restoring from history (undo/redo).
133
135
  * When true, prevents pushing to history to avoid recursive loops.
@@ -322,9 +324,8 @@ export class WorkflowStore {
322
324
  markAsSaved() {
323
325
  const wasDirty = this.#editVersion !== this.#savedVersion;
324
326
  this.#savedVersion = this.#editVersion;
325
- if (wasDirty && this.#onDirtyStateChange) {
326
- this.#onDirtyStateChange(false);
327
- }
327
+ if (wasDirty)
328
+ this.#emitDirty(false);
328
329
  }
329
330
  /**
330
331
  * Take the server's word on the workflow's revision and permissions after a
@@ -341,6 +342,34 @@ export class WorkflowStore {
341
342
  ...(state.can !== undefined && { can: state.can })
342
343
  };
343
344
  }
345
+ /**
346
+ * Stop calling the dirty-state and workflow-change callbacks until the
347
+ * returned release is called, e.g. while a change is made and then taken as
348
+ * the workflow's new clean state, which the host should not hear about.
349
+ *
350
+ * On release the host hears only what is still true: the dirty state when it
351
+ * differs from the one at muting, and one `'metadata'` change when the
352
+ * workflow is dirty and was replaced meanwhile. Release is idempotent.
353
+ */
354
+ muteCallbacks() {
355
+ const dirtyBefore = this.isDirty;
356
+ const workflowBefore = this.#workflow;
357
+ this.#muted++;
358
+ let released = false;
359
+ return () => {
360
+ if (released)
361
+ return;
362
+ released = true;
363
+ this.#muted--;
364
+ if (this.#muted > 0)
365
+ return;
366
+ const dirty = this.isDirty;
367
+ if (dirty !== dirtyBefore)
368
+ this.#emitDirty(dirty);
369
+ if (dirty && this.#workflow !== workflowBefore)
370
+ this.#notifyWorkflowChange('metadata');
371
+ };
372
+ }
344
373
  /**
345
374
  * Set the restoring from history flag.
346
375
  *
@@ -360,17 +389,20 @@ export class WorkflowStore {
360
389
  this.#editVersion++;
361
390
  // Dirty state just flipped from clean → dirty
362
391
  if (this.#editVersion - 1 === this.#savedVersion) {
363
- if (this.#onDirtyStateChange) {
364
- this.#onDirtyStateChange(true);
365
- }
392
+ this.#emitDirty(true);
366
393
  }
367
394
  }
395
+ /** Tell the host the dirty state changed, unless the callbacks are muted. */
396
+ #emitDirty(isDirty) {
397
+ if (this.#muted === 0)
398
+ this.#onDirtyStateChange?.(isDirty);
399
+ }
368
400
  /**
369
401
  * Notify external listeners of a workflow change.
370
402
  * Does NOT bump the version — callers that mutate must call #bumpVersion() explicitly.
371
403
  */
372
404
  #notifyWorkflowChange(changeType) {
373
- if (this.#workflow && this.#onWorkflowChange) {
405
+ if (this.#workflow && this.#onWorkflowChange && this.#muted === 0) {
374
406
  this.#onWorkflowChange(this.#workflow, changeType);
375
407
  }
376
408
  }
@@ -425,9 +457,7 @@ export class WorkflowStore {
425
457
  // Reset version counters — workflow is "clean" after initialization
426
458
  this.#editVersion = 0;
427
459
  this.#savedVersion = 0;
428
- if (this.#onDirtyStateChange) {
429
- this.#onDirtyStateChange(false);
430
- }
460
+ this.#emitDirty(false);
431
461
  // Initialize history with the loaded workflow
432
462
  this.#history.initialize(workflow);
433
463
  }
@@ -667,9 +697,7 @@ export class WorkflowStore {
667
697
  this.#editVersion = 0;
668
698
  this.#savedVersion = 0;
669
699
  this.#history.clear();
670
- if (this.#onDirtyStateChange) {
671
- this.#onDirtyStateChange(false);
672
- }
700
+ this.#emitDirty(false);
673
701
  }
674
702
  /** Update workflow metadata. */
675
703
  updateMetadata(metadata) {
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @module svelte-app
8
8
  */
9
- import type { Workflow, NodeMetadata, PortConfig, CategoryDefinition } from './types/index.js';
9
+ import type { Workflow, NodeMetadata, PortConfig, CategoryDefinition, ConfigSchema } from './types/index.js';
10
10
  import type { EndpointConfig } from './config/endpoints.js';
11
11
  import type { AuthProvider } from './types/auth.js';
12
12
  import type { EditorPlaygroundConfig } from './types/playground.js';
@@ -18,6 +18,7 @@ import { type DraftStorageOption } from './services/draftStorage.js';
18
18
  import type { ColorSchemeOption, PartialSettings, SettingsCategory, SurfacePlacement } from './types/settings.js';
19
19
  import type { NavbarAction, NavbarBranding } from './types/navbar.js';
20
20
  import type { HostHooks, WebMCPHandle, WebMCPMountOptions } from './webmcp/types.js';
21
+ import type { Command, CommandResult } from './commands/types.js';
21
22
  export type { NavbarAction, NavbarBranding };
22
23
  import type { ContextMenuOptions } from './editor/contextMenu.js';
23
24
  export type { HostHooks, WebMCPHandle, WebMCPMountOptions };
@@ -154,6 +155,14 @@ export interface FlowDropMountOptions {
154
155
  * is left untouched. Omit to offer every registered format.
155
156
  */
156
157
  workflowFormats?: string[];
158
+ /**
159
+ * Extra JSON Schema properties for the Workflow Settings panel. Their values
160
+ * are stored in `workflow.config`: loaded from the workflow passed in,
161
+ * returned by `getWorkflow()` and saved with it. The built-in keys (`name`,
162
+ * `description`, `format`, `interface`, `playground`) are reserved: a
163
+ * property using one is ignored with a console warning.
164
+ */
165
+ workflowSettingsSchema?: ConfigSchema;
157
166
  /** Visual theme — named built-in ('graphite' | 'classic' | 'minimal' | 'drafter') or custom theme object */
158
167
  theme?: FlowDropTheme | FlowDropThemeName;
159
168
  /** Which settings tabs to show in the modal (defaults to all) */
@@ -207,6 +216,15 @@ export interface FlowDropMountOptions {
207
216
  */
208
217
  contextMenu?: ContextMenuOptions;
209
218
  }
219
+ /** Options for {@link MountedFlowDropApp.runCommand}. */
220
+ export interface RunCommandOptions {
221
+ /**
222
+ * Make the command's result the workflow's clean starting point: no undo
223
+ * step and not dirty. Refused with `code: 'DIRTY'` when the workflow already
224
+ * has unsaved changes.
225
+ */
226
+ baseline?: boolean;
227
+ }
210
228
  /**
211
229
  * Return type for mounted FlowDrop app
212
230
  */
@@ -257,6 +275,49 @@ export interface MountedFlowDropApp {
257
275
  * @returns The number of entries removed.
258
276
  */
259
277
  clearAllDrafts: () => number;
278
+ /**
279
+ * Run one Command Console command against this mount's workflow, as if it
280
+ * had been typed into the console: `await app.runCommand('layout auto')`.
281
+ *
282
+ * `command` is a console line (parsed with the editing DSL) or an already
283
+ * parsed `Command` object. An object is checked first: an unknown `type`, or
284
+ * a field that is missing or of the wrong kind, resolves with
285
+ * `code: 'INVALID_ARGUMENT'` and runs nothing. Never rejects: failures (a
286
+ * line that does not parse, an unknown node, ...) resolve to
287
+ * `{ ok: false, error, code }`.
288
+ *
289
+ * - **Waits for the workflow.** The mount resolves before the editor has
290
+ * loaded its workflow, so a call made right after mounting waits for it.
291
+ * If the mount is destroyed first, or was already destroyed, the call
292
+ * resolves with `{ ok: false, code: 'NO_WORKFLOW' }`.
293
+ * - **One undo step per call**, the same as typing the command in the
294
+ * console; the workflow becomes dirty.
295
+ * - **Sizes before first paint.** `layout auto` reads node sizes the canvas
296
+ * has measured and `layout beautify` asks the mounted canvas to measure
297
+ * them. A call made before the canvas has rendered falls back to computed
298
+ * geometry, so the result can differ slightly from the same command run
299
+ * later.
300
+ * - **`options.baseline`** makes the command's result the workflow's clean
301
+ * starting point: `isDirty()` is `false` afterwards and the undo history
302
+ * starts over from it (earlier undo steps are cleared too). Useful to
303
+ * tidy a loaded model before the user sees it. It needs a workflow with no
304
+ * unsaved changes: when the workflow is dirty the command is not run and
305
+ * the call resolves with `{ ok: false, code: 'DIRTY' }`. `undo` and `redo`
306
+ * are refused with `code: 'INVALID_ARGUMENT'`. `onDirtyStateChange` and
307
+ * `onWorkflowChange` are not called for a baseline run; a failed command
308
+ * that still left changes is reported once it returns. A failed command,
309
+ * or one that changes nothing (`info`, `list nodes`), keeps the undo
310
+ * history. A draft saved earlier is not overwritten by the re-baselined
311
+ * workflow.
312
+ * - **Read-only mounts** (`mode: 'readonly' | 'locked'`) accept it too, so a
313
+ * host can lay out a model it only displays.
314
+ * - **UI actions** (select a node, open its config panel, fit/zoom/pan) are
315
+ * applied by `mountFlowDropApp`'s editor shell. `mountWorkflowEditor` has
316
+ * no shell, so they are dropped there.
317
+ * - **Session commands** (`session ...`) belong to the console and are not
318
+ * available: they resolve with `{ ok: false, code: 'SESSION_REFUSED' }`.
319
+ */
320
+ runCommand: (command: string | Command, options?: RunCommandOptions) => Promise<CommandResult>;
260
321
  /**
261
322
  * The WebMCP registration when the `webmcp` mount option was set and the
262
323
  * browser has the API; `undefined` otherwise. The adapter attaches in the
@@ -19,6 +19,12 @@ import { initializeSettings, getHostColorSchemeRegistration, releaseHostColorSch
19
19
  import { logger } from './utils/logger.js';
20
20
  import { globalSaveWorkflow, globalExportWorkflow } from './services/globalSave.js';
21
21
  import { whenWorkflowLoaded } from './utils/whenWorkflowLoaded.svelte.js';
22
+ import { parseCommand } from './commands/parser.js';
23
+ import { executeCommand } from './commands/executor.js';
24
+ import { isSessionLine } from './commands/session.js';
25
+ import { createStoreCommandContext } from './commands/storeIntegration.svelte.js';
26
+ import { dispatchUIAction } from './commands/uiActionTarget.js';
27
+ import { validateCommand } from './commands/validate.js';
22
28
  // ---------------------------------------------------------------------------
23
29
  // Instance acquisition
24
30
  // ---------------------------------------------------------------------------
@@ -134,6 +140,120 @@ function attachWebMCPToMount(fd, options, isDestroyed) {
134
140
  });
135
141
  });
136
142
  }
143
+ /**
144
+ * Build `runCommand` for a mount (shared by `mountFlowDropApp` and
145
+ * `mountWorkflowEditor`).
146
+ *
147
+ * @param isDestroyed - Whether the mount is gone.
148
+ * @param registerCancel - Registers a callback the mount calls on destroy to
149
+ * settle a call still waiting for the workflow; returns its unregister.
150
+ * @param onBaseline - Runs after a successful baseline run, e.g. to tell a
151
+ * draft manager the re-baselined workflow is not an unsaved draft.
152
+ */
153
+ function createRunCommand(fd, isDestroyed, registerCancel, onBaseline) {
154
+ const gone = () => ({
155
+ ok: false,
156
+ code: 'NO_WORKFLOW',
157
+ error: 'The editor was destroyed before a workflow was available.'
158
+ });
159
+ const run = (command, options) => {
160
+ if (isDestroyed() || !fd.workflow.current)
161
+ return gone();
162
+ let parsed;
163
+ if (typeof command === 'string') {
164
+ if (isSessionLine(command)) {
165
+ return {
166
+ ok: false,
167
+ code: 'SESSION_REFUSED',
168
+ error: '`session` commands run only in the editor Console; they are not available here.'
169
+ };
170
+ }
171
+ const result = parseCommand(command);
172
+ if (!result.ok)
173
+ return { ok: false, code: 'PARSE_ERROR', error: result.error };
174
+ parsed = result.command;
175
+ }
176
+ else {
177
+ // Not from the parser: a host may have built it by hand, in plain JS.
178
+ const problem = validateCommand(command);
179
+ if (problem)
180
+ return { ok: false, code: 'INVALID_ARGUMENT', error: problem };
181
+ parsed = command;
182
+ }
183
+ const baseline = options?.baseline === true;
184
+ if (baseline && fd.workflow.isDirty) {
185
+ return {
186
+ ok: false,
187
+ code: 'DIRTY',
188
+ error: 'baseline needs a workflow with no unsaved changes; save or discard them first. Nothing was run.'
189
+ };
190
+ }
191
+ // Undo/redo would step past the saved state and then call it clean.
192
+ if (baseline && (parsed.type === 'undo' || parsed.type === 'redo')) {
193
+ return {
194
+ ok: false,
195
+ code: 'INVALID_ARGUMENT',
196
+ error: `${parsed.type} cannot be run as a baseline. Nothing was run.`
197
+ };
198
+ }
199
+ const context = createStoreCommandContext(fd.nodeTypes.current ?? [], (action) => dispatchUIAction(fd, action), fd);
200
+ if (!context)
201
+ return gone();
202
+ // A baseline run is not a change the host should hear about: on release
203
+ // it is told only what is still true (a failed command that left changes).
204
+ const release = baseline ? fd.workflow.muteCallbacks() : null;
205
+ try {
206
+ const result = executeCommand(parsed, context);
207
+ // A command that changed nothing (`info`, `list nodes`, ...) leaves the
208
+ // workflow clean: keep its undo history.
209
+ if (baseline && result.ok && fd.workflow.isDirty) {
210
+ const current = fd.workflow.current;
211
+ if (current)
212
+ fd.workflow.initialize(current);
213
+ onBaseline?.();
214
+ }
215
+ return result;
216
+ }
217
+ finally {
218
+ release?.();
219
+ }
220
+ };
221
+ // The promise never rejects, whatever the executor does.
222
+ const settle = (command, options) => {
223
+ try {
224
+ return run(command, options);
225
+ }
226
+ catch (error) {
227
+ logger.error('runCommand failed:', error);
228
+ return {
229
+ ok: false,
230
+ code: 'INTERNAL_ERROR',
231
+ error: `The command failed: ${error instanceof Error ? error.message : String(error)}`
232
+ };
233
+ }
234
+ };
235
+ return (command, options) => new Promise((resolve) => {
236
+ if (isDestroyed())
237
+ return resolve(gone());
238
+ let settled = false;
239
+ let unregister = null;
240
+ const finish = (result) => {
241
+ if (settled)
242
+ return;
243
+ settled = true;
244
+ unregister?.();
245
+ resolve(result);
246
+ };
247
+ // Fires at once when the workflow is already loaded.
248
+ const stopWaiting = whenWorkflowLoaded(fd, () => finish(settle(command, options)));
249
+ if (!settled) {
250
+ unregister = registerCancel(() => {
251
+ stopWaiting();
252
+ finish(gone());
253
+ });
254
+ }
255
+ });
256
+ }
137
257
  /**
138
258
  * Mount the full FlowDrop App with navbar, sidebars, and workflow editor
139
259
  *
@@ -159,7 +279,7 @@ function attachWebMCPToMount(fd, options, isDestroyed) {
159
279
  * ```
160
280
  */
161
281
  export async function mountFlowDropApp(container, options = {}) {
162
- const { workflow, nodes, endpointConfig, portConfig, categories, height = '100vh', width = '100%', showNavbar = false, disableSidebar, configPlacement, consolePlacement, mode, editorMode, onEditorModeChange, playground, pipelineId, navbarTitle, navbarActions, branding, showSettings, showStatus, authProvider, eventHandlers, features: userFeatures, settings: initialSettings, colorScheme, draftStorageKey: customDraftKey, draftStorage, formatAdapters, workflowFormats, theme, settingsCategories, showSettingsSyncButton, showSettingsResetButton, instanceId, webmcp, host, contextMenu } = options;
282
+ const { workflow, nodes, endpointConfig, portConfig, categories, height = '100vh', width = '100%', showNavbar = false, disableSidebar, configPlacement, consolePlacement, mode, editorMode, onEditorModeChange, playground, pipelineId, navbarTitle, navbarActions, branding, showSettings, showStatus, authProvider, eventHandlers, features: userFeatures, settings: initialSettings, colorScheme, draftStorageKey: customDraftKey, draftStorage, formatAdapters, workflowFormats, workflowSettingsSchema, theme, settingsCategories, showSettingsSyncButton, showSettingsResetButton, instanceId, webmcp, host, contextMenu } = options;
163
283
  // Per-instance state container — this is what allows multiple FlowDrop
164
284
  // editors to coexist on one page without sharing workflow/history state.
165
285
  const { fd, isDefault } = acquireInstance(instanceId);
@@ -239,6 +359,9 @@ export async function mountFlowDropApp(container, options = {}) {
239
359
  onSaveError: eventHandlers?.onSaveError,
240
360
  onApiError: eventHandlers?.onApiError,
241
361
  onWorkflowLoad: eventHandlers?.onWorkflowLoad,
362
+ onExternalEdit: eventHandlers?.onExternalEdit
363
+ ? (node, link) => eventHandlers.onExternalEdit(node, link)
364
+ : undefined,
242
365
  onBeforeSwap: eventHandlers?.onBeforeSwap,
243
366
  onAfterSwap: eventHandlers?.onAfterSwap,
244
367
  features,
@@ -247,6 +370,7 @@ export async function mountFlowDropApp(container, options = {}) {
247
370
  showSettingsSyncButton,
248
371
  showSettingsResetButton,
249
372
  workflowFormats,
373
+ workflowSettingsSchema,
250
374
  contextMenu
251
375
  }
252
376
  });
@@ -295,6 +419,8 @@ export async function mountFlowDropApp(container, options = {}) {
295
419
  // its default `onSave` is `mountedApp.save()`.
296
420
  let webmcpHandle;
297
421
  let destroyed = false;
422
+ // Calls to runCommand still waiting for the workflow; settled on destroy.
423
+ const pendingRuns = new Set();
298
424
  // Create the mounted app interface
299
425
  const mountedApp = {
300
426
  instance: fd,
@@ -305,6 +431,8 @@ export async function mountFlowDropApp(container, options = {}) {
305
431
  // Remove the agent-facing tools before anything else goes away.
306
432
  destroyed = true;
307
433
  webmcpHandle?.detach();
434
+ for (const cancel of [...pendingRuns])
435
+ cancel();
308
436
  // Call onBeforeUnmount if provided
309
437
  if (state.eventHandlers?.onBeforeUnmount) {
310
438
  const currentWorkflow = fd.workflow.current;
@@ -355,6 +483,12 @@ export async function mountFlowDropApp(container, options = {}) {
355
483
  }
356
484
  },
357
485
  getWorkflow: () => fd.workflow.current,
486
+ runCommand: createRunCommand(fd, () => destroyed, (cancel) => {
487
+ pendingRuns.add(cancel);
488
+ return () => pendingRuns.delete(cancel);
489
+ },
490
+ // The re-baselined workflow is clean, so it is not a draft to restore.
491
+ () => state.draftManager?.markAsSaved()),
358
492
  save: async () => {
359
493
  return globalSaveWorkflow({
360
494
  instance: fd,
@@ -462,16 +596,25 @@ export async function mountWorkflowEditor(container, options = {}) {
462
596
  contextMenu
463
597
  }
464
598
  });
599
+ let destroyed = false;
600
+ const pendingRuns = new Set();
465
601
  // Create the mounted app interface (simpler version)
466
602
  const mountedApp = {
467
603
  instance: fd,
468
604
  destroy: () => {
605
+ destroyed = true;
606
+ for (const cancel of [...pendingRuns])
607
+ cancel();
469
608
  releaseInstance(fd, isDefault);
470
609
  unmount(svelteApp);
471
610
  },
472
611
  isDirty: () => fd.workflow.isDirty,
473
612
  markAsSaved: () => fd.workflow.markAsSaved(),
474
613
  getWorkflow: () => fd.workflow.current,
614
+ runCommand: createRunCommand(fd, () => destroyed, (cancel) => {
615
+ pendingRuns.add(cancel);
616
+ return () => pendingRuns.delete(cancel);
617
+ }),
475
618
  save: async () => {
476
619
  return globalSaveWorkflow({ instance: fd });
477
620
  },
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @module types/events
8
8
  */
9
- import type { Workflow, NodeExecutionInfo, WorkflowNode } from './index.js';
9
+ import type { Workflow, NodeExecutionInfo, WorkflowNode, ConfigValues, ExternalEditLink } from './index.js';
10
10
  import type { SwapEventContext, SwapResult } from '../utils/nodeSwap.js';
11
11
  /**
12
12
  * Types of workflow changes
@@ -36,6 +36,23 @@ export type WorkflowChangeType = 'node_add' | 'node_remove' | 'node_move' | 'nod
36
36
  * ```
37
37
  */
38
38
  export interface FlowDropEventHandlers {
39
+ /**
40
+ * Called instead of opening a node's externalEditLink. Resolve with the new
41
+ * config to write it into the node (one undo step), or with nothing to leave
42
+ * the node as it is.
43
+ *
44
+ * `node` and `link` are copies: changing them does not change the workflow;
45
+ * return the config instead. The returned config replaces the node's
46
+ * config; it is not merged, and it is copied, so changing the object later
47
+ * does not change the workflow either. Anything but a plain object is
48
+ * ignored. A rejection is logged and leaves the node unchanged. While the
49
+ * editor is read-only or locked the handler is still called but its result
50
+ * is not written (a console warning says so).
51
+ *
52
+ * @param node - The node whose external edit link was activated
53
+ * @param link - That node's resolved external edit link
54
+ */
55
+ onExternalEdit?(node: WorkflowNode, link: ExternalEditLink): ConfigValues | void | Promise<ConfigValues | void>;
39
56
  /**
40
57
  * Called when workflow changes (any modification)
41
58
  *
@@ -546,6 +546,9 @@ export interface ExternalEditLink {
546
546
  /**
547
547
  * Callback URL parameter name for FlowDrop to receive updates
548
548
  * If set, the external form should redirect back with config updates
549
+ *
550
+ * @deprecated Nothing passes a callback URL, so this has no effect. Handle the
551
+ * round trip in the host with `FlowDropEventHandlers.onExternalEdit` instead.
549
552
  */
550
553
  callbackUrlParam?: string;
551
554
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Host-handled external editing (`onExternalEdit`).
3
+ *
4
+ * Calls the host's handler for a node's external edit link and, when the host
5
+ * resolves with a config, writes it into the node as one undo step.
6
+ *
7
+ * @module utils/externalEdit
8
+ */
9
+ import type { ConfigValues, ExternalEditLink, Workflow, WorkflowNode } from '../types/index.js';
10
+ /** The slice of the workflow store this needs. */
11
+ export interface ExternalEditStore {
12
+ readonly current: Workflow | null;
13
+ updateNodeConfig(nodeId: string, updates: Partial<WorkflowNode>): void;
14
+ finalizeNodeConfig(): void;
15
+ }
16
+ export interface RunExternalEditOptions {
17
+ node: WorkflowNode;
18
+ link: ExternalEditLink;
19
+ /** The host's `onExternalEdit` handler. */
20
+ handler: (node: WorkflowNode, link: ExternalEditLink) => ConfigValues | void | Promise<ConfigValues | void>;
21
+ store: ExternalEditStore;
22
+ /**
23
+ * Whether the editor accepts the result, asked when the handler resolves
24
+ * (the editor may have been locked while the host form was open). False
25
+ * when read-only or locked: the handler is still called (the link is shown
26
+ * there), but its result is not written. Defaults to writable.
27
+ */
28
+ canWrite?: () => boolean;
29
+ /**
30
+ * Ids of nodes whose host form is open. A node already in it is skipped
31
+ * (the handler is not called again); the caller keeps the set alive.
32
+ */
33
+ pending?: Set<string>;
34
+ /** Called with the node as written, e.g. to refresh the canvas. */
35
+ onWritten?: (node: WorkflowNode) => void;
36
+ }
37
+ /**
38
+ * Run the host handler and apply its result.
39
+ *
40
+ * - A config replaces the node's config (not merged): one undo step, workflow dirty.
41
+ * It is copied, so the host keeps no reference into the workflow.
42
+ * - Anything but a plain object (an array, a string, ...) is logged and dropped.
43
+ * - Nothing resolved: the node is left as it is.
44
+ * - A rejection is logged and swallowed.
45
+ * - A node deleted while the host form was open: the result is dropped.
46
+ * - A node whose host form is already open (`pending`): nothing happens.
47
+ */
48
+ export declare function runExternalEdit(options: RunExternalEditOptions): Promise<void>;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Host-handled external editing (`onExternalEdit`).
3
+ *
4
+ * Calls the host's handler for a node's external edit link and, when the host
5
+ * resolves with a config, writes it into the node as one undo step.
6
+ *
7
+ * @module utils/externalEdit
8
+ */
9
+ import { logger } from './logger.js';
10
+ /**
11
+ * Run the host handler and apply its result.
12
+ *
13
+ * - A config replaces the node's config (not merged): one undo step, workflow dirty.
14
+ * It is copied, so the host keeps no reference into the workflow.
15
+ * - Anything but a plain object (an array, a string, ...) is logged and dropped.
16
+ * - Nothing resolved: the node is left as it is.
17
+ * - A rejection is logged and swallowed.
18
+ * - A node deleted while the host form was open: the result is dropped.
19
+ * - A node whose host form is already open (`pending`): nothing happens.
20
+ */
21
+ export async function runExternalEdit(options) {
22
+ const { node, link, handler, store, canWrite, pending, onWritten } = options;
23
+ if (pending?.has(node.id))
24
+ return;
25
+ pending?.add(node.id);
26
+ let result;
27
+ try {
28
+ result = await handler(node, link);
29
+ }
30
+ catch (error) {
31
+ logger.warn('onExternalEdit rejected; node left unchanged:', error);
32
+ return;
33
+ }
34
+ finally {
35
+ pending?.delete(node.id);
36
+ }
37
+ if (result === undefined || result === null)
38
+ return;
39
+ if (typeof result !== 'object' || Array.isArray(result)) {
40
+ logger.warn('onExternalEdit resolved with something other than a config object; ignored:', result);
41
+ return;
42
+ }
43
+ if (canWrite && !canWrite()) {
44
+ logger.warn('onExternalEdit result ignored: the editor is read-only or locked');
45
+ return;
46
+ }
47
+ // A copy, so the host keeps no reference into the workflow (a Svelte host's
48
+ // `$state` proxy included).
49
+ const config = $state.snapshot(result);
50
+ const current = store.current?.nodes.find((n) => n.id === node.id);
51
+ if (!current) {
52
+ logger.debug(`onExternalEdit result dropped: node ${node.id} no longer exists`);
53
+ return;
54
+ }
55
+ // Close any open field-editing session first so this is a step of its own.
56
+ store.finalizeNodeConfig();
57
+ store.updateNodeConfig(node.id, { data: { ...current.data, config } });
58
+ store.finalizeNodeConfig();
59
+ const written = store.current?.nodes.find((n) => n.id === node.id);
60
+ if (written)
61
+ onWritten?.(written);
62
+ }
@@ -8,6 +8,11 @@ export interface ExternalLinkInfo {
8
8
  title?: string;
9
9
  href: string;
10
10
  newTab: boolean;
11
+ /**
12
+ * When set, a plain left click calls this instead of following the link
13
+ * (the host opens its own form). Modified clicks still follow the href.
14
+ */
15
+ onActivate?: () => void;
11
16
  }
12
17
  export interface InspectorContext {
13
18
  /** The form tab currently shown. */
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "A drop-in visual workflow editor for any web application. You own the backend. You own the data. You own the orchestration.",
4
4
  "license": "MIT",
5
5
  "private": false,
6
- "version": "2.14.0",
6
+ "version": "2.15.0",
7
7
  "author": "Shibin Das (D34dMan)",
8
8
  "bugs": {
9
9
  "url": "https://github.com/flowdrop-io/flowdrop/issues"