@dudousxd/nestjs-catalog-react 0.26.0 → 0.28.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.
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { isTransformLanguage, transformShape } from '@dudousxd/nestjs-catalog/client';
2
+ import { isTransformLanguage, isTransformMode, recordModeRefusal, transformMode, transformShape, } from '@dudousxd/nestjs-catalog/client';
3
3
  import { useMutation } from '@tanstack/react-query';
4
4
  import { ArrowLeft, Play } from 'lucide-react';
5
5
  import { useState } from 'react';
@@ -72,6 +72,63 @@ return [{
72
72
  "critical": int(r["risk"]) >= 80,
73
73
  } for r in records]`,
74
74
  };
75
+ /**
76
+ * Starter code for the per-record mode.
77
+ *
78
+ * A second table rather than a branch inside the first, so that adding a
79
+ * language without a per-record starter is a type error in the same way adding
80
+ * one without a batch starter already is.
81
+ *
82
+ * Python is absent from this table and cannot be here: its harness writes
83
+ * `def transform(records, context):` and there is no second `def` yet, which is
84
+ * why `recordModeRefusal` refuses the combination outright. The type says so —
85
+ * the key set is the two languages the mode can actually run in — rather than
86
+ * carrying a starter for a mode the server will reject.
87
+ */
88
+ const RECORD_STARTERS = {
89
+ typescript: `import type { CatalogRecordTransformFunction } from '@dudousxd/nestjs-catalog/client';
90
+
91
+ // One record in, one row out. This runs once per record over a stream, so
92
+ // nothing anywhere holds the whole read — see the mode selector above.
93
+ type Source = { tag: string; risk: string; kind: string };
94
+
95
+ const transform: CatalogRecordTransformFunction<Source> = ({ record, context }) => ({
96
+ assetId: record.tag,
97
+ riskScore: Number(record.risk),
98
+ vehicleTypeName: record.kind.toUpperCase(),
99
+ critical: Number(record.risk) >= 80,
100
+ });
101
+
102
+ export default transform;`,
103
+ javascript: `// One record in, one row out — this runs once per record over a stream.
104
+ // Return an array to turn one record into several, or null to drop it.
105
+ export default function transform({ record, context }) {
106
+ return {
107
+ assetId: record.tag,
108
+ riskScore: Number(record.risk),
109
+ vehicleTypeName: String(record.kind).toUpperCase(),
110
+ critical: Number(record.risk) >= 80,
111
+ };
112
+ }`,
113
+ };
114
+ /**
115
+ * What an empty editor opens with, for this language in this mode.
116
+ *
117
+ * One function so the two tables are consulted in one place. A per-record
118
+ * Python transform has no starter because it has no harness; it falls back to
119
+ * the batch one, and `recordModeRefusal` is what tells the author why the
120
+ * combination cannot be saved — a starter that pretended otherwise would be the
121
+ * editor teaching a shape the server refuses.
122
+ */
123
+ function starterFor(language, mode) {
124
+ if (mode === 'record' && language !== 'python')
125
+ return RECORD_STARTERS[language];
126
+ return STARTERS[language];
127
+ }
128
+ /** Every starter, so "has this been edited" can be asked without listing them. */
129
+ function isUntouchedStarter(code) {
130
+ return Object.values(STARTERS).includes(code) || Object.values(RECORD_STARTERS).includes(code);
131
+ }
75
132
  const SAMPLE = `[
76
133
  { "tag": "AF93E00073", "risk": "88", "kind": "truck" },
77
134
  { "tag": "AF00D00169", "risk": "12", "kind": "sedan" }
@@ -113,13 +170,18 @@ function TryOutput({ result, error }) {
113
170
  * Not shown for Python, which has one shape and no rule: its harness writes the
114
171
  * `def` itself, so there is nothing here for an author to have got wrong.
115
172
  */
116
- function ShapeBadge({ language, code }) {
173
+ function ShapeBadge({ language, code, mode, }) {
117
174
  if (language === 'python')
118
175
  return null;
119
176
  const shape = transformShape(code);
120
177
  const isModule = shape === 'module';
178
+ // The argument named in the tooltip follows the selected mode, because that is
179
+ // what the harness will actually pass. A badge that said `{ records, context }`
180
+ // beside a per-record selector would be reassuring somebody about a call that
181
+ // is not going to happen.
182
+ const argument = mode === 'record' ? '{ record, context }' : '{ records, context }';
121
183
  return (_jsx(Tooltip, { content: isModule
122
- ? 'A top-level `export`, so this is imported as a module and its default export (or an export named `transform`) is called with one object: { records, context }. Fields can be added to that object later without changing this signature.'
184
+ ? `A top-level \`export\`, so this is imported as a module and its default export (or an export named \`transform\`) is called with one object: ${argument}. Fields can be added to that object later without changing this signature.`
123
185
  : 'No top-level `export`, so this runs as the body of a function that already has `records` and `context` in scope. Supported and unchanged — `export default function transform({ records, context })` is the shape that can gain fields later.', children: _jsx("span", { className: cn('cursor-default rounded border px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-[0.14em]', RULE, MUTED), children: isModule ? 'function' : 'bare body' }) }));
124
186
  }
125
187
  /**
@@ -130,15 +192,16 @@ function ShapeBadge({ language, code }) {
130
192
  * the code it was pinned to — and it should be visible before the click, not
131
193
  * explained after it.
132
194
  */
133
- function SaveBar({ transform, nameIsEmpty, pending, error, onSave, }) {
134
- return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: onSave, disabled: pending || nameIsEmpty, className: cn('rounded-md border px-3 py-1.5 text-xs disabled:opacity-40', RULE, 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: pending ? 'Saving…' : transform ? 'Save changes' : 'Save transform' }), transform && (_jsxs("span", { className: cn('font-mono text-[10px]', MUTED), children: ["saving new code makes this v", transform.version + 1] })), error ? (_jsx("span", { className: "text-[11px] text-red-600", children: error instanceof Error ? error.message : 'Could not save.' })) : null] }));
195
+ function SaveBar({ transform, nameIsEmpty, refused, pending, error, onSave, }) {
196
+ return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: onSave, disabled: pending || nameIsEmpty || refused, className: cn('rounded-md border px-3 py-1.5 text-xs disabled:opacity-40', RULE, 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: pending ? 'Saving…' : transform ? 'Save changes' : 'Save transform' }), transform && (_jsxs("span", { className: cn('font-mono text-[10px]', MUTED), children: ["saving new code makes this v", transform.version + 1] })), error ? (_jsx("span", { className: "text-[11px] text-red-600", children: error instanceof Error ? error.message : 'Could not save.' })) : null] }));
135
197
  }
136
198
  export function TransformEditor({ transform, languages, pythonPackages = [], onClose, onSaved, }) {
137
199
  const client = useCatalogClient();
138
200
  const [name, setName] = useState(transform?.name ?? '');
139
201
  const [description, setDescription] = useState(transform?.description ?? '');
140
202
  const [language, setLanguage] = useState(transform?.language ?? languages[0] ?? 'javascript');
141
- const [code, setCode] = useState(transform?.code ?? STARTERS[transform?.language ?? 'javascript']);
203
+ const [mode, setMode] = useState(transform ? transformMode(transform) : 'batch');
204
+ const [code, setCode] = useState(transform?.code ?? starterFor(transform?.language ?? 'javascript', 'batch'));
142
205
  const [sample, setSample] = useState(SAMPLE);
143
206
  const [historyOpen, setHistoryOpen] = useState(false);
144
207
  const tryIt = useMutation({
@@ -154,7 +217,11 @@ export function TransformEditor({ transform, languages, pythonPackages = [], onC
154
217
  // person reading it would go looking at their transform.
155
218
  throw new Error('The sample is not valid JSON.');
156
219
  }
157
- return client.tryTransform({ language, code, records });
220
+ // The mode goes with it, so the pane runs the code under the contract the
221
+ // author has selected rather than under whichever one the server would
222
+ // default to. A per-record transform tried as a batch is handed the whole
223
+ // array as its `record` and shows empty rows for correct code.
224
+ return client.tryTransform({ language, code, records, mode });
158
225
  },
159
226
  });
160
227
  const save = useMutation({
@@ -163,10 +230,14 @@ export function TransformEditor({ transform, languages, pythonPackages = [], onC
163
230
  name: name.trim(),
164
231
  language,
165
232
  code,
233
+ mode,
166
234
  description: description.trim() || undefined,
167
235
  }),
168
236
  onSuccess: onSaved,
169
237
  });
238
+ // The same question the controller asks, from the same function, so the
239
+ // editor and the server cannot disagree about which combinations are legal.
240
+ const refusal = recordModeRefusal({ language, code, mode });
170
241
  // `preventDefault` is what claims the key. The editor's default keymap binds
171
242
  // ⌘↵ to "insert a blank line", and `CodeEditor` only withholds a keystroke
172
243
  // from it when the host has said it wants it — so without this, trying the
@@ -185,20 +256,30 @@ export function TransformEditor({ transform, languages, pythonPackages = [], onC
185
256
  setLanguage(value);
186
257
  // Only replace untouched starter code — silently discarding
187
258
  // somebody's work because they changed a dropdown would be rude.
188
- if (Object.values(STARTERS).includes(code)) {
189
- setCode(STARTERS[value]);
190
- }
259
+ if (isUntouchedStarter(code))
260
+ setCode(starterFor(value, mode));
191
261
  }, options: languages.map((option) => ({
192
262
  value: option,
193
263
  label: option,
194
- })) })] }), _jsxs("div", { className: "grid gap-3 lg:grid-cols-2", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsxs("div", { className: cn('flex items-center justify-between border-b px-3 py-1.5', RULE), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Code" }), _jsx(ShapeBadge, { language: language, code: code })] }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: language === 'python' && pythonPackages.length > 0
264
+ })) })] }), _jsxs("div", { className: "grid gap-3 sm:grid-cols-3", children: [_jsx(SelectField, { label: "Called", ariaLabel: "Called", value: mode, onValueChange: (value) => {
265
+ if (!isTransformMode(value))
266
+ return;
267
+ setMode(value);
268
+ if (isUntouchedStarter(code))
269
+ setCode(starterFor(language, value));
270
+ }, options: [
271
+ { value: 'batch', label: 'once with the whole batch' },
272
+ { value: 'record', label: 'once per record (streams)' },
273
+ ] }), _jsx("p", { className: cn('sm:col-span-2 self-center text-xs leading-relaxed', MUTED), children: mode === 'record'
274
+ ? 'Each record is mapped on its own and the rows are written as they are produced, so nothing holds the whole read. Return one object, an array of them, or null to drop the record. Aggregating, deduplicating and sorting need the whole batch and cannot be written this way.'
275
+ : 'The code is called once with every record, which is what aggregating, deduplicating, sorting and joining need. The whole read is held in memory while it runs.' })] }), refusal ? (_jsx("p", { className: "rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-xs leading-relaxed text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-200", children: refusal })) : null, _jsxs("div", { className: "grid gap-3 lg:grid-cols-2", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsxs("div", { className: cn('flex items-center justify-between border-b px-3 py-1.5', RULE), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Code" }), _jsx(ShapeBadge, { language: language, code: code, mode: mode })] }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: language === 'python' && pythonPackages.length > 0
195
276
  ? `imports: ${pythonPackages.join(', ')}`
196
277
  : '⌘↵ to try' })] }), _jsx(CodeEditor, { value: code, onChange: setCode, onKeyDown: onKeyDown,
197
278
  // A table rather than the `language === 'python' ? 'python' : 'tsx'`
198
279
  // that used to be here. The ternary answered a fourth transform
199
280
  // language with `tsx` — silently, and wrongly — where the table
200
281
  // cannot be indexed by one at all until somebody adds the row.
201
- language: TRANSFORM_HIGHLIGHTED_AS[language], label: "Transform code", className: "h-72" })] }), _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Sample records" }) }), _jsx(CodeEditor, { value: sample, onChange: setSample, language: "json", label: "Sample records", className: "h-32" })] }), _jsxs("button", { type: "button", onClick: () => tryIt.mutate(), disabled: tryIt.isPending, className: "flex items-center gap-1.5 rounded-md bg-zinc-950 px-3 py-1.5 text-xs text-zinc-50 disabled:opacity-40 dark:bg-zinc-100 dark:text-zinc-950", children: [_jsx(Play, { size: 12 }), tryIt.isPending ? 'Running…' : 'Try it'] }), _jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Output" }) }), _jsx(TryOutput, { result: tryIt.data, error: tryIt.error })] })] })] }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx(SaveBar, { transform: transform, nameIsEmpty: name.trim().length === 0, pending: save.isPending, error: save.error, onSave: () => save.mutate() }), transform && (_jsx(RevisionHistoryButton, { className: "ml-auto", onClick: () => setHistoryOpen(true) }))] }), transform && (_jsx(RevisionHistorySheet, { open: historyOpen, onOpenChange: setHistoryOpen, subject: { kind: 'transform', id: transform.id, name: transform.name },
282
+ language: TRANSFORM_HIGHLIGHTED_AS[language], label: "Transform code", className: "h-72" })] }), _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Sample records" }) }), _jsx(CodeEditor, { value: sample, onChange: setSample, language: "json", label: "Sample records", className: "h-32" })] }), _jsxs("button", { type: "button", onClick: () => tryIt.mutate(), disabled: tryIt.isPending, className: "flex items-center gap-1.5 rounded-md bg-zinc-950 px-3 py-1.5 text-xs text-zinc-50 disabled:opacity-40 dark:bg-zinc-100 dark:text-zinc-950", children: [_jsx(Play, { size: 12 }), tryIt.isPending ? 'Running…' : 'Try it'] }), _jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Output" }) }), _jsx(TryOutput, { result: tryIt.data, error: tryIt.error })] })] })] }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx(SaveBar, { refused: refusal !== undefined, transform: transform, nameIsEmpty: name.trim().length === 0, pending: save.isPending, error: save.error, onSave: () => save.mutate() }), transform && (_jsx(RevisionHistoryButton, { className: "ml-auto", onClick: () => setHistoryOpen(true) }))] }), transform && (_jsx(RevisionHistorySheet, { open: historyOpen, onOpenChange: setHistoryOpen, subject: { kind: 'transform', id: transform.id, name: transform.name },
202
283
  // The SAVED code, not what is in the editor above. A history is what
203
284
  // this catalog has recorded; comparing against an unsaved buffer would
204
285
  // put a version number on text that exists only in one browser tab,
@@ -7,7 +7,7 @@ import { Background, BackgroundVariant, ConnectionLineType, Controls, MiniMap, P
7
7
  // See src/styles.d.ts for why `tsc` tolerates this import.
8
8
  import '@xyflow/react/dist/style.css';
9
9
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
10
- import { ArrowRight, ChevronDown, CircleAlert, CircleDashed, Code2, Database, ExternalLink, Filter, GitBranch, Info, LayoutGrid, Loader2, Maximize2, Minimize2, PanelRight, Plug, Plus, Repeat, Save, Trash2, TriangleAlert, Unplug, X, } from 'lucide-react';
10
+ import { ArrowRight, ChevronDown, CircleAlert, CircleDashed, Code2, Database, ExternalLink, Filter, GitBranch, Info, LayoutGrid, Loader2, Maximize2, Minimize2, PanelRight, Plug, Plus, Repeat, Save, TextCursorInput, Trash2, TriangleAlert, Unplug, X, } from 'lucide-react';
11
11
  import { AnimatePresence, motion, useReducedMotion } from 'motion/react';
12
12
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
13
13
  import { connectionOptionsFor } from './ConnectionPanel';
@@ -32,7 +32,7 @@ import { defaultLabel, describeFilterPredicate, flowingEdgeIds, layout, layoutIf
32
32
  import { HistoryControls, keepKnown, namesOf, nodeEditAction, reverted, snapshotOf, undone, useUndoShortcut, useUnsavedGuard, withEdit, } from './workflow/history';
33
33
  import { PublishControls, RunControls, SchedulePanel, ShrinkRefusalNote, WorkflowStatusBadge, } from './workflow/lifecycle';
34
34
  import { CanvasContextMenu, NodeActionsToolbar } from './workflow/menu';
35
- import { WORKFLOW_BRANCH_LABELS, WORKFLOW_CALL_MODES, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_NODE_KINDS, callableWorkflowBlock, describeDurability, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicateKind, isWorkflowNodeKind, isWorkflowPredicateKind, newLocalId, nodeName, producedTypes, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, workflowCallMode, workflowNarrowedTypes, } from './workflow/model';
35
+ import { WORKFLOW_BRANCH_LABELS, WORKFLOW_CALL_MODES, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_NODE_KINDS, WORKFLOW_RENAME_MAX_COLUMNS, callableWorkflowBlock, describeDurability, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicateKind, isWorkflowNodeKind, isWorkflowPredicateKind, isWorkflowRenameUnnamed, newLocalId, nodeName, producedTypes, renameColumnRefusals, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, workflowCallMode, workflowKnownColumns, workflowNarrowedTypes, workflowRenameUnnamed, } from './workflow/model';
36
36
  import { WORKFLOW_NAME } from './workflow/name';
37
37
  import { WorkflowNodeProvider, workflowNodeTypes } from './workflow/nodes';
38
38
  import { freeSpot, placeNextTo } from './workflow/place';
@@ -460,6 +460,11 @@ const ADD_NODE = {
460
460
  label: 'Filter',
461
461
  hint: 'Drops the rows that fail a test you write here. Unlike an If, every box still runs — there are simply fewer rows in them from this point on.',
462
462
  },
463
+ rename: {
464
+ icon: TextCursorInput,
465
+ label: 'Rename',
466
+ hint: 'Renames columns, and nothing else. No code, no child process — a pure rename rewrites the staged column list and leaves every row exactly where it is. It can also drop the columns you do not name, which does cost a pass over the rows.',
467
+ },
463
468
  };
464
469
  /**
465
470
  * The value the workflow picker uses for "start a fresh one".
@@ -873,6 +878,11 @@ function miniMapColor(data) {
873
878
  // that answer that question in completely different ways.
874
879
  if (kind === 'filter')
875
880
  return '#f43f5e';
881
+ // Teal-500, the rename's own accent. Deliberately not the violet a transform
882
+ // gets: a rename is the node that is *provably* cheap, and an overview where
883
+ // it reads as another piece of user code hides the one thing worth seeing.
884
+ if (kind === 'rename')
885
+ return '#14b8a6';
876
886
  return '#8b5cf6';
877
887
  }
878
888
  /**
@@ -3384,6 +3394,62 @@ function RowCountPredicateFields({ predicate, canEdit, onChange, }) {
3384
3394
  * question is live — offering them on a filter that narrows nothing would train
3385
3395
  * people to flip them.
3386
3396
  */
3397
+ /**
3398
+ * The rename node's form: a list of columns, and one decision about the rest.
3399
+ *
3400
+ * ## Why the list is local state and the record is not
3401
+ *
3402
+ * The model is a `Record<string, string>`, which is the right shape to store —
3403
+ * a key cannot appear twice, so "two renames of the same source column" is
3404
+ * unrepresentable rather than merely refused. It is the wrong shape to *edit*:
3405
+ * a half-typed key is a key, and rebuilding the record on every keystroke would
3406
+ * collapse two rows the moment they were briefly equal — most obviously the two
3407
+ * blank rows you get by pressing "Add column" twice.
3408
+ *
3409
+ * So the rows are held here, in order, and the record is derived from them. The
3410
+ * one thing that can diverge is two rows naming the same source column, and
3411
+ * that is said out loud below rather than silently resolved.
3412
+ *
3413
+ * ## What the panel can tell somebody that a transform's could not
3414
+ *
3415
+ * Which columns actually reach this node — sometimes. `workflowKnownColumns` is
3416
+ * exact downstream of a rename that drops what it does not name, unknown
3417
+ * everywhere else, and the difference is stated rather than papered over. This
3418
+ * is the whole payoff of the node being data instead of code, so the panel
3419
+ * should say it in as many words.
3420
+ */
3421
+ function RenameInspector({ node, graph, canEdit, onChange, }) {
3422
+ const map = node.columns ?? {};
3423
+ const [rows, setRows] = useState(() => {
3424
+ const entries = Object.entries(map).map(([from, to]) => ({ from, to }));
3425
+ return entries.length > 0 ? entries : [{ from: '', to: '' }];
3426
+ });
3427
+ const commit = (next) => {
3428
+ setRows(next);
3429
+ const columns = {};
3430
+ for (const row of next)
3431
+ columns[row.from] = row.to;
3432
+ onChange({ ...node, columns });
3433
+ };
3434
+ const setUnnamed = (value) => {
3435
+ if (!isWorkflowRenameUnnamed(value))
3436
+ return;
3437
+ // Stored absent for `keep`, so the default has one spelling and picking up
3438
+ // this release cannot renumber a graph nobody edited. The boundary
3439
+ // normalises the same way.
3440
+ onChange({ ...node, unnamed: value === 'drop' ? 'drop' : undefined });
3441
+ };
3442
+ const dropping = workflowRenameUnnamed(node) === 'drop';
3443
+ const known = workflowKnownColumns(graph, node.id);
3444
+ const refusals = renameColumnRefusals(map);
3445
+ const duplicated = rows
3446
+ .map((row) => row.from)
3447
+ .filter((from, at, all) => from.length > 0 && all.indexOf(from) !== at);
3448
+ return (_jsxs("div", { className: "space-y-3", children: [_jsxs(FieldGroup, { title: "Columns", hint: _jsxs(_Fragment, { children: ["The name the records arrive with, and the name they leave with. The old name is whatever the source actually calls it \u2014 ", _jsx("code", { children: "Mgmt Cd" }), " and ", _jsx("code", { children: "VEH Type Name" }), " are fine. The new one has to be a name a column can have: letters, digits and underscore, starting with a letter or an underscore."] }), children: [rows.map((row, index) => (_jsxs("div", { className: "flex items-end gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(TextField, { label: index === 0 ? 'In the source' : '', value: row.from, placeholder: "Mgmt Cd", disabled: !canEdit, onChange: (from) => commit(rows.map((each, at) => (at === index ? { ...each, from } : each))) }) }), _jsx("div", { className: "min-w-0 flex-1", children: _jsx(TextField, { label: index === 0 ? 'Becomes' : '', value: row.to, placeholder: "mgmtCd", disabled: !canEdit, onChange: (to) => commit(rows.map((each, at) => (at === index ? { ...each, to } : each))) }) }), canEdit && rows.length > 1 && (_jsx(Button, { variant: "ghost", size: "sm", className: "shrink-0", onClick: () => commit(rows.filter((_, at) => at !== index)), children: "Remove" }))] }, index))), canEdit && (_jsx(Button, { variant: "outline", size: "sm", onClick: () => commit([...rows, { from: '', to: '' }]), disabled: rows.length >= WORKFLOW_RENAME_MAX_COLUMNS, children: "Add column" }))] }), _jsx(SelectField, { label: "Columns you did not name", ariaLabel: "What happens to the columns this node does not rename", value: workflowRenameUnnamed(node), onValueChange: setUnnamed, disabled: !canEdit, options: [
3449
+ { value: 'keep', label: 'Pass through unchanged', hint: 'no data moves' },
3450
+ { value: 'drop', label: 'Drop them', hint: 'rebuilds every row' },
3451
+ ] }), _jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: dropping ? (_jsxs(_Fragment, { children: ["This node ", _jsx("strong", { children: "also removes" }), " every column it does not name, so what reaches the sink is exactly the ", Object.keys(map).length, " new name", Object.keys(map).length === 1 ? '' : 's', " above. That is a projection as well as a rename, and it costs a pass over the rows \u2014 a staged batch keeps its values in positional arrays, and taking a column out moves every one of them."] })) : (_jsxs(_Fragment, { children: ["Nothing else changes. A staged batch names its columns once and keeps the values in positional arrays, so renaming one rewrites a handful of strings and", ' ', _jsx("strong", { children: "moves no data at all" }), " \u2014 which is why this is a node rather than four lines of JavaScript in a transform."] })) }), refusals.length > 0 && (_jsx("p", { className: "text-[11px] leading-relaxed text-amber-600 dark:text-amber-400", children: refusals.join(' ') })), duplicated.length > 0 && (_jsxs("p", { className: "text-[11px] leading-relaxed text-amber-600 dark:text-amber-400", children: [duplicated.map((from) => `“${from}”`).join(', '), " appears more than once on the left. A column can only be renamed to one thing, so only the last row naming it is stored."] })), known ? (_jsxs("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: ["A rename above this node drops the columns it does not name, so the graph knows exactly what arrives here:", ' ', _jsx("span", { className: "font-mono", children: [...known].join(', ') || 'nothing at all' }), ". A row on the left naming anything else is refused when this graph is saved, rather than found out when the column comes back empty."] })) : (_jsx("p", { className: cn('text-[11px] leading-relaxed', MUTED), children: "The graph cannot say which columns reach this node \u2014 a source discovers its shape against the live system, and a transform is code. So the old names are taken on trust, and the run says out loud if one of them was in no row." }))] }));
3452
+ }
3387
3453
  function FilterInspector({ node, graph, canEdit, onChange, }) {
3388
3454
  // Core's answer, not this file's. A canvas that worked out its own set would
3389
3455
  // offer acknowledgements the server then refuses, which is a person ticking a
@@ -3715,6 +3781,13 @@ function KindInspector({ node, graph, transforms, connections, typeOptions, canE
3715
3781
  // `WorkflowFilterNode.narrows`.
3716
3782
  return (_jsx(FilterInspector, { node: node, graph: graph, canEdit: canEdit, onChange: onChange }, node.id));
3717
3783
  }
3784
+ if (node.kind === 'rename') {
3785
+ // Given the whole graph for the same reason the filter inspector is, and
3786
+ // with a different question in mind: the one thing a declarative rename
3787
+ // buys is that the graph can sometimes say exactly which columns reach this
3788
+ // node. See `workflowKnownColumns`.
3789
+ return (_jsx(RenameInspector, { node: node, graph: graph, canEdit: canEdit, onChange: onChange }, node.id));
3790
+ }
3718
3791
  if (node.kind === 'sink') {
3719
3792
  return (_jsx(SinkInspector, { node: node, typeOptions: typeOptions, canEdit: canEdit, modelHref: modelHref, onChange: onChange }));
3720
3793
  }
package/dist/context.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CallableWorkflowRef, CatalogAuditEvent, CatalogConnection, CatalogConnector, CatalogObjectPage, CatalogQueryRelation, CatalogQueryResult, CatalogReusableNode, CatalogRevision, CatalogSearchResult, CatalogSnapshot, CatalogTrace, CatalogTraceList, CatalogTransform, ConnectionCheck, ConnectorRun, Dashboard, DashboardCard, DeleteReconciliation, LoadExpectation, LoadExpectationInput, ObjectQueryParams, PropertyPatch, ResolvedLoadExpectation, ReusableNodeBody, RowCountBound, SaveQueryInput, SavedQuery, SnapshotRef, StoredLoadExpectation, TraceQuery, TransformLanguage, TransformResult, TypePatch } from '@dudousxd/nestjs-catalog/client';
1
+ import type { CallableWorkflowRef, CatalogAuditEvent, CatalogConnection, CatalogConnector, CatalogObjectPage, CatalogQueryRelation, CatalogQueryResult, CatalogReusableNode, CatalogRevision, CatalogSearchResult, CatalogSnapshot, CatalogTrace, CatalogTraceList, CatalogTransform, ConnectionCheck, ConnectorRun, Dashboard, DashboardCard, DeleteReconciliation, LoadExpectation, LoadExpectationInput, ObjectQueryParams, PropertyPatch, ResolvedLoadExpectation, ReusableNodeBody, RowCountBound, SaveQueryInput, SavedQuery, SnapshotRef, StoredLoadExpectation, TraceQuery, TransformLanguage, TransformMode, TransformResult, TypePatch } from '@dudousxd/nestjs-catalog/client';
2
2
  import { type ReactNode } from 'react';
3
3
  import type { EmbeddedChartPayload, EmbeddedDashboardPayload } from './embed/payload';
4
4
  import { type PeopleQuery } from './routes';
@@ -153,6 +153,16 @@ export interface TransformInput {
153
153
  description?: string;
154
154
  language: TransformLanguage;
155
155
  code: string;
156
+ /**
157
+ * Whether the code is called once with the batch or once per record.
158
+ *
159
+ * Optional, and **absent means "leave whatever is stored alone"** rather than
160
+ * "make it a batch". A caller written before this field existed sends no mode,
161
+ * and the store reads that as no instruction — so an older client saving a
162
+ * rename cannot silently undo somebody's deliberate choice. See
163
+ * `TRANSFORM_MODES`.
164
+ */
165
+ mode?: TransformMode;
156
166
  }
157
167
  /**
158
168
  * One pipeline that would break if a connection were deleted.
@@ -718,6 +728,15 @@ export interface CatalogClient {
718
728
  language: TransformLanguage;
719
729
  code: string;
720
730
  records: unknown[];
731
+ /**
732
+ * Which contract to run the sample under.
733
+ *
734
+ * Sent by the editor, because a pane that tried a per-record transform as a
735
+ * batch would hand it the whole array as its `record` and show empty rows
736
+ * for correct code — through the one screen whose value is that it predicts
737
+ * what the load will do.
738
+ */
739
+ mode?: TransformMode;
721
740
  }): Promise<TransformResult>;
722
741
  /**
723
742
  * Authored graphs: sources wired through transforms into sinks.
@@ -76,6 +76,21 @@ export function newNodeOfKind(kind, id, position, name) {
76
76
  position,
77
77
  };
78
78
  }
79
+ if (kind === 'rename') {
80
+ // One entry with both halves blank, and the validator refuses it by name
81
+ // from the moment the node is dropped — the same stance `filter` takes and
82
+ // for the same reason. An empty map is representable and is exactly the
83
+ // dangerous state: with unnamed columns kept it is a node that draws as
84
+ // finished and does nothing, and with them dropped it deletes every column
85
+ // of every row. So the node starts visibly incomplete rather than
86
+ // invisibly inert.
87
+ //
88
+ // `unnamed` is left absent, which means keep. A rename that started by
89
+ // dropping everything it does not name would be a projection wearing the
90
+ // word "rename", and somebody would find that out by looking at a committed
91
+ // snapshot.
92
+ return { id, name, kind: 'rename', columns: { '': '' }, position };
93
+ }
79
94
  if (kind === 'sink') {
80
95
  return { id, name, kind: 'sink', targetType: '', position };
81
96
  }
@@ -1,6 +1,6 @@
1
1
  import { WORKFLOW_NODE_HEIGHT, WORKFLOW_NODE_WIDTH, workflowColumnX, workflowRowY, workflowRunOrder, } from '@dudousxd/nestjs-catalog/client';
2
2
  import { MarkerType } from '@xyflow/react';
3
- import { nodeName, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, workflowCallMode, } from './model';
3
+ import { nodeName, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, workflowCallMode, workflowRenameUnnamed, } from './model';
4
4
  import { edgeId } from './validate';
5
5
  /**
6
6
  * Turning the stored graph into what React Flow draws, and back.
@@ -52,6 +52,8 @@ function subtitleFor(node, describe) {
52
52
  return ifSubtitle(node);
53
53
  if (node.kind === 'filter')
54
54
  return filterSubtitle(node);
55
+ if (node.kind === 'rename')
56
+ return renameSubtitle(node);
55
57
  if (node.kind === 'transform') {
56
58
  return describe.transformName(node.transformId) ?? 'no transform chosen';
57
59
  }
@@ -92,6 +94,28 @@ function filterSubtitle(node) {
92
94
  return `keeps rows matching ${leaves} conditions`;
93
95
  return `keeps ${describeFilterPredicate(predicate)}`;
94
96
  }
97
+ /**
98
+ * A rename's face: how many columns, and whether anything else survives.
99
+ *
100
+ * The disposition is on the face rather than only in the inspector because it is
101
+ * the difference between a node that renames and a node that also *deletes* —
102
+ * and a graph where those two look identical is one where a column disappears
103
+ * from a published type with nothing on the canvas to point at.
104
+ *
105
+ * One rename is spelled out, because the overwhelmingly common node has one or
106
+ * two entries and `Mgmt Cd -> mgmtCd` is the whole content of it.
107
+ */
108
+ function renameSubtitle(node) {
109
+ const entries = Object.entries(node.columns ?? {}).filter(([from, to]) => from.length > 0 && to.length > 0);
110
+ const dropped = workflowRenameUnnamed(node) === 'drop';
111
+ if (entries.length === 0)
112
+ return 'no columns named';
113
+ const first = entries[0];
114
+ const what = entries.length === 1 && first
115
+ ? `${first[0]} \u2192 ${first[1]}`
116
+ : `renames ${entries.length} columns`;
117
+ return dropped ? `${what}, drops the rest` : what;
118
+ }
95
119
  /** How many comparisons a predicate is made of, groups not counted. */
96
120
  function countFilterLeaves(predicate) {
97
121
  if (predicate.kind === 'all' || predicate.kind === 'any') {
@@ -335,6 +359,8 @@ export function defaultLabel(kind) {
335
359
  return 'If';
336
360
  if (kind === 'filter')
337
361
  return 'Filter';
362
+ if (kind === 'rename')
363
+ return 'Rename';
338
364
  if (kind === 'transform')
339
365
  return 'Transform';
340
366
  return unreachableNodeKind(kind, 'defaultLabel');
@@ -18,8 +18,8 @@
18
18
  * executes it, it belongs to core; if only this screen has an opinion about it,
19
19
  * it belongs here.
20
20
  */
21
- export type { CallableWorkflowBlock, CallableWorkflowDisagreement, CallableWorkflowRef, CatalogWorkflow, CatalogWorkflowRelease, WorkflowBranchLabel, WorkflowEdge, WorkflowCallMode, WorkflowCallNode, WorkflowEnvPredicate, WorkflowFilterAll, WorkflowFilterAny, WorkflowFilterComparison, WorkflowFilterGroup, WorkflowFilterNode, WorkflowFilterOneOf, WorkflowFilterOperator, WorkflowFilterPredicate, WorkflowFilterPredicateKind, WorkflowFilterPresence, WorkflowFilterValue, WorkflowGraph, WorkflowIfNode, WorkflowIfPredicate, WorkflowNode, WorkflowNodeKind, WorkflowPredicateKind, WorkflowRowCountPredicate, WorkflowSinkNode, WorkflowSkipReason, WorkflowSourceNode, WorkflowTransformNode, } from '@dudousxd/nestjs-catalog/client';
22
- export { callableWorkflowBlock, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicate, isWorkflowFilterPredicateKind, isWorkflowFilterValue, isWorkflowNodeKind, isWorkflowPredicateKind, WORKFLOW_CALL_MODES, unreachableCallMode, workflowCallMode, unreachableFilterOperator, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, workflowNarrowedTypes, WORKFLOW_BRANCH_LABELS, WORKFLOW_FILTER_COLUMN_PATTERN, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_FILTER_PREDICATE_KINDS, WORKFLOW_PREDICATE_KINDS, WORKFLOW_NODE_ID_PATTERN, WORKFLOW_NODE_KINDS, } from '@dudousxd/nestjs-catalog/client';
21
+ export type { CallableWorkflowBlock, CallableWorkflowDisagreement, CallableWorkflowRef, CatalogWorkflow, CatalogWorkflowRelease, WorkflowBranchLabel, WorkflowEdge, WorkflowCallMode, WorkflowCallNode, WorkflowEnvPredicate, WorkflowFilterAll, WorkflowFilterAny, WorkflowFilterComparison, WorkflowFilterGroup, WorkflowFilterNode, WorkflowFilterOneOf, WorkflowFilterOperator, WorkflowFilterPredicate, WorkflowFilterPredicateKind, WorkflowFilterPresence, WorkflowFilterValue, WorkflowGraph, WorkflowIfNode, WorkflowIfPredicate, WorkflowNode, WorkflowNodeKind, WorkflowPredicateKind, WorkflowRenameNode, WorkflowRenameUnnamed, WorkflowRowCountPredicate, WorkflowSinkNode, WorkflowSkipReason, WorkflowSourceNode, WorkflowTransformNode, } from '@dudousxd/nestjs-catalog/client';
22
+ export { callableWorkflowBlock, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicate, isWorkflowFilterPredicateKind, isWorkflowFilterValue, isWorkflowNodeKind, isWorkflowPredicateKind, isWorkflowRenameUnnamed, renameColumnRefusals, workflowKnownColumns, workflowRenameUnnamed, WORKFLOW_CALL_MODES, unreachableCallMode, workflowCallMode, unreachableFilterOperator, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, unreachableRenameUnnamed, workflowNarrowedTypes, WORKFLOW_BRANCH_LABELS, WORKFLOW_FILTER_COLUMN_PATTERN, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_FILTER_PREDICATE_KINDS, WORKFLOW_PREDICATE_KINDS, WORKFLOW_RENAME_MAX_COLUMNS, WORKFLOW_RENAME_UNNAMED, WORKFLOW_NODE_ID_PATTERN, WORKFLOW_NODE_KINDS, } from '@dudousxd/nestjs-catalog/client';
23
23
  import { type WorkflowBranchLabel, type WorkflowNode, type WorkflowSkipReason } from '@dudousxd/nestjs-catalog/client';
24
24
  /**
25
25
  * What a caller may set.
@@ -23,19 +23,25 @@ export {
23
23
  // not a copy: the picker greys an entry out and the server reasons about the
24
24
  // same list, and two copies of that rule is a picker that eventually offers
25
25
  // something the rest of the system will not accept.
26
- callableWorkflowBlock, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicate, isWorkflowFilterPredicateKind, isWorkflowFilterValue, isWorkflowNodeKind, isWorkflowPredicateKind,
26
+ callableWorkflowBlock, isWorkflowBranchLabel, isWorkflowFilterOperator, isWorkflowFilterPredicate, isWorkflowFilterPredicateKind, isWorkflowFilterValue, isWorkflowNodeKind, isWorkflowPredicateKind, isWorkflowRenameUnnamed,
27
+ // The rename rules, core's for the reason every rule here is core's: a form
28
+ // that checked a target name against its own copy of the identifier pattern
29
+ // would accept a name the server refuses, after Save — and `workflowKnownColumns`
30
+ // is what lets the inspector say which columns actually reach a node instead of
31
+ // guessing.
32
+ renameColumnRefusals, workflowKnownColumns, workflowRenameUnnamed,
27
33
  // The two wire formats a call node can be authored in, plus the reader that
28
34
  // applies the default. Core's, not a copy, for the reason every rule here is:
29
35
  // an inspector offering a mode the runner cannot build a payload for is a
30
36
  // graph somebody saves and a child run that fails, and a screen carrying its
31
37
  // own `?? 'envelope'` would eventually disagree with `workflowGraphHash` and
32
38
  // show unsaved changes on a graph nobody edited.
33
- WORKFLOW_CALL_MODES, unreachableCallMode, workflowCallMode, unreachableFilterOperator, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind,
39
+ WORKFLOW_CALL_MODES, unreachableCallMode, workflowCallMode, unreachableFilterOperator, unreachableFilterPredicateKind, unreachableNodeKind, unreachablePredicateKind, unreachableRenameUnnamed,
34
40
  // Core's, not a copy, for the reason every other rule here is core's: the
35
41
  // inspector has to offer exactly the acknowledgements `validateWorkflow`
36
42
  // requires, and a screen that worked out its own list would offer a set the
37
43
  // server then refuses — with the person having ticked a box to be told no.
38
- workflowNarrowedTypes, WORKFLOW_BRANCH_LABELS, WORKFLOW_FILTER_COLUMN_PATTERN, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_FILTER_PREDICATE_KINDS, WORKFLOW_PREDICATE_KINDS, WORKFLOW_NODE_ID_PATTERN, WORKFLOW_NODE_KINDS, } from '@dudousxd/nestjs-catalog/client';
44
+ workflowNarrowedTypes, WORKFLOW_BRANCH_LABELS, WORKFLOW_FILTER_COLUMN_PATTERN, WORKFLOW_FILTER_MAX_DEPTH, WORKFLOW_FILTER_MAX_VALUES, WORKFLOW_FILTER_OPERATORS, WORKFLOW_FILTER_PREDICATE_KINDS, WORKFLOW_PREDICATE_KINDS, WORKFLOW_RENAME_MAX_COLUMNS, WORKFLOW_RENAME_UNNAMED, WORKFLOW_NODE_ID_PATTERN, WORKFLOW_NODE_KINDS, } from '@dudousxd/nestjs-catalog/client';
39
45
  import { WORKFLOW_NODE_ID_PATTERN, } from '@dudousxd/nestjs-catalog/client';
40
46
  export function describeDurability(durability) {
41
47
  if (!durability) {
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Handle, Position } from '@xyflow/react';
3
- import { CircleAlert, CircleCheck, CircleSlash, Code2, Database, ExternalLink, Filter, GitBranch, Loader2, Plug, Repeat, TriangleAlert, } from 'lucide-react';
3
+ import { CircleAlert, CircleCheck, CircleSlash, Code2, Database, ExternalLink, Filter, GitBranch, Loader2, Plug, Repeat, TextCursorInput, TriangleAlert, } from 'lucide-react';
4
4
  import { motion, useReducedMotion } from 'motion/react';
5
5
  import { createContext, useContext, } from 'react';
6
6
  import { cn } from '../cn';
@@ -97,6 +97,19 @@ const KIND_STYLE = {
97
97
  icon: Filter,
98
98
  noun: 'filter',
99
99
  },
100
+ // Teal and a label-shaped mark. A rename is the one node that changes neither
101
+ // which rows exist nor which boxes run — it changes what the columns are
102
+ // *called* — so it deliberately shares nothing with the two subtraction
103
+ // colours beside it. It also has to be told apart from a transform at a
104
+ // glance, because the whole reason it is not one is that it is cheap and
105
+ // provable, and a canvas where the two read alike hides exactly that.
106
+ rename: {
107
+ accent: 'bg-gradient-to-b from-teal-400 to-teal-600',
108
+ chip: 'text-teal-700 dark:text-teal-300',
109
+ wash: 'bg-teal-50/70 dark:bg-teal-950/30',
110
+ icon: TextCursorInput,
111
+ noun: 'rename',
112
+ },
100
113
  };
101
114
  /**
102
115
  * Handles are styled larger than React Flow's default 6px dot.
@@ -87,6 +87,15 @@ const NODE_FACTORIES = {
87
87
  // impossible: the template would be shipping a graph that shrinks a published
88
88
  // type, with nobody having chosen it.
89
89
  filter: (id, name, init) => ({ id, name, kind: 'filter', ...init }),
90
+ // `rename` arrived fourth, and the map stopped the build a fourth time.
91
+ //
92
+ // Unused by every template below for the same reason `filter` is, one step
93
+ // sharper: a rename map is a list of one source system's own spellings of its
94
+ // own headers. `Mgmt Cd` is a fact about one Air Force fleet export and about
95
+ // nothing else, so a template that prefilled one would be renaming columns
96
+ // that do not exist in whatever the reader wired up — and the symptom of that
97
+ // is not an error, it is a target column absent from every row.
98
+ rename: (id, name, init) => ({ id, name, kind: 'rename', ...init }),
90
99
  };
91
100
  /* -------------------------------------------------------------------------- */
92
101
  /* Starter transform code */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudousxd/nestjs-catalog-react",
3
- "version": "0.26.0",
3
+ "version": "0.28.0",
4
4
  "description": "Ready-made React screens for @dudousxd/nestjs-catalog — a model manager and a generic object explorer you can drop into your own app shell.",
5
5
  "license": "MIT",
6
6
  "author": "Davide Carvalho",
@@ -110,7 +110,7 @@
110
110
  "tailwind-merge": "3.4.1",
111
111
  "tiptap-markdown": "0.9.0",
112
112
  "typescript": "5.9.3",
113
- "@dudousxd/nestjs-catalog": "0.22.0"
113
+ "@dudousxd/nestjs-catalog": "0.24.0"
114
114
  },
115
115
  "dependencies": {
116
116
  "clsx": "2.1.1",