@dudousxd/nestjs-catalog-react 0.9.0 → 0.11.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,11 +1,12 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
- import { ArrowUpRight, Eye, EyeOff, RotateCcw, Search } from 'lucide-react';
3
+ import { ArrowLeft, ArrowRight, ArrowUpRight, Eye, EyeOff, RotateCcw, Search, Unlink, } from 'lucide-react';
4
4
  import { useMemo, useState } from 'react';
5
5
  import { CoverageLedger } from './CoverageLedger';
6
6
  import { EditableField } from './EditableField';
7
7
  import { cn } from './cn';
8
8
  import { catalogQueryKeys, useCatalogClient } from './context';
9
+ import { freshnessOf, isWorthFlagging } from './freshness';
9
10
  import { DataTable } from './ui/data-table';
10
11
  import { RichTextField } from './ui/rich-text-field';
11
12
  import { Tooltip, TooltipProvider } from './ui/tooltip';
@@ -99,16 +100,86 @@ export function CatalogManager({ explorerHref, title = 'Catalog', eyebrow = 'Sem
99
100
  if (isError || !data) {
100
101
  return (_jsx("div", { className: "flex h-full items-center justify-center px-6", children: _jsxs("div", { className: "max-w-md text-center", children: [_jsx("h2", { className: "text-lg font-medium", children: "The catalog did not load" }), _jsx("p", { className: cn('mt-1 text-sm', SECONDARY), children: "The server builds it from ORM metadata at boot. Check that the API is reachable and that your account may read it." })] }) }));
101
102
  }
102
- return (_jsx(TooltipProvider, { children: _jsxs("div", { className: "flex h-full flex-col bg-zinc-50 dark:bg-zinc-950", children: [_jsxs("header", { className: cn('shrink-0 border-b px-8 py-6', RULE, PANEL), children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-6", children: [_jsxs("div", { children: [_jsx("p", { className: cn('font-mono text-[11px] uppercase tracking-[0.18em]', MUTED), children: eyebrow }), _jsx("h1", { className: "mt-1 text-2xl font-semibold tracking-tight", children: title }), _jsx("p", { className: cn('mt-1 max-w-xl text-sm', SECONDARY), children: intro })] }), _jsxs("div", { className: "flex items-center gap-6", children: [_jsx(Stat, { label: "Types", value: data.stats.types }), _jsx(Stat, { label: "Properties", value: data.stats.properties }), _jsx(Stat, { label: "Links", value: data.stats.relations }), _jsxs("button", { type: "button", onClick: () => resetMutation.mutate(), disabled: resetMutation.isPending, className: cn('flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs', RULE, SECONDARY, 'transition-colors hover:bg-zinc-50 disabled:opacity-50 dark:hover:bg-zinc-800'), children: [_jsx(RotateCcw, { size: 13 }), "Reset edits"] })] })] }), _jsx("div", { className: "mt-6", children: _jsx(CoverageLedger, { types: types, selected: selected?.name, onSelect: setSelectedName }) })] }), _jsxs("div", { className: "flex min-h-0 flex-1", children: [_jsxs("aside", { className: cn('flex w-72 shrink-0 flex-col border-r', RULE, PANEL), children: [_jsxs("div", { className: cn('shrink-0 space-y-2 border-b p-3', HAIRLINE), children: [_jsxs("div", { className: "relative", children: [_jsx(Search, { size: 14, className: cn('pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2', MUTED) }), _jsx("input", { type: "text", value: filter, onChange: (e) => setFilter(e.target.value), placeholder: "Find a type or table", "aria-label": "Filter object types", className: cn('w-full rounded-md border bg-zinc-50 py-1.5 pl-8 pr-2 text-sm outline-none dark:bg-zinc-950', RULE, 'placeholder:text-zinc-400 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/15') })] }), _jsxs("label", { className: cn('flex cursor-pointer items-center gap-2 px-0.5 text-xs', SECONDARY), children: [_jsx("input", { type: "checkbox", checked: onlyUnnamed, onChange: (e) => setOnlyUnnamed(e.target.checked), className: "accent-amber-500" }), "Only types nobody has named"] })] }), _jsxs("nav", { className: "min-h-0 flex-1 overflow-y-auto p-2", children: [grouped.length === 0 && (_jsxs("p", { className: cn('px-2 py-6 text-center text-xs', MUTED), children: ["Nothing matches \u201C", filter, "\u201D."] })), grouped.map(([group, groupTypes]) => (_jsxs("div", { className: "mb-3", children: [_jsxs("div", { className: "flex items-baseline justify-between px-2 py-1", children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: group }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: groupTypes.length })] }), groupTypes.map((type) => (_jsxs("button", { type: "button", onClick: () => setSelectedName(type.name), className: cn('group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors', selected?.name === type.name
103
+ return (_jsx(TooltipProvider, { children: _jsxs("div", { className: "flex h-full flex-col bg-zinc-50 dark:bg-zinc-950", children: [_jsxs("header", { className: cn('shrink-0 border-b px-8 py-6', RULE, PANEL), children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-6", children: [_jsxs("div", { children: [_jsx("p", { className: cn('font-mono text-[11px] uppercase tracking-[0.18em]', MUTED), children: eyebrow }), _jsx("h1", { className: "mt-1 text-2xl font-semibold tracking-tight", children: title }), _jsx("p", { className: cn('mt-1 max-w-xl text-sm', SECONDARY), children: intro })] }), _jsxs("div", { className: "flex items-center gap-6", children: [_jsx(Stat, { label: "Types", value: data.stats.types }), _jsx(Stat, { label: "Properties", value: data.stats.properties }), _jsx(Tooltip, { content: "Relations declared across every type. A link declared at both ends counts twice \u2014 the graph draws it once.", children: _jsx("span", { className: "cursor-help", children: _jsx(Stat, { label: "Relations", value: data.stats.relations }) }) }), _jsxs("button", { type: "button", onClick: () => resetMutation.mutate(), disabled: resetMutation.isPending, className: cn('flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs', RULE, SECONDARY, 'transition-colors hover:bg-zinc-50 disabled:opacity-50 dark:hover:bg-zinc-800'), children: [_jsx(RotateCcw, { size: 13 }), "Reset edits"] })] })] }), _jsx("div", { className: "mt-6", children: _jsx(CoverageLedger, { types: types, selected: selected?.name, onSelect: setSelectedName }) })] }), _jsxs("div", { className: "flex min-h-0 flex-1", children: [_jsxs("aside", { className: cn('flex w-72 shrink-0 flex-col border-r', RULE, PANEL), children: [_jsxs("div", { className: cn('shrink-0 space-y-2 border-b p-3', HAIRLINE), children: [_jsxs("div", { className: "relative", children: [_jsx(Search, { size: 14, className: cn('pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2', MUTED) }), _jsx("input", { type: "text", value: filter, onChange: (e) => setFilter(e.target.value), placeholder: "Find a type or table", "aria-label": "Filter object types", className: cn('w-full rounded-md border bg-zinc-50 py-1.5 pl-8 pr-2 text-sm outline-none dark:bg-zinc-950', RULE, 'placeholder:text-zinc-400 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/15') })] }), _jsxs("label", { className: cn('flex cursor-pointer items-center gap-2 px-0.5 text-xs', SECONDARY), children: [_jsx("input", { type: "checkbox", checked: onlyUnnamed, onChange: (e) => setOnlyUnnamed(e.target.checked), className: "accent-amber-500" }), "Only types nobody has named"] })] }), _jsxs("nav", { className: "min-h-0 flex-1 overflow-y-auto p-2", children: [grouped.length === 0 && (_jsxs("p", { className: cn('px-2 py-6 text-center text-xs', MUTED), children: ["Nothing matches \u201C", filter, "\u201D."] })), grouped.map(([group, groupTypes]) => (_jsxs("div", { className: "mb-3", children: [_jsxs("div", { className: "flex items-baseline justify-between px-2 py-1", children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: group }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: groupTypes.length })] }), groupTypes.map((type) => (_jsxs("button", { type: "button", onClick: () => setSelectedName(type.name), className: cn('group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors', selected?.name === type.name
103
104
  ? 'bg-sky-100 dark:bg-sky-950'
104
- : 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [_jsx("span", { "aria-hidden": true, className: cn('h-1.5 w-1.5 shrink-0 rounded-full', type.enriched ? 'bg-emerald-500' : 'bg-amber-400/60') }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsxs("span", { className: "block truncate text-sm", children: [type.icon ? `${type.icon} ` : '', type.displayName] }), _jsx("span", { className: cn('block truncate font-mono text-[10px]', MUTED), children: type.tableName })] })] }, type.name)))] }, group)))] })] }), _jsx("main", { className: "min-w-0 flex-1 overflow-y-auto", children: selected && (_jsx(TypeDetail, { type: selected, explorerHref: explorerHref, onPatchType: (patch) => typeMutation.mutate({ name: selected.name, patch }), onPatchProperty: (property, patch) => propertyMutation.mutate({ name: selected.name, property, patch }), onNavigate: setSelectedName }, selected.name)) })] })] }) }));
105
+ : 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [_jsx("span", { "aria-hidden": true, className: cn('h-1.5 w-1.5 shrink-0 rounded-full', type.enriched ? 'bg-emerald-500' : 'bg-amber-400/60') }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsxs("span", { className: "block truncate text-sm", children: [type.icon ? `${type.icon} ` : '', type.displayName] }), _jsxs("span", { className: cn('block truncate font-mono text-[10px]', MUTED), children: [type.tableName, _jsx(FreshnessNote, { type: type })] })] })] }, type.name)))] }, group)))] })] }), _jsx("main", { className: "min-w-0 flex-1 overflow-y-auto", children: selected && (_jsx(TypeDetail, { type: selected,
106
+ // The whole catalog, so the detail pane can answer what points
107
+ // AT this type. Nothing on a type records its inbound links —
108
+ // one row per declaration, and the declaration lives on the
109
+ // other end — so the only place that question can be answered
110
+ // is somewhere holding every type.
111
+ types: types, explorerHref: explorerHref, onPatchType: (patch) => typeMutation.mutate({ name: selected.name, patch }), onPatchProperty: (property, patch) => propertyMutation.mutate({ name: selected.name, property, patch }), onNavigate: setSelectedName }, selected.name)) })] })] }) }));
105
112
  }
106
113
  function Stat({ label, value }) {
107
114
  return (_jsxs("div", { className: "text-right", children: [_jsx("div", { className: "font-mono text-xl leading-none tabular-nums", children: value }), _jsx("div", { className: cn('mt-1 font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: label })] }));
108
115
  }
109
- function TypeDetail({ type, explorerHref, onPatchType, onPatchProperty, onNavigate, }) {
116
+ function TypeDetail({ type, types, explorerHref, onPatchType, onPatchProperty, onNavigate, }) {
110
117
  const visible = type.properties.filter((p) => !p.hidden).length;
111
- return (_jsxs("div", { className: "mx-auto max-w-5xl px-8 py-8", children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-4", children: [_jsxs("div", { className: "min-w-0", children: [_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "text-2xl leading-none", children: type.icon ?? '◈' }), _jsx(EditableField, { label: "display name", value: type.displayName, onSave: (displayName) => onPatchType({ displayName }), className: "text-2xl font-semibold tracking-tight", inputClassName: "text-2xl font-semibold tracking-tight" })] }), _jsxs("div", { className: cn('mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 pl-1 font-mono text-[11px]', MUTED), children: [_jsx("span", { children: type.name }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsx("span", { children: type.tableName }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsxs("span", { children: ["pk ", type.primaryKey.join(', ') || 'none'] }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsxs("span", { children: [visible, " of ", type.properties.length, " shown"] })] })] }), explorerHref && (_jsxs("a", { href: explorerHref(type.name), className: cn('flex items-center gap-1.5 rounded-md bg-zinc-950 px-3 py-2 text-xs text-zinc-50', 'transition-colors hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-950 dark:hover:bg-zinc-300'), children: ["Open ", type.pluralDisplayName, _jsx(ArrowUpRight, { size: 13 })] }))] }), _jsx("div", { className: "mt-5 border-l-2 border-sky-200 pl-4 dark:border-sky-900", children: _jsx(RichTextField, { label: "description", value: type.description ?? '', placeholder: "No one has written down what this type means yet.", onSave: (description) => onPatchType({ description }), className: cn('text-sm leading-relaxed', SECONDARY) }) }), _jsxs("div", { className: "mt-4 flex flex-wrap items-center gap-2", children: [_jsx(FieldChip, { label: "Group", value: type.group, onSave: (group) => onPatchType({ group }) }), _jsx(FieldChip, { label: "Plural", value: type.pluralDisplayName, onSave: (pluralDisplayName) => onPatchType({ pluralDisplayName }) }), _jsx(FieldChip, { label: "Icon", value: type.icon ?? '', onSave: (icon) => onPatchType({ icon }) })] }), _jsxs("section", { className: "mt-10", children: [_jsx(SectionHeading, { title: "Properties", note: "The column and its SQL type are read from the ORM. The label, description and unit are yours." }), _jsx("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: _jsx(PropertyTable, { properties: type.properties, onPatchProperty: onPatchProperty }) })] }), _jsxs("section", { className: "mt-10 pb-16", children: [_jsx(SectionHeading, { title: "Links", note: "Read from the foreign keys." }), type.relations.length === 0 ? (_jsxs("p", { className: cn('rounded-lg border border-dashed px-4 py-6 text-center text-sm', RULE, MUTED), children: ["Nothing links to or from ", type.displayName, " yet."] })) : (_jsx("div", { className: "flex flex-wrap gap-2", children: type.relations.map((relation) => (_jsxs("button", { type: "button", onClick: () => onNavigate(relation.targetType), className: cn('group flex items-center gap-2 rounded-md border px-3 py-2 text-left transition-colors', RULE, PANEL, 'hover:border-sky-500 hover:bg-sky-100 dark:hover:bg-sky-950'), children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-wider', MUTED), children: relation.kind }), _jsx("span", { className: "text-sm", children: relation.displayName }), _jsxs("span", { className: cn('font-mono text-[10px]', MUTED), children: ["\u2192 ", relation.targetType] })] }, relation.name))) }))] })] }));
118
+ return (_jsxs("div", { className: "mx-auto max-w-5xl px-8 py-8", children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-4", children: [_jsxs("div", { className: "min-w-0", children: [_jsxs("div", { className: "flex items-baseline gap-2", children: [_jsx("span", { className: "text-2xl leading-none", children: type.icon ?? '◈' }), _jsx(EditableField, { label: "display name", value: type.displayName, onSave: (displayName) => onPatchType({ displayName }), className: "text-2xl font-semibold tracking-tight", inputClassName: "text-2xl font-semibold tracking-tight" })] }), _jsxs("div", { className: cn('mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 pl-1 font-mono text-[11px]', MUTED), children: [_jsx("span", { children: type.name }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsx("span", { children: type.tableName }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsxs("span", { children: ["pk ", type.primaryKey.join(', ') || 'none'] }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsxs("span", { children: [visible, " of ", type.properties.length, " shown"] })] })] }), explorerHref && (_jsxs("a", { href: explorerHref(type.name), className: cn('flex items-center gap-1.5 rounded-md bg-zinc-950 px-3 py-2 text-xs text-zinc-50', 'transition-colors hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-950 dark:hover:bg-zinc-300'), children: ["Open ", type.pluralDisplayName, _jsx(ArrowUpRight, { size: 13 })] }))] }), _jsx("div", { className: "mt-5 border-l-2 border-sky-200 pl-4 dark:border-sky-900", children: _jsx(RichTextField, { label: "description", value: type.description ?? '', placeholder: "No one has written down what this type means yet.", onSave: (description) => onPatchType({ description }), className: cn('text-sm leading-relaxed', SECONDARY) }) }), _jsxs("div", { className: "mt-4 flex flex-wrap items-center gap-2", children: [_jsx(FieldChip, { label: "Group", value: type.group, onSave: (group) => onPatchType({ group }) }), _jsx(FieldChip, { label: "Plural", value: type.pluralDisplayName, onSave: (pluralDisplayName) => onPatchType({ pluralDisplayName }) }), _jsx(FieldChip, { label: "Icon", value: type.icon ?? '', onSave: (icon) => onPatchType({ icon }) })] }), _jsxs("section", { className: "mt-10", children: [_jsx(SectionHeading, { title: "Properties", note: "The column and its SQL type are read from the ORM. The label, description and unit are yours." }), _jsx("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: _jsx(PropertyTable, { properties: type.properties, onPatchProperty: onPatchProperty }) })] }), _jsx(LinkSection, { type: type, types: types, onPatchProperty: onPatchProperty, onNavigate: onNavigate })] }));
119
+ }
120
+ /** What each kind actually says, for people who do not read `m:n` fluently. */
121
+ const KIND_MEANING = {
122
+ 'm:1': 'Many of these point at one of those. The key is on this side.',
123
+ '1:m': 'One of these has many of those. The key is on the other side.',
124
+ '1:1': 'One of each, paired.',
125
+ 'm:n': 'Many on both sides, joined through a table of pairs.',
126
+ };
127
+ /**
128
+ * A link this type declares, together with the one that points back at it.
129
+ *
130
+ * A type carries one row per link it DECLARES, which is the honest shape — the
131
+ * declaration belongs to whoever wrote it, and inventing a mirror row on the
132
+ * other type would double every count and hand a curator a label no publisher
133
+ * owns. But it makes half the truth invisible: `@ManyToOne(() => Base)` on `Mvr`
134
+ * leaves `Base` with an empty relations list, and this screen said, in as many
135
+ * words, that nothing linked to or from it. Base is one of the most linked-to
136
+ * types in the schema.
137
+ *
138
+ * So the inbound half is derived here, from the catalog the screen already has,
139
+ * and derived is exactly what it stays: nothing about it is stored, counted or
140
+ * editable from this end.
141
+ */
142
+ function inboundLinks(type, types) {
143
+ // The other ends this type already declares. `Base.mvrs` names `Mvr.base`
144
+ // through `inverseName`, and the two are one link — listing the second as an
145
+ // inbound arrival would show a single foreign key as two separate links.
146
+ const alreadyMine = new Set(type.relations.flatMap((relation) => relation.inverseName ? [`${relation.targetType}.${relation.inverseName}`] : []));
147
+ const inbound = [];
148
+ for (const from of types) {
149
+ // A type that points at itself is already listed once, above. Showing it
150
+ // again under "points here" says there are two links where there is one.
151
+ if (from.name === type.name)
152
+ continue;
153
+ for (const relation of from.relations) {
154
+ if (relation.targetType !== type.name)
155
+ continue;
156
+ if (alreadyMine.has(`${from.name}.${relation.name}`))
157
+ continue;
158
+ inbound.push({ from, relation });
159
+ }
160
+ }
161
+ return inbound;
162
+ }
163
+ function LinkSection({ type, types, onPatchProperty, onNavigate, }) {
164
+ const inbound = useMemo(() => inboundLinks(type, types), [type, types]);
165
+ const labelFor = useMemo(() => new Map(types.map((t) => [t.name, t.displayName])), [types]);
166
+ return (_jsxs("section", { className: "mt-10 pb-16", children: [_jsx(SectionHeading, { title: "Links", note: "Read from the foreign keys. What a link is called is yours to change; where it points is not." }), type.relations.length === 0 && inbound.length === 0 ? (_jsxs("p", { className: cn('rounded-lg border border-dashed px-4 py-6 text-center text-sm', RULE, MUTED), children: ["Nothing links to or from ", type.displayName, " yet."] })) : (_jsxs("div", { className: "space-y-5", children: [type.relations.length > 0 && (_jsxs("div", { children: [_jsxs("p", { className: cn('mb-2 font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: [type.displayName, " points at"] }), _jsx("ul", { className: "space-y-1.5", children: type.relations.map((relation) => (_jsx(OutboundLink, { relation: relation, targetLabel: labelFor.get(relation.targetType), onPatchProperty: onPatchProperty, onNavigate: onNavigate }, relation.name))) })] })), inbound.length > 0 && (_jsxs("div", { children: [_jsxs("p", { className: cn('mb-2 font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: ["Points at ", type.displayName] }), _jsx("ul", { className: "space-y-1.5", children: inbound.map(({ from, relation }) => (_jsx("li", { children: _jsxs("button", { type: "button", onClick: () => onNavigate(from.name), className: cn('flex w-full items-center gap-2 rounded-md border px-3 py-2 text-left transition-colors', RULE, PANEL, 'hover:border-sky-500 hover:bg-sky-100 dark:hover:bg-sky-950'), children: [_jsx(ArrowLeft, { size: 13, className: MUTED }), _jsx("span", { className: "text-sm", children: from.displayName }), _jsxs("span", { className: cn('font-mono text-[10px]', MUTED), children: [relation.kind, " \u00B7 ", from.name, ".", relation.name] })] }) }, `${from.name}.${relation.name}`))) }), _jsx("p", { className: cn('mt-1.5 text-[11px]', MUTED), children: "Declared on the other type. Open it to rename the link." })] }))] }))] }));
167
+ }
168
+ /**
169
+ * One link this type declares.
170
+ *
171
+ * Not a single button any more, and that is the point: the label is editable and
172
+ * the target is navigable, so a control that was both meant the only way to
173
+ * rename a link was to first go somewhere else. A nested interactive element is
174
+ * also the one thing a screen reader cannot describe.
175
+ */
176
+ function OutboundLink({ relation, targetLabel, onPatchProperty, onNavigate, }) {
177
+ return (_jsxs("li", { className: cn('flex items-center gap-2 rounded-md border px-3 py-2', RULE, PANEL, relation.hidden && 'opacity-45'), children: [_jsx(Tooltip, { content: KIND_MEANING[relation.kind], children: _jsx("span", { className: cn('cursor-help font-mono text-[10px] uppercase tracking-wider', MUTED), children: relation.kind }) }), _jsx("span", { className: "min-w-0 flex-1", children: _jsx(EditableField, { label: `label for ${relation.name}`, value: relation.displayName, onSave: (displayName) => onPatchProperty(relation.name, { displayName }), className: "text-sm", inputClassName: "text-sm" }) }), _jsxs("span", { className: cn('shrink-0 font-mono text-[10px]', MUTED), children: [relation.name, relation.localKey ? ` · ${relation.localKey}` : ''] }), _jsx("span", { className: "shrink-0", children: relation.targetPublished ? (_jsxs("button", { type: "button", onClick: () => onNavigate(relation.targetType), className: cn('flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs transition-colors', SECONDARY, 'hover:bg-sky-100 dark:hover:bg-sky-950'), children: [_jsx(ArrowRight, { size: 13 }), targetLabel ?? relation.targetType] })) : (
178
+ // Kept, and marked. Dropping it would leave the type looking less
179
+ // connected than it is; making it navigable would send the reader to
180
+ // a type that is not there — the button used to do exactly that, and
181
+ // silently selected whichever type happened to be first.
182
+ _jsx(Tooltip, { content: `This catalog holds nothing called ${relation.targetType}. The link is real in the source schema; the type on the other end has been excluded, or nobody has published it here.`, children: _jsxs("span", { className: cn('flex cursor-help items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs', 'text-amber-700 dark:text-amber-400'), children: [_jsx(Unlink, { size: 13 }), relation.targetType] }) })) })] }));
112
183
  }
113
184
  function SectionHeading({ title, note }) {
114
185
  return (_jsxs("div", { className: "mb-3", children: [_jsx("h2", { className: cn('font-mono text-[11px] uppercase tracking-[0.16em]', MUTED), children: title }), _jsx("p", { className: cn('mt-1 text-xs', MUTED), children: note })] }));
@@ -198,3 +269,31 @@ function VisibilityToggle({ property, onPatchProperty, }) {
198
269
  ? `Hidden from tables and search. ${property.displayName} is still stored — showing it again needs no migration.`
199
270
  : 'Shown in tables and search. Hiding it only changes what is displayed; the column is untouched.', children: _jsx("button", { type: "button", "aria-label": `${property.hidden ? 'Show' : 'Hide'} ${property.displayName}`, onClick: () => onPatchProperty(property.name, { hidden: !property.hidden }), className: cn('rounded-sm p-1 hover:bg-zinc-100 dark:hover:bg-zinc-800', MUTED), children: property.hidden ? _jsx(EyeOff, { size: 14 }) : _jsx(Eye, { size: 14 }) }) }));
200
271
  }
272
+ /**
273
+ * The age of a type's data, beside its table name.
274
+ *
275
+ * Here rather than behind a hover or a detail pane, because the whole failure
276
+ * this addresses is that nobody thinks to look: a type whose publisher was
277
+ * deleted in January renders identically to one loaded ten minutes ago, and
278
+ * somebody reads a number off it in June.
279
+ *
280
+ * A tooltip carries the row count and the publisher — the two questions that
281
+ * follow "this is old" — without spending width on them for the types where
282
+ * nobody is asking.
283
+ */
284
+ function FreshnessNote({ type }) {
285
+ const freshness = freshnessOf(type);
286
+ const flag = isWorthFlagging(freshness);
287
+ return (_jsx("span", { className: cn('ml-2', flag && 'text-amber-600 dark:text-amber-400'), title: titleFor(type, freshness), children: freshness.kind === 'never' ? '· never loaded' : `· ${freshness.label}` }));
288
+ }
289
+ function titleFor(type, freshness) {
290
+ if (freshness.kind === 'never') {
291
+ // Said plainly, because this is the state most often mistaken for a
292
+ // problem: a type can be published by a schema and legitimately never
293
+ // loaded, and that is not the same as a load that failed.
294
+ return 'This type has a schema but no committed snapshot — nothing has ever been loaded into it.';
295
+ }
296
+ const rows = type.rowCount === undefined ? 'unknown rows' : `${type.rowCount} rows`;
297
+ const who = type.lastPrincipalId ? ` by ${type.lastPrincipalId}` : '';
298
+ return `Serving ${rows}, committed ${freshness.label}${who}.`;
299
+ }
package/dist/FlowView.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useQuery } from '@tanstack/react-query';
3
- import { ArrowRight, CircleAlert, CircleCheck, CircleDot } from 'lucide-react';
3
+ import { ArrowRight, CircleAlert, CircleCheck, CircleDot, Link2 } from 'lucide-react';
4
4
  import { useMemo } from 'react';
5
5
  import { cn } from './cn';
6
6
  import { catalogQueryKeys, useCatalogClient } from './context';
@@ -42,7 +42,7 @@ export function FlowView() {
42
42
  * exactly that.
43
43
  */
44
44
  /** An empty lane for one (publisher, type) pair, named from the type when it is known. */
45
- function newLane(principalId, typeName, def) {
45
+ function newLane(principalId, typeName, def, byType) {
46
46
  return {
47
47
  principalId,
48
48
  typeName,
@@ -50,8 +50,47 @@ function newLane(principalId, typeName, def) {
50
50
  icon: def?.icon,
51
51
  loads: [],
52
52
  schemaChanges: 0,
53
+ dependsOn: crossPublisherLinks(principalId, def, byType),
53
54
  };
54
55
  }
56
+ /**
57
+ * The links out of a type that land outside this publisher's own set.
58
+ *
59
+ * "Whose type is it" is answered by who last committed to it, which is the same
60
+ * evidence the rest of this screen runs on — a declared owner would be a claim,
61
+ * and a lane built from claims is the diagram this screen exists not to be. A
62
+ * type nobody has committed to yet has no publisher, and that is reported as its
63
+ * own state rather than folded into "someone else's": nothing has ever loaded it
64
+ * is a worse answer than somebody else loads it, and they want different fixes.
65
+ *
66
+ * Unpublished targets (`targetPublished === false`) are the sharpest case and
67
+ * are included first: the catalog does not hold the type at all, so the join has
68
+ * nowhere to land no matter who runs.
69
+ */
70
+ function crossPublisherLinks(principalId, def, byType) {
71
+ if (!def)
72
+ return [];
73
+ const seen = new Set();
74
+ const dependsOn = [];
75
+ for (const relation of def.relations) {
76
+ const target = byType.get(relation.targetType);
77
+ const publisher = target?.lastPrincipalId;
78
+ // The links this publisher can fix on its own are not this screen's news.
79
+ if (relation.targetPublished && publisher === principalId)
80
+ continue;
81
+ // One entry per target, not per link: two foreign keys into the same type
82
+ // are one dependency, and listing both says nothing the first did not.
83
+ if (seen.has(relation.targetType))
84
+ continue;
85
+ seen.add(relation.targetType);
86
+ dependsOn.push({
87
+ typeName: relation.targetType,
88
+ displayName: target?.displayName ?? relation.targetType,
89
+ ...(publisher === undefined ? {} : { publisher }),
90
+ });
91
+ }
92
+ return dependsOn;
93
+ }
55
94
  /**
56
95
  * Fold one snapshot event into a lane's loads.
57
96
  *
@@ -84,7 +123,7 @@ function buildLanes(types, events) {
84
123
  continue;
85
124
  const principalId = event.principalId ?? 'curated by hand';
86
125
  const key = `${principalId}:${event.typeName}`;
87
- const lane = lanes.get(key) ?? newLane(principalId, event.typeName, byType.get(event.typeName));
126
+ const lane = lanes.get(key) ?? newLane(principalId, event.typeName, byType.get(event.typeName), byType);
88
127
  if (event.event === 'schema.changed')
89
128
  lane.schemaChanges += 1;
90
129
  recordSnapshot(lane, event);
@@ -98,5 +137,9 @@ function Lane({ lane }) {
98
137
  const uncommitted = lane.loads.length - committed;
99
138
  return (_jsxs("div", { className: cn('rounded-lg border p-4', RULE, PANEL), children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("span", { className: "rounded-md bg-zinc-100 px-2 py-1 font-mono text-[11px] dark:bg-zinc-800", children: lane.principalId }), _jsx(ArrowRight, { size: 14, className: MUTED }), _jsxs("span", { className: "text-sm", children: [lane.icon ? `${lane.icon} ` : '', lane.displayName] }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: lane.typeName }), _jsx("span", { className: cn('ml-auto font-mono text-[10px]', MUTED), children: lane.lastAt ? new Date(lane.lastAt).toLocaleString() : '' })] }), _jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-1.5", children: [lane.loads.length === 0 && (_jsx("span", { className: cn('text-[11px]', MUTED), children: "No loads recorded." })), [...lane.loads].reverse().map((load) => (_jsx(Tooltip, { content: _jsxs("span", { className: "font-mono text-[11px]", children: [load.snapshotId, _jsx("br", {}), load.rows, " rows \u00B7 ", load.committed ? 'committed' : 'written, never committed', _jsx("br", {}), new Date(load.at).toLocaleString()] }), children: _jsxs("span", { className: cn('flex cursor-help items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px]', load.committed
100
139
  ? 'border-emerald-200 text-emerald-700 dark:border-emerald-900 dark:text-emerald-300'
101
- : 'border-amber-200 text-amber-700 dark:border-amber-900 dark:text-amber-300'), children: [load.committed ? _jsx(CircleCheck, { size: 10 }) : _jsx(CircleDot, { size: 10 }), load.rows] }) }, load.snapshotId)))] }), _jsxs("div", { className: cn('mt-2 flex flex-wrap gap-3 font-mono text-[10px]', MUTED), children: [_jsxs("span", { children: [committed, " committed"] }), uncommitted > 0 && (_jsx(Tooltip, { content: "Written but never committed. Nobody is reading these \u2014 a publisher that stopped halfway leaves exactly this.", children: _jsxs("span", { className: "cursor-help text-amber-600", children: [uncommitted, " left uncommitted"] }) })), lane.schemaChanges > 0 && (_jsx(Tooltip, { content: "Columns were added. This catalog never drops or retypes one automatically.", children: _jsxs("span", { className: "flex cursor-help items-center gap-1", children: [_jsx(CircleAlert, { size: 10 }), lane.schemaChanges, " schema change", lane.schemaChanges === 1 ? '' : 's'] }) }))] })] }));
140
+ : 'border-amber-200 text-amber-700 dark:border-amber-900 dark:text-amber-300'), children: [load.committed ? _jsx(CircleCheck, { size: 10 }) : _jsx(CircleDot, { size: 10 }), load.rows] }) }, load.snapshotId)))] }), _jsxs("div", { className: cn('mt-2 flex flex-wrap gap-3 font-mono text-[10px]', MUTED), children: [_jsxs("span", { children: [committed, " committed"] }), uncommitted > 0 && (_jsx(Tooltip, { content: "Written but never committed. Nobody is reading these \u2014 a publisher that stopped halfway leaves exactly this.", children: _jsxs("span", { className: "cursor-help text-amber-600", children: [uncommitted, " left uncommitted"] }) })), lane.schemaChanges > 0 && (_jsx(Tooltip, { content: "Columns were added. This catalog never drops or retypes one automatically.", children: _jsxs("span", { className: "flex cursor-help items-center gap-1", children: [_jsx(CircleAlert, { size: 10 }), lane.schemaChanges, " schema change", lane.schemaChanges === 1 ? '' : 's'] }) }))] }), lane.dependsOn.length > 0 && (_jsxs("div", { className: cn('mt-2 flex flex-wrap items-center gap-1.5 font-mono text-[10px]', MUTED), children: [_jsx(Link2, { size: 10 }), _jsx("span", { children: "needs" }), lane.dependsOn.map((dependency) => (_jsx(Tooltip, { content: dependency.publisher
141
+ ? `${lane.displayName} links to ${dependency.displayName}, which ${dependency.publisher} loads. Rows here can arrive before the ones they point at, and the join comes back empty rather than failing.`
142
+ : `${lane.displayName} links to ${dependency.typeName}, and nothing has ever committed to it. Every one of those joins resolves to nothing.`, children: _jsxs("span", { className: cn('cursor-help rounded-sm border px-1.5 py-0.5', dependency.publisher
143
+ ? 'border-zinc-200 dark:border-zinc-800'
144
+ : 'border-amber-200 text-amber-700 dark:border-amber-900 dark:text-amber-300'), children: [dependency.displayName, dependency.publisher ? ` · ${dependency.publisher}` : ' · nobody'] }) }, dependency.typeName)))] }))] }));
102
145
  }
@@ -1,3 +1,4 @@
1
+ import type { ScalarType } from '@dudousxd/nestjs-catalog/client';
1
2
  export interface PipelineConsoleProps {
2
3
  /** Heading copy, so the host can call this whatever its users call it. */
3
4
  title?: string;
@@ -8,6 +9,93 @@ export interface PipelineConsoleProps {
8
9
  * regardless; this only stops the console offering buttons that always 403.
9
10
  */
10
11
  canEdit?: boolean;
12
+ /**
13
+ * Asking a connector what its source looks like, and creating the type from
14
+ * the answer.
15
+ *
16
+ * A prop rather than two more methods on `CatalogClient`, and that is not a
17
+ * design preference — it is the honest report of a boundary. `CatalogClient`
18
+ * carries no `discoverConnectorSchema` and no publish call of any kind, and
19
+ * both live in `context.tsx`, so a console that reached for them would be
20
+ * naming methods that do not exist. Wiring is one function each:
21
+ *
22
+ * discover: POST <pipelineBasePath>/connectors/:id/discover
23
+ * createType: PUT <publishBasePath>/publish/:name/schema
24
+ *
25
+ * Omit it and the connector editor simply does not offer discovery, which is
26
+ * the correct state for a host that has not mounted those routes. Supply
27
+ * `discover` without `createType` and the panel does everything up to the
28
+ * confirmation and then shows the exact request it would have sent — the
29
+ * publish route requires `catalog:write` and per-type ownership, and a host
30
+ * that has deliberately not given its console that has to be able to say so
31
+ * without the screen pretending the button is merely broken.
32
+ */
33
+ schemaDiscovery?: SchemaDiscoveryBridge;
34
+ }
35
+ export interface SchemaDiscoveryBridge {
36
+ discover(connectorId: string): Promise<ConnectorSchemaDiscovery>;
37
+ /**
38
+ * Create the type from what a person confirmed. Absent is a supported state —
39
+ * see {@link PipelineConsoleProps.schemaDiscovery}.
40
+ */
41
+ createType?(draft: DiscoveredTypeDraft): Promise<unknown>;
42
+ }
43
+ /**
44
+ * What `POST pipeline/connectors/:id/discover` answers, mirrored for the browser.
45
+ *
46
+ * Mirrored rather than imported, exactly as `PipelineCapabilities` is in
47
+ * `context.tsx`: the authority is `schema-discovery.ts` in
48
+ * `@dudousxd/nestjs-catalog-pipeline`, which is a NestJS package with a
49
+ * `node:fs` import in its dependency graph and has no business in a browser
50
+ * bundle. The two are kept honest by being the documented response of one route,
51
+ * and by this screen treating every field it renders as something the server may
52
+ * not have sent.
53
+ */
54
+ export interface DiscoveredColumn {
55
+ /**
56
+ * The column as the source spells it, which is also the property name. The
57
+ * server explains at length why it is not tidied: the store matches records to
58
+ * properties by property NAME, so a renamed property is a column that loads
59
+ * null on every run and reports success.
60
+ */
61
+ name: string;
62
+ /** `null` means discovery reached no conclusion — which is not a type. */
63
+ type: ScalarType | null;
64
+ confidence: 'reported' | 'inferred' | 'unknown';
65
+ sourceType: string;
66
+ /** `null` where the source did not say. Postgres never does. */
67
+ nullable: boolean | null;
68
+ note?: string;
69
+ }
70
+ export interface SchemaDrift {
71
+ added: string[];
72
+ removed: string[];
73
+ retyped: Array<{
74
+ property: string;
75
+ was: ScalarType;
76
+ now: ScalarType;
77
+ }>;
78
+ }
79
+ export interface ConnectorSchemaDiscovery {
80
+ connectorId: string;
81
+ connectorName: string;
82
+ targetType: string;
83
+ typeExists: boolean;
84
+ basis: 'driver' | 'sample';
85
+ sampled: number;
86
+ caveat: string;
87
+ columns: DiscoveredColumn[];
88
+ drift: SchemaDrift | null;
89
+ }
90
+ /** The subset of a published type this screen is able to state. */
91
+ export interface DiscoveredTypeDraft {
92
+ name: string;
93
+ properties: Array<{
94
+ name: string;
95
+ columnName: string;
96
+ type: ScalarType;
97
+ nullable: boolean;
98
+ }>;
11
99
  }
12
100
  /**
13
101
  * Where data comes from, and the code that shapes it.
@@ -17,4 +105,39 @@ export interface PipelineConsoleProps {
17
105
  * without its transform is a URL, and a transform without the connector it
18
106
  * feeds is code nobody can place.
19
107
  */
20
- export declare function PipelineConsole({ title, eyebrow, intro, canEdit, }: PipelineConsoleProps): import("react/jsx-runtime").JSX.Element;
108
+ export declare function PipelineConsole({ title, eyebrow, intro, canEdit, schemaDiscovery, }: PipelineConsoleProps): import("react/jsx-runtime").JSX.Element;
109
+ /** What a person decided about one discovered column. */
110
+ export interface ColumnChoice {
111
+ include: boolean;
112
+ /** Empty means nothing has been chosen yet — see {@link initialChoices}. */
113
+ type: ScalarType | '';
114
+ }
115
+ /**
116
+ * Where the checkboxes start, and why the untyped ones start off.
117
+ *
118
+ * A column discovery could type is proposed; a column it could not is present,
119
+ * visible, and **excluded** until somebody says what it is. Pre-selecting it
120
+ * with a plausible default is the failure that matters — a wrong type becomes a
121
+ * wrong column in a lake nobody re-checks, and everything downstream reads it
122
+ * as fact rather than as the guess it was.
123
+ *
124
+ * Keyed by position rather than by name on purpose: `SELECT a.id, b.id` gives
125
+ * two columns called `id`, and a map would silently merge their choices.
126
+ */
127
+ export declare function initialChoices(columns: DiscoveredColumn[]): ColumnChoice[];
128
+ /**
129
+ * The type this would create, and everything standing in the way of creating it.
130
+ *
131
+ * Pure, and separate from the panel, because these are the rules that decide
132
+ * whether a schema somebody approved is one the publish route will accept — and
133
+ * rules that live inside a component are rules only a rendered DOM can check.
134
+ *
135
+ * `columnName` is sent as well as `name`, and they are the same string. The
136
+ * publish service maps `columnName` to `sourceColumn` and `name` to the property
137
+ * itself, and the store reads records by property name; sending them equal is
138
+ * what makes a load match. See the server's `DiscoveredColumn.name`.
139
+ */
140
+ export declare function proposalFrom(discovery: ConnectorSchemaDiscovery, choices: ColumnChoice[]): {
141
+ draft: DiscoveredTypeDraft;
142
+ problems: string[];
143
+ };
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
- import { Cable, CircleCheck, CircleX, Code2, KeyRound, Loader2, Play, Plug, Plus, RefreshCw, Trash2, } from 'lucide-react';
4
- import { useState } from 'react';
3
+ import { Cable, CircleCheck, CircleX, Code2, KeyRound, Loader2, Play, Plug, Plus, RefreshCw, ScanSearch, Trash2, TriangleAlert, } from 'lucide-react';
4
+ import { useMemo, useState } from 'react';
5
5
  import { ConnectionPanel, connectionOptionsFor } from './ConnectionPanel';
6
6
  import { TransformEditor } from './TransformEditor';
7
7
  import { cn } from './cn';
@@ -18,6 +18,28 @@ import { Tooltip, TooltipProvider } from './ui/tooltip';
18
18
  const MUTED = 'text-zinc-400 dark:text-zinc-500';
19
19
  const RULE = 'border-zinc-200 dark:border-zinc-800';
20
20
  const PANEL = 'bg-white dark:bg-zinc-900';
21
+ /**
22
+ * The discovery response, checked rather than assumed.
23
+ *
24
+ * The client returns `unknown` because this package must not import
25
+ * `@dudousxd/nestjs-catalog-pipeline` — it would drag database drivers behind
26
+ * optional imports into a browser bundle — so the shape above is a mirror of a
27
+ * contract held somewhere else. A mirror can fall behind: a console talking to
28
+ * an older server gets a body with no `columns`, and rendering it would throw
29
+ * somewhere deep in the table with a message about `undefined.map`.
30
+ *
31
+ * Checked at the seam, once, so the failure names itself. Only the fields this
32
+ * screen would crash without — validating every column here would be
33
+ * re-implementing the server's own shape in a place that cannot be kept honest.
34
+ */
35
+ function narrowDiscovery(answer) {
36
+ if (!answer || typeof answer !== 'object' || !Array.isArray(Reflect.get(answer, 'columns'))) {
37
+ throw new Error('The server answered the discovery request with something this console does not recognise. ' +
38
+ 'It is most likely running a version of @dudousxd/nestjs-catalog-pipeline older than this ' +
39
+ 'console expects.');
40
+ }
41
+ return Object.assign(Object.create(null), answer);
42
+ }
21
43
  /**
22
44
  * Where data comes from, and the code that shapes it.
23
45
  *
@@ -26,9 +48,37 @@ const PANEL = 'bg-white dark:bg-zinc-900';
26
48
  * without its transform is a URL, and a transform without the connector it
27
49
  * feeds is code nobody can place.
28
50
  */
29
- export function PipelineConsole({ title = 'Connectors', eyebrow = 'Ingestion', intro = 'A source, code that reshapes it, and a snapshot at the end. Running one goes through exactly the same append-and-commit a publisher uses, so there is one way rows arrive rather than two.', canEdit = true, }) {
51
+ export function PipelineConsole({ title = 'Connectors', eyebrow = 'Ingestion', intro = 'A source, code that reshapes it, and a snapshot at the end. Running one goes through exactly the same append-and-commit a publisher uses, so there is one way rows arrive rather than two.', canEdit = true, schemaDiscovery, }) {
30
52
  const client = useCatalogClient();
31
53
  const [tab, setTab] = useState('connectors');
54
+ /**
55
+ * The bridge, from the client, unless the host supplied its own.
56
+ *
57
+ * Until this existed the panel took `schemaDiscovery` as a prop and nothing
58
+ * supplied one, so the feature was reachable only by a host that had read the
59
+ * source and written the two calls itself. The prop stays — a host embedding
60
+ * this screen may route discovery through its own gateway — but it is an
61
+ * override now rather than the only way in.
62
+ */
63
+ const bridge = useMemo(() => ({
64
+ discover: async (connectorId) => narrowDiscovery(await client.discoverConnectorSchema(connectorId)),
65
+ // `async` on purpose: `publishType` THROWS rather than rejecting when the
66
+ // transport cannot PUT, and a bridge whose method throws synchronously
67
+ // would escape the panel's error handling and take the screen with it.
68
+ createType: async (draft) => client.publishType(draft.name, {
69
+ // Only what a person confirmed on screen. Everything else about a type
70
+ // — its label, its description, its units — is curation, and inventing
71
+ // any of it here would put words nobody chose into a catalog whose
72
+ // whole claim is that its names were chosen.
73
+ properties: draft.properties.map((property) => ({
74
+ name: property.name,
75
+ columnName: property.columnName,
76
+ type: property.type,
77
+ nullable: property.nullable,
78
+ })),
79
+ }),
80
+ }), [client]);
81
+ const discovery = schemaDiscovery ?? bridge;
32
82
  const { data: capabilities } = useQuery({
33
83
  queryKey: catalogQueryKeys.capabilities,
34
84
  queryFn: () => client.pipelineCapabilities(),
@@ -39,9 +89,9 @@ export function PipelineConsole({ title = 'Connectors', eyebrow = 'Ingestion', i
39
89
  });
40
90
  return (_jsx(TooltipProvider, { children: _jsx("div", { className: "h-full overflow-y-auto", children: _jsxs("div", { className: "mx-auto max-w-5xl px-8 py-8", children: [_jsx("p", { className: cn('font-mono text-[11px] uppercase tracking-[0.18em]', MUTED), children: eyebrow }), _jsx("h1", { className: "mt-1 text-2xl font-semibold tracking-tight", children: title }), _jsx("p", { className: "mt-1 max-w-2xl text-sm text-zinc-500 dark:text-zinc-400", children: intro }), _jsxs(Tabs, { value: tab, onValueChange: setTab, className: "mt-6", children: [_jsxs(TabsList, { children: [_jsxs(TabsTab, { value: "connections", children: [_jsx(Plug, { size: 13 }), "Connections"] }), _jsxs(TabsTab, { value: "connectors", children: [_jsx(Cable, { size: 13 }), "Connectors"] }), _jsxs(TabsTab, { value: "transforms", children: [_jsx(Code2, { size: 13 }), "Transforms"] }), _jsx(Tooltip, { content: capabilities?.pythonPackages?.length
41
91
  ? `Python transforms may import ${capabilities.pythonPackages.join(', ')} — provisioned by the image, not by this service.`
42
- : 'Which languages this deployment can actually execute.', children: _jsx("span", { className: cn('ml-auto cursor-help self-center font-mono text-[10px]', MUTED), children: capabilities ? `runs ${capabilities.languages.join(' · ')}` : 'checking…' }) })] }), _jsx(TabsPanel, { value: "connections", children: _jsx(ConnectionPanel, { canEdit: canEdit }) }), _jsx(TabsPanel, { value: "connectors", children: _jsx(ConnectorList, { canEdit: canEdit }) }), _jsx(TabsPanel, { value: "transforms", children: _jsx(TransformList, { canEdit: canEdit, languages: capabilities?.languages ?? ['javascript'], pythonPackages: capabilities?.pythonPackages ?? [] }) })] })] }) }) }));
92
+ : 'Which languages this deployment can actually execute.', children: _jsx("span", { className: cn('ml-auto cursor-help self-center font-mono text-[10px]', MUTED), children: capabilities ? `runs ${capabilities.languages.join(' · ')}` : 'checking…' }) })] }), _jsx(TabsPanel, { value: "connections", children: _jsx(ConnectionPanel, { canEdit: canEdit }) }), _jsx(TabsPanel, { value: "connectors", children: _jsx(ConnectorList, { canEdit: canEdit, schemaDiscovery: discovery }) }), _jsx(TabsPanel, { value: "transforms", children: _jsx(TransformList, { canEdit: canEdit, languages: capabilities?.languages ?? ['javascript'], pythonPackages: capabilities?.pythonPackages ?? [] }) })] })] }) }) }));
43
93
  }
44
- function ConnectorList({ canEdit }) {
94
+ function ConnectorList({ canEdit, schemaDiscovery, }) {
45
95
  const client = useCatalogClient();
46
96
  const queryClient = useQueryClient();
47
97
  const [editing, setEditing] = useState(null);
@@ -76,7 +126,7 @@ function ConnectorList({ canEdit }) {
76
126
  onSuccess: invalidateRun,
77
127
  });
78
128
  if (editing) {
79
- return (_jsx(ConnectorForm, { connector: editing === 'new' ? undefined : editing, transforms: transforms, connections: connections, onClose: () => setEditing(null), onSaved: () => {
129
+ return (_jsx(ConnectorForm, { connector: editing === 'new' ? undefined : editing, transforms: transforms, connections: connections, schemaDiscovery: schemaDiscovery, onClose: () => setEditing(null), onSaved: () => {
80
130
  setEditing(null);
81
131
  queryClient.invalidateQueries({ queryKey: catalogQueryKeys.connectors });
82
132
  } }));
@@ -190,7 +240,188 @@ function connectionPickerHint(optionCount, viaConnection) {
190
240
  function ConnectorFormActions({ editing, pending, incomplete, error, onClose, }) {
191
241
  return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "submit", disabled: pending || incomplete, className: "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: pending ? 'Saving…' : editing ? 'Save changes' : 'Save connector' }), _jsx("button", { type: "button", onClick: onClose, className: cn('rounded-md px-3 py-1.5 text-xs', MUTED), children: "Cancel" })] }), error ? (_jsx("p", { className: "text-[11px] text-red-600", children: error instanceof Error ? error.message : 'Could not save.' })) : null] }));
192
242
  }
193
- function ConnectorForm({ connector, transforms, connections, onClose, onSaved, }) {
243
+ /**
244
+ * Every type the catalog can hold, in the order a person scans for one.
245
+ *
246
+ * `unknown` is last and named plainly, because choosing it is a decision: the
247
+ * store gives it a TEXT column and stringifies whatever arrives. It is the right
248
+ * answer for a column nobody can classify and the wrong answer for one nobody
249
+ * looked at, which is exactly why discovery never picks it on anyone's behalf.
250
+ */
251
+ const SCALAR_TYPES = [
252
+ 'string',
253
+ 'number',
254
+ 'boolean',
255
+ 'date',
256
+ 'uuid',
257
+ 'json',
258
+ 'unknown',
259
+ ];
260
+ /**
261
+ * Where the checkboxes start, and why the untyped ones start off.
262
+ *
263
+ * A column discovery could type is proposed; a column it could not is present,
264
+ * visible, and **excluded** until somebody says what it is. Pre-selecting it
265
+ * with a plausible default is the failure that matters — a wrong type becomes a
266
+ * wrong column in a lake nobody re-checks, and everything downstream reads it
267
+ * as fact rather than as the guess it was.
268
+ *
269
+ * Keyed by position rather than by name on purpose: `SELECT a.id, b.id` gives
270
+ * two columns called `id`, and a map would silently merge their choices.
271
+ */
272
+ export function initialChoices(columns) {
273
+ return columns.map((column) => ({ include: column.type !== null, type: column.type ?? '' }));
274
+ }
275
+ /**
276
+ * The type this would create, and everything standing in the way of creating it.
277
+ *
278
+ * Pure, and separate from the panel, because these are the rules that decide
279
+ * whether a schema somebody approved is one the publish route will accept — and
280
+ * rules that live inside a component are rules only a rendered DOM can check.
281
+ *
282
+ * `columnName` is sent as well as `name`, and they are the same string. The
283
+ * publish service maps `columnName` to `sourceColumn` and `name` to the property
284
+ * itself, and the store reads records by property name; sending them equal is
285
+ * what makes a load match. See the server's `DiscoveredColumn.name`.
286
+ */
287
+ export function proposalFrom(discovery, choices) {
288
+ const chosen = discovery.columns
289
+ .map((column, index) => ({ column, choice: choices[index] ?? { include: false, type: '' } }))
290
+ .filter((entry) => entry.choice.include);
291
+ const problems = [];
292
+ const untyped = chosen.filter((entry) => entry.choice.type === '');
293
+ if (untyped.length > 0) {
294
+ problems.push(`Choose a type for ${untyped.map((entry) => `"${entry.column.name}"`).join(', ')}, or leave ${untyped.length === 1 ? 'it' : 'them'} out.`);
295
+ }
296
+ const counts = new Map();
297
+ for (const entry of chosen) {
298
+ counts.set(entry.column.name, (counts.get(entry.column.name) ?? 0) + 1);
299
+ }
300
+ const duplicated = [...counts].filter(([, count]) => count > 1).map(([name]) => `"${name}"`);
301
+ if (duplicated.length > 0) {
302
+ problems.push(`${duplicated.join(', ')} appears more than once. A record is an object, so only one of them can survive — leave the others out.`);
303
+ }
304
+ const properties = [];
305
+ for (const entry of chosen) {
306
+ if (entry.choice.type === '')
307
+ continue;
308
+ properties.push({
309
+ name: entry.column.name,
310
+ columnName: entry.column.name,
311
+ type: entry.choice.type,
312
+ // Not stated is published nullable. A column marked NOT NULL that the
313
+ // source sometimes leaves empty is a load that fails at 3am; a nullable
314
+ // column that never holds a null costs nothing at all.
315
+ nullable: entry.column.nullable ?? true,
316
+ });
317
+ }
318
+ if (properties.length === 0) {
319
+ problems.push('Nothing is selected, and a type with no properties is refused.');
320
+ }
321
+ return { draft: { name: discovery.targetType, properties }, problems };
322
+ }
323
+ /**
324
+ * What the source looks like, offered to the person who has to name it.
325
+ *
326
+ * Only for a SAVED connector: discovery runs the connector's own configured
327
+ * read, and there is nothing to read from a form that has not been stored yet.
328
+ *
329
+ * The screen's job is to make the difference between what was *reported* and
330
+ * what was *inferred* impossible to miss, because that difference is the whole
331
+ * value of the report. A driver describing a `NUMERIC` column is the database
332
+ * speaking; forty records that all happened to hold a string is a sample, and
333
+ * the forty-first is where somebody finds out.
334
+ */
335
+ function SchemaDiscoveryPanel({ connectorId, bridge, }) {
336
+ // Counted rather than timestamped so a second discovery always remounts the
337
+ // table below, dropping the choices somebody made against a column list that
338
+ // no longer exists.
339
+ const [discovered, setDiscovered] = useState();
340
+ const discover = useMutation({
341
+ mutationFn: () => bridge.discover(connectorId),
342
+ onSuccess: (value) => setDiscovered((previous) => ({ run: (previous?.run ?? 0) + 1, value })),
343
+ });
344
+ return (_jsxs("div", { className: cn('rounded-md border border-dashed p-3', RULE), children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsxs("button", { type: "button", onClick: () => discover.mutate(), disabled: discover.isPending, className: cn('flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-40', RULE, 'hover:bg-zinc-50 dark:hover:bg-zinc-800'), children: [discover.isPending ? (_jsx(Loader2, { size: 12, className: "animate-spin" })) : (_jsx(ScanSearch, { size: 12 })), discover.isPending ? 'Reading the source…' : 'Discover schema'] }), _jsx("span", { className: cn('text-[11px]', MUTED), children: "Reads the source and reports its columns. Creates nothing on its own." })] }), discover.error ? (_jsx("p", { className: "mt-2 text-[11px] text-red-600", children: discover.error instanceof Error ? discover.error.message : 'Could not read the source.' })) : null, discovered && (_jsx(DiscoveredSchema, { discovery: discovered.value, createType: bridge.createType }, discovered.run))] }));
345
+ }
346
+ function DiscoveredSchema({ discovery, createType, }) {
347
+ const [choices, setChoices] = useState(() => initialChoices(discovery.columns));
348
+ const { draft, problems } = proposalFrom(discovery, choices);
349
+ const setChoice = (index, next) => setChoices((current) => current.map((choice, position) => (position === index ? { ...choice, ...next } : choice)));
350
+ return (_jsxs("div", { className: "mt-3 space-y-3", children: [_jsx("p", { className: cn('text-[11px]', MUTED), children: discovery.caveat }), _jsx(DriftReport, { drift: discovery.drift, targetType: discovery.targetType }), discovery.columns.length === 0 ? (_jsx("p", { className: cn('text-[11px]', MUTED), children: "No columns came back." })) : (_jsxs("table", { className: "w-full text-left text-[11px]", children: [_jsx("thead", { className: cn('font-mono uppercase tracking-[0.14em]', MUTED), children: _jsxs("tr", { children: [_jsx("th", { className: "w-6 pb-1 font-normal", children: _jsx("span", { className: "sr-only", children: "Include" }) }), _jsx("th", { className: "pb-1 font-normal", children: "Column" }), _jsx("th", { className: "pb-1 font-normal", children: "Type" }), _jsx("th", { className: "pb-1 font-normal", children: "Null" }), _jsx("th", { className: "pb-1 font-normal", children: "Source" })] }) }), _jsx("tbody", { children: discovery.columns.map((column, index) => (_jsx(ColumnRow
351
+ // The source may legally return two columns of one name, so the
352
+ // position has to be part of the key: on its own the name would
353
+ // collide, and React would reuse one row's choice for the other.
354
+ , { column: column, choice: choices[index] ?? { include: false, type: '' }, onChange: (next) => setChoice(index, next) }, `${column.name}-${index}`))) })] })), problems.map((problem) => (_jsxs("p", { className: "flex items-start gap-1.5 text-[11px] text-amber-600", children: [_jsx(TriangleAlert, { size: 11, className: "mt-0.5 shrink-0", "aria-hidden": true }), problem] }, problem))), _jsx(Confirmation, { discovery: discovery, draft: draft, problems: problems, createType: createType })] }));
355
+ }
356
+ /**
357
+ * The act that creates the type — the only thing on this screen that writes.
358
+ *
359
+ * Its own component because it has three states and they are not variations on
360
+ * a button: nothing has been created yet, something has, or this console has no
361
+ * way to create anything and has to hand over the request instead.
362
+ */
363
+ function Confirmation({ discovery, draft, problems, createType, }) {
364
+ const [created, setCreated] = useState(false);
365
+ const create = useMutation({
366
+ mutationFn: () => {
367
+ if (!createType)
368
+ return Promise.reject(new Error('This console cannot create types.'));
369
+ return createType(draft);
370
+ },
371
+ onSuccess: () => setCreated(true),
372
+ });
373
+ if (!createType)
374
+ return _jsx(UnwiredConfirmation, { draft: draft });
375
+ if (created) {
376
+ return (_jsxs("p", { className: "flex items-center gap-1.5 text-[11px] text-emerald-600", children: [_jsx(CircleCheck, { size: 11, "aria-hidden": true }), discovery.targetType, " now exists with ", draft.properties.length, " properties. Running this connector will load into it."] }));
377
+ }
378
+ return (_jsxs("div", { className: "space-y-1", children: [_jsx("button", { type: "button", onClick: () => create.mutate(), disabled: problems.length > 0 || create.isPending, className: "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: create.isPending
379
+ ? 'Creating…'
380
+ : discovery.typeExists
381
+ ? `Update ${discovery.targetType}`
382
+ : `Create ${discovery.targetType}` }), _jsx("p", { className: cn('text-[11px]', MUTED), children: discovery.typeExists
383
+ ? 'Adds and retypes properties. Display names, descriptions and classifications somebody wrote are kept.'
384
+ : 'This is the act that creates the type. Nothing has been created up to here.' }), create.error ? (_jsx("p", { className: "text-[11px] text-red-600", children: create.error instanceof Error ? create.error.message : 'Could not create it.' })) : null] }));
385
+ }
386
+ /** One column, with the two decisions a person can make about it. */
387
+ function ColumnRow({ column, choice, onChange, }) {
388
+ return (_jsxs(_Fragment, { children: [_jsxs("tr", { className: cn('border-t', RULE), children: [_jsx("td", { className: "py-1 align-top", children: _jsx("input", { type: "checkbox", checked: choice.include, "aria-label": `Include ${column.name}`, onChange: (event) => onChange({ include: event.target.checked }) }) }), _jsx("td", { className: "py-1 align-top font-mono", children: column.name }), _jsxs("td", { className: "py-1 align-top", children: [_jsxs("select", { value: choice.type, "aria-label": `Type for ${column.name}`, onChange: (event) => {
389
+ const next = SCALAR_TYPES.find((scalar) => scalar === event.target.value);
390
+ onChange({ type: next ?? '' });
391
+ }, className: cn('rounded-sm border bg-transparent px-1 py-0.5 font-mono text-[11px]', RULE, choice.type === '' && 'text-amber-600'), children: [_jsx("option", { value: "", children: "not typed" }), SCALAR_TYPES.map((scalar) => (_jsx("option", { value: scalar, children: scalar }, scalar)))] }), column.confidence === 'inferred' && (_jsx("span", { className: cn('ml-1.5 font-mono text-[10px]', MUTED), children: "inferred" }))] }), _jsx("td", { className: cn('py-1 align-top font-mono', MUTED), children: column.nullable === null ? 'not stated' : column.nullable ? 'nullable' : 'not null' }), _jsx("td", { className: cn('py-1 align-top font-mono', MUTED), children: column.sourceType })] }), column.note && (_jsxs("tr", { children: [_jsx("td", {}), _jsx("td", { colSpan: 4, className: "pb-1.5 text-[11px] text-amber-600", children: column.note })] }))] }));
392
+ }
393
+ /**
394
+ * What the source says now against what the type says now.
395
+ *
396
+ * The part worth having. A first discovery happens once per source; drift
397
+ * happens for as long as the connector exists, and every one of these is silent
398
+ * today — an added column is dropped by the store, a removed one loads as null,
399
+ * and a retyped one is coerced into whatever the catalog still believes.
400
+ */
401
+ function DriftReport({ drift, targetType }) {
402
+ if (!drift) {
403
+ return (_jsxs("p", { className: cn('text-[11px]', MUTED), children: [targetType, " does not exist yet, so there is nothing to compare against."] }));
404
+ }
405
+ const quiet = drift.added.length === 0 && drift.removed.length === 0 && drift.retyped.length === 0;
406
+ if (quiet) {
407
+ return (_jsxs("p", { className: "flex items-center gap-1.5 text-[11px] text-emerald-600", children: [_jsx(CircleCheck, { size: 11, "aria-hidden": true }), "The source still matches ", targetType, "."] }));
408
+ }
409
+ return (_jsxs("div", { className: "space-y-1 rounded-md border border-amber-300 bg-amber-50 p-2 dark:border-amber-900 dark:bg-amber-950/30", children: [_jsxs("p", { className: "font-mono text-[10px] uppercase tracking-[0.14em] text-amber-700 dark:text-amber-400", children: ["Drift since ", targetType, " was written down"] }), drift.added.length > 0 && (_jsxs("p", { className: "text-[11px] text-amber-700 dark:text-amber-300", children: ["New in the source, and dropped by every load until the type has them:", ' ', _jsx("span", { className: "font-mono", children: drift.added.join(', ') })] })), drift.removed.length > 0 && (_jsxs("p", { className: "text-[11px] text-amber-700 dark:text-amber-300", children: ["On the type, absent from the source, so they load as null:", ' ', _jsx("span", { className: "font-mono", children: drift.removed.join(', ') })] })), drift.retyped.map((change) => (_jsxs("p", { className: "text-[11px] text-amber-700 dark:text-amber-300", children: [_jsx("span", { className: "font-mono", children: change.property }), " is ", change.now, " in the source and", ' ', change.was, " here \u2014 every load coerces it, and a value that will not convert becomes null."] }, change.property)))] }));
410
+ }
411
+ /**
412
+ * The confirmation, for a console whose host did not wire one.
413
+ *
414
+ * The request is printed rather than the button being greyed out with a
415
+ * shrug. Creating a type is a `PUT` a person can make with a terminal, and a
416
+ * host that deliberately kept type creation out of its console — because the
417
+ * publish route is owned by an application principal, or because schema changes
418
+ * go through review — has a reader here who still needs the body somebody
419
+ * approved on this screen.
420
+ */
421
+ function UnwiredConfirmation({ draft }) {
422
+ return (_jsxs("div", { className: "space-y-1", children: [_jsx("p", { className: cn('text-[11px]', MUTED), children: "This console cannot create types \u2014 nothing is wired to the publish route. What was confirmed above is this request:" }), _jsx("pre", { className: cn('overflow-x-auto rounded-md border p-2 font-mono text-[10px]', RULE, 'bg-zinc-50 dark:bg-zinc-950'), children: `PUT /publish/${draft.name}/schema\n${JSON.stringify(draft, null, 2)}` })] }));
423
+ }
424
+ function ConnectorForm({ connector, transforms, connections, schemaDiscovery, onClose, onSaved, }) {
194
425
  const client = useCatalogClient();
195
426
  const [kind, setKind] = useState(toConnectorKind(connector?.kind ?? 'http'));
196
427
  const [connectionId, setConnectionId] = useState(connector?.connectionId ?? INLINE_CONNECTION);
@@ -255,7 +486,7 @@ function ConnectorForm({ connector, transforms, connections, onClose, onSaved, }
255
486
  return (_jsxs("form", { className: cn('mt-6 space-y-4 rounded-lg border p-4', RULE, PANEL), onSubmit: (event) => {
256
487
  event.preventDefault();
257
488
  save.mutate();
258
- }, children: [_jsxs("div", { className: "grid gap-3 sm:grid-cols-3", children: [_jsx(TextField, { label: "Name", value: draft.name, onChange: (name) => setDraft({ ...draft, name }), placeholder: "Nightly fleet load" }), _jsx(TextField, { label: "Target object type", value: draft.targetType, onChange: (targetType) => setDraft({ ...draft, targetType }), placeholder: "e.g. Mvr" }), _jsx(SelectField, { label: "Source kind", ariaLabel: "Source kind", value: kind, onValueChange: (value) => setKind(toConnectorKind(value)), options: KIND_OPTIONS })] }), usesConnection(kind) && (_jsx(ConnectionPicker, { value: chosenConnection, options: connectionOptions, viaConnection: viaConnection, onChange: setConnectionId })), _jsx(SourceFields, { kind: kind, draft: source, onChange: setSource, viaConnection: viaConnection }), _jsx(ReadModeFields, { kind: kind, mode: mode, onModeChange: setMode, draft: source, onChange: setSource }), _jsxs("div", { className: "grid gap-3 sm:grid-cols-2", children: [!viaConnection && (_jsx(CredentialField, { kind: kind, value: draft.secretEnvVar, onChange: (secretEnvVar) => setDraft({ ...draft, secretEnvVar }) })), _jsx(SelectField, { label: "Transform", ariaLabel: "Transform", value: draft.transformId, onValueChange: (transformId) => setDraft({ ...draft, transformId }), options: [
489
+ }, children: [_jsxs("div", { className: "grid gap-3 sm:grid-cols-3", children: [_jsx(TextField, { label: "Name", value: draft.name, onChange: (name) => setDraft({ ...draft, name }), placeholder: "Nightly fleet load" }), _jsx(TextField, { label: "Target object type", value: draft.targetType, onChange: (targetType) => setDraft({ ...draft, targetType }), placeholder: "e.g. Mvr" }), _jsx(SelectField, { label: "Source kind", ariaLabel: "Source kind", value: kind, onValueChange: (value) => setKind(toConnectorKind(value)), options: KIND_OPTIONS })] }), usesConnection(kind) && (_jsx(ConnectionPicker, { value: chosenConnection, options: connectionOptions, viaConnection: viaConnection, onChange: setConnectionId })), schemaDiscovery && connector?.id && (_jsx(SchemaDiscoveryPanel, { connectorId: connector.id, bridge: schemaDiscovery })), _jsx(SourceFields, { kind: kind, draft: source, onChange: setSource, viaConnection: viaConnection }), _jsx(ReadModeFields, { kind: kind, mode: mode, onModeChange: setMode, draft: source, onChange: setSource }), _jsxs("div", { className: "grid gap-3 sm:grid-cols-2", children: [!viaConnection && (_jsx(CredentialField, { kind: kind, value: draft.secretEnvVar, onChange: (secretEnvVar) => setDraft({ ...draft, secretEnvVar }) })), _jsx(SelectField, { label: "Transform", ariaLabel: "Transform", value: draft.transformId, onValueChange: (transformId) => setDraft({ ...draft, transformId }), options: [
259
490
  {
260
491
  value: '',
261
492
  label: 'No transform',
package/dist/context.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CatalogAuditEvent, CatalogConnection, CatalogConnector, CatalogObjectPage, CatalogQueryRelation, CatalogQueryResult, CatalogSnapshot, CatalogTraceList, CatalogTransform, ConnectionCheck, ConnectorRun, Dashboard, DashboardCard, ObjectQueryParams, PropertyPatch, SaveQueryInput, SavedQuery, TraceQuery, TransformLanguage, TransformResult, TypePatch } from '@dudousxd/nestjs-catalog/client';
1
+ import type { CatalogAuditEvent, CatalogConnection, CatalogConnector, CatalogObjectPage, CatalogQueryRelation, CatalogQueryResult, CatalogSearchResult, CatalogSnapshot, CatalogTraceList, CatalogTransform, ConnectionCheck, ConnectorRun, Dashboard, DashboardCard, ObjectQueryParams, PropertyPatch, SaveQueryInput, SavedQuery, TraceQuery, TransformLanguage, 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';
@@ -39,6 +39,21 @@ export interface CatalogTransport {
39
39
  * the console's own does it in one line.
40
40
  */
41
41
  url?(path: string): string;
42
+ /**
43
+ * `PUT`, for the one route that has to be one.
44
+ *
45
+ * Optional for the same reason `url` is: a transport written before this
46
+ * existed keeps compiling. Publishing a type is an idempotent upsert of the
47
+ * whole shape — the same body twice is the same result — and the publish
48
+ * route says so with its method. Adding a `POST` alias to spare this
49
+ * three-line addition would have put a second name on one act, and the two
50
+ * would eventually mean different things.
51
+ *
52
+ * A client that needs it and does not find it refuses by name rather than
53
+ * silently doing nothing, because a "Create type" button that returns without
54
+ * creating a type is the failure this whole panel exists to prevent.
55
+ */
56
+ put?<T>(path: string, body: unknown): Promise<T>;
42
57
  }
43
58
  /**
44
59
  * What this deployment can actually execute.
@@ -209,6 +224,19 @@ export interface CatalogClient {
209
224
  sql: string;
210
225
  maxRows?: number;
211
226
  }): Promise<CatalogQueryResult>;
227
+ /**
228
+ * One term across object types, properties, saved queries and dashboards.
229
+ *
230
+ * One call rather than four, and the ranking is the server's. A client that
231
+ * merged four lists would own the order across kinds, which means the order
232
+ * would live in whichever screen was written last — see the block above
233
+ * `CatalogService.search`, which makes the argument where the code is.
234
+ *
235
+ * `limit` is the caller's request and the server's decision: it caps whatever
236
+ * is asked for, and the answer carries `total` and `truncated` so a screen can
237
+ * say "50 of 312" rather than implying the list it drew is the list.
238
+ */
239
+ search(term: string, limit?: number): Promise<CatalogSearchResult>;
212
240
  workspaceCapabilities(): Promise<{
213
241
  workspace: boolean;
214
242
  query: boolean;
@@ -321,6 +349,29 @@ export interface CatalogClient {
321
349
  deleted: boolean;
322
350
  }>;
323
351
  runConnector(id: string): Promise<ConnectorRun>;
352
+ /**
353
+ * What the source behind a connector looks like right now. Writes nothing.
354
+ *
355
+ * Typed loosely on purpose. The shape comes from
356
+ * `@dudousxd/nestjs-catalog-pipeline`, and this package must not import that
357
+ * one — it would drag a package built for a Node process, with database
358
+ * drivers behind optional imports, into a browser bundle. `PipelineCapabilities`
359
+ * above is mirrored for exactly the same reason.
360
+ */
361
+ discoverConnectorSchema(id: string): Promise<unknown>;
362
+ /**
363
+ * Publish an object type's schema — create it, or update the shape of one
364
+ * that exists.
365
+ *
366
+ * The only write on this client that does not go through the catalog's own
367
+ * routes: publishing is how a type comes into existence at all, and there is
368
+ * deliberately no `POST /catalog/types`, because structure follows a
369
+ * publisher and curation follows a person.
370
+ *
371
+ * Refuses by name when the transport cannot `PUT`, rather than resolving
372
+ * having done nothing.
373
+ */
374
+ publishType(name: string, schema: unknown): Promise<unknown>;
324
375
  listRuns(connectorId?: string): Promise<ConnectorRun[]>;
325
376
  listTransforms(): Promise<CatalogTransform[]>;
326
377
  saveTransform(input: TransformInput): Promise<CatalogTransform>;
@@ -389,17 +440,31 @@ export interface CatalogProviderProps {
389
440
  * the README passes nothing.
390
441
  */
391
442
  pipelineBasePath?: string;
443
+ /** Where `/publish` is mounted — a sibling of {@link pipelineBasePath}. */
444
+ publishBasePath?: string;
392
445
  /** Same, for the access endpoints. */
393
446
  accessBasePath?: string;
394
447
  children: ReactNode;
395
448
  }
396
- export declare function CatalogProvider({ transport, pipelineBasePath, accessBasePath, children, }: CatalogProviderProps): import("react/jsx-runtime").JSX.Element;
449
+ export declare function CatalogProvider({ transport, pipelineBasePath, publishBasePath, accessBasePath, children, }: CatalogProviderProps): import("react/jsx-runtime").JSX.Element;
397
450
  export declare function useCatalogClient(): CatalogClient;
398
451
  /** Query keys, exported so a host can invalidate them from its own code. */
399
452
  export declare const catalogQueryKeys: {
400
453
  all: readonly ["nestjs-catalog"];
401
454
  snapshot: readonly ["nestjs-catalog", "snapshot"];
402
455
  objects: (type: string, params: ObjectQueryParams) => readonly ["nestjs-catalog", "objects", string, ObjectQueryParams];
456
+ /**
457
+ * Keyed on the term, so react-query caches per term and a backspace shows the
458
+ * previous answer instantly instead of re-asking.
459
+ *
460
+ * Deliberately NOT keyed on anything about the caller. The answer already
461
+ * depends on who is asking — the route filters by principal — and a cache key
462
+ * that did not say so would be a bug; it is safe here only because a browser
463
+ * session is one principal, and a host that swaps identity in place without a
464
+ * reload should invalidate `catalogQueryKeys.all`, which is what that prefix
465
+ * is for.
466
+ */
467
+ search: (term: string, limit?: number) => readonly ["nestjs-catalog", "search", string, number | null];
403
468
  /**
404
469
  * The pipeline keys are nested under one prefix so a host — or a screen that
405
470
  * just ran a connector — can invalidate the whole of it at once. Running a
package/dist/context.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { catalogRoutes } from '@dudousxd/nestjs-catalog/client';
3
3
  import { createContext, useContext, useMemo } from 'react';
4
- import { DEFAULT_ACCESS_BASE_PATH, DEFAULT_PIPELINE_BASE_PATH, accessRoutes, embedRoutes, pipelineRoutes, } from './routes';
4
+ import { DEFAULT_ACCESS_BASE_PATH, DEFAULT_PIPELINE_BASE_PATH, DEFAULT_PUBLISH_BASE_PATH, accessRoutes, embedRoutes, pipelineRoutes, } from './routes';
5
5
  const CatalogContext = createContext(null);
6
- export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE_BASE_PATH, accessBasePath = DEFAULT_ACCESS_BASE_PATH, children, }) {
6
+ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE_BASE_PATH, publishBasePath = DEFAULT_PUBLISH_BASE_PATH, accessBasePath = DEFAULT_ACCESS_BASE_PATH, children, }) {
7
7
  const client = useMemo(() => {
8
8
  const pipeline = pipelineRoutes(pipelineBasePath);
9
9
  const access = accessRoutes(accessBasePath);
@@ -17,6 +17,15 @@ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE
17
17
  reset: () => transport.post(catalogRoutes.reset()),
18
18
  queryRelations: () => transport.get(catalogRoutes.queryRelations()),
19
19
  runQuery: (input) => transport.post(catalogRoutes.query(), input),
20
+ // `limit` is omitted rather than sent undefined when nobody asked for
21
+ // one, for the reason `listRuns` states below: a transport that
22
+ // serialises `limit=` hands the server an empty string, and `Number('')`
23
+ // is 0 — which the route would floor back to 1 and answer with a single
24
+ // row that reads as "there is only one match".
25
+ search: (term, limit) => transport.get(catalogRoutes.search(), {
26
+ q: term,
27
+ ...(limit === undefined ? {} : { limit }),
28
+ }),
20
29
  workspaceCapabilities: () => transport.get(catalogRoutes.workspaceCapabilities()),
21
30
  listSavedQueries: () => transport.get(catalogRoutes.savedQueries()),
22
31
  saveQuery: (input) => transport.post(catalogRoutes.savedQueries(), input),
@@ -50,6 +59,15 @@ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE
50
59
  saveConnector: (input) => transport.post(pipeline.connectors(), input),
51
60
  deleteConnector: (id) => transport.delete(pipeline.connector(id)),
52
61
  runConnector: (id) => transport.post(pipeline.runConnector(id), {}),
62
+ discoverConnectorSchema: (id) => transport.post(pipeline.discoverConnectorSchema(id), {}),
63
+ publishType: (name, schema) => {
64
+ if (!transport.put) {
65
+ throw new Error('This transport cannot PUT, so it cannot publish a type. Implement `put` on the ' +
66
+ 'transport you passed to CatalogProvider — publishing is an idempotent upsert of ' +
67
+ 'the whole shape, which is why the route is a PUT and not a POST.');
68
+ }
69
+ return transport.put(`${publishBasePath}/${encodeURIComponent(name)}/schema`, schema);
70
+ },
53
71
  // The parameter is omitted rather than sent empty when no connector is
54
72
  // named, because a transport that serialises `connector=` turns "every
55
73
  // run" into "runs of the connector whose id is the empty string", which
@@ -67,7 +85,7 @@ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE
67
85
  listPeople: (query) => transport.get(access.people(query)),
68
86
  upsertPerson: (input) => transport.post(access.people(), input),
69
87
  };
70
- }, [transport, pipelineBasePath, accessBasePath]);
88
+ }, [transport, pipelineBasePath, publishBasePath, accessBasePath]);
71
89
  return _jsx(CatalogContext.Provider, { value: client, children: children });
72
90
  }
73
91
  export function useCatalogClient() {
@@ -82,6 +100,18 @@ export const catalogQueryKeys = {
82
100
  all: ['nestjs-catalog'],
83
101
  snapshot: ['nestjs-catalog', 'snapshot'],
84
102
  objects: (type, params) => ['nestjs-catalog', 'objects', type, params],
103
+ /**
104
+ * Keyed on the term, so react-query caches per term and a backspace shows the
105
+ * previous answer instantly instead of re-asking.
106
+ *
107
+ * Deliberately NOT keyed on anything about the caller. The answer already
108
+ * depends on who is asking — the route filters by principal — and a cache key
109
+ * that did not say so would be a bug; it is safe here only because a browser
110
+ * session is one principal, and a host that swaps identity in place without a
111
+ * reload should invalidate `catalogQueryKeys.all`, which is what that prefix
112
+ * is for.
113
+ */
114
+ search: (term, limit) => ['nestjs-catalog', 'search', term, limit ?? null],
85
115
  /**
86
116
  * The pipeline keys are nested under one prefix so a host — or a screen that
87
117
  * just ran a connector — can invalidate the whole of it at once. Running a
@@ -0,0 +1,37 @@
1
+ import type { CatalogObjectTypeDef } from '@dudousxd/nestjs-catalog/client';
2
+ /**
3
+ * How old the data a type serves is, said in words.
4
+ *
5
+ * Its own module because two screens ask and the answer must not drift between
6
+ * them: a type reading "4 months" on the model screen and "recent" on a card is
7
+ * worse than neither saying anything.
8
+ *
9
+ * Deliberately NOT a health verdict. The catalog cannot tell a deleted
10
+ * publisher from a monthly load, and a type labelled "orphaned" is a type
11
+ * somebody eventually deletes on the strength of a guess. What is reported is
12
+ * the fact — when it last committed — and the reader, who knows the cadence,
13
+ * draws the conclusion.
14
+ */
15
+ /** Never loaded is a different thing from loaded long ago, so it has its own shape. */
16
+ export type Freshness = {
17
+ kind: 'never';
18
+ } | {
19
+ kind: 'loaded';
20
+ label: string;
21
+ ageMs: number;
22
+ };
23
+ export declare function freshnessOf(type: CatalogObjectTypeDef, now?: number): Freshness;
24
+ /**
25
+ * Whether to draw attention to it, and the honest answer is "rarely".
26
+ *
27
+ * There is no universal threshold. A type fed by an hourly connector is dead at
28
+ * two days; one fed by a monthly load is healthy at twenty. Without knowing the
29
+ * cadence the only defensible marks are the two that need no cadence to read:
30
+ * nothing was ever committed, and nothing has been committed in a long time by
31
+ * any schedule anyone runs.
32
+ *
33
+ * A week is that line. It is not a claim that a week is bad — it is the point
34
+ * past which the age is worth a second glance rather than a number in the
35
+ * corner.
36
+ */
37
+ export declare function isWorthFlagging(freshness: Freshness): boolean;
@@ -0,0 +1,44 @@
1
+ const MINUTE = 60_000;
2
+ const HOUR = 60 * MINUTE;
3
+ const DAY = 24 * HOUR;
4
+ export function freshnessOf(type, now = Date.now()) {
5
+ if (!type.lastCommittedAt)
6
+ return { kind: 'never' };
7
+ const at = Date.parse(type.lastCommittedAt);
8
+ if (Number.isNaN(at))
9
+ return { kind: 'never' };
10
+ // Clamped at zero rather than reported as negative. Clock skew between the
11
+ // database and the browser is ordinary, and "in 3 minutes" reads as a bug in
12
+ // the catalog rather than as the two-second difference it is.
13
+ const ageMs = Math.max(0, now - at);
14
+ return { kind: 'loaded', label: relative(ageMs), ageMs };
15
+ }
16
+ function relative(ageMs) {
17
+ if (ageMs < MINUTE)
18
+ return 'just now';
19
+ if (ageMs < HOUR)
20
+ return `${Math.floor(ageMs / MINUTE)}m ago`;
21
+ if (ageMs < DAY)
22
+ return `${Math.floor(ageMs / HOUR)}h ago`;
23
+ const days = Math.floor(ageMs / DAY);
24
+ if (days < 30)
25
+ return `${days}d ago`;
26
+ const months = Math.floor(days / 30);
27
+ return months < 12 ? `${months}mo ago` : `${Math.floor(months / 12)}y ago`;
28
+ }
29
+ /**
30
+ * Whether to draw attention to it, and the honest answer is "rarely".
31
+ *
32
+ * There is no universal threshold. A type fed by an hourly connector is dead at
33
+ * two days; one fed by a monthly load is healthy at twenty. Without knowing the
34
+ * cadence the only defensible marks are the two that need no cadence to read:
35
+ * nothing was ever committed, and nothing has been committed in a long time by
36
+ * any schedule anyone runs.
37
+ *
38
+ * A week is that line. It is not a claim that a week is bad — it is the point
39
+ * past which the age is worth a second glance rather than a number in the
40
+ * corner.
41
+ */
42
+ export function isWorthFlagging(freshness) {
43
+ return freshness.kind === 'never' || freshness.ageMs >= 7 * DAY;
44
+ }
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export { EMBED_ACTIONS, type EmbedAction, type EmbedActions, EmbeddedChart, type
11
11
  export { FlowView } from './FlowView';
12
12
  export { GovernanceTimeline } from './GovernanceTimeline';
13
13
  export { QueryConsole, type QueryConsoleProps } from './QueryConsole';
14
+ export { CatalogSearch, type CatalogSearchProps } from './search-console';
14
15
  export { SavedQueryPanel } from './SavedQueryPanel';
15
16
  export { CATALOG_EVENT_META, type CatalogTraceSource, eventMeta, TraceExplorer, useTraceSource, } from './TraceExplorer';
16
17
  export { ConnectionPanel, type ConnectionPanelProps, connectionOptionsFor, describeConnection, } from './ConnectionPanel';
package/dist/index.js CHANGED
@@ -15,6 +15,11 @@ export { EMBED_ACTIONS, EmbeddedChart, EmbeddedDashboard, chartsInLayoutOrder, r
15
15
  export { FlowView } from './FlowView';
16
16
  export { GovernanceTimeline } from './GovernanceTimeline';
17
17
  export { QueryConsole } from './QueryConsole';
18
+ // One box across the whole catalog: types, properties, saved queries, boards.
19
+ // Not mounted anywhere by this package — a host places it wherever its shell
20
+ // wants a search, and tells it where each kind of thing lives with the same
21
+ // `explorerHref` shape `CatalogManager` takes.
22
+ export { CatalogSearch } from './search-console';
18
23
  export { SavedQueryPanel } from './SavedQueryPanel';
19
24
  export { CATALOG_EVENT_META, eventMeta, TraceExplorer, useTraceSource, } from './TraceExplorer';
20
25
  // Getting data in: connections, connectors and the code that reshapes what they
package/dist/routes.d.ts CHANGED
@@ -55,6 +55,17 @@ export declare const embedRoutes: {
55
55
  };
56
56
  /** Where the pipeline endpoints sit unless the host says otherwise. */
57
57
  export declare const DEFAULT_PIPELINE_BASE_PATH = "/pipeline";
58
+ /**
59
+ * Where the publish endpoints sit unless the host says otherwise.
60
+ *
61
+ * A sibling of the pipeline's base, not a child, because that is how the
62
+ * library mounts them: one `path` given to `CatalogPipelineModule.forRoot`
63
+ * yields `<path>/pipeline` and `<path>/publish`. Its own constant rather than a
64
+ * string derived from the other, because deriving would mean rewriting
65
+ * `/pipeline` into `/publish` inside whatever the host passed — which is right
66
+ * until the day a host passes a base that contains the word twice.
67
+ */
68
+ export declare const DEFAULT_PUBLISH_BASE_PATH = "/publish";
58
69
  /** Where the access endpoints sit unless the host says otherwise. */
59
70
  export declare const DEFAULT_ACCESS_BASE_PATH = "/access";
60
71
  export interface PipelineRoutes {
@@ -67,6 +78,17 @@ export interface PipelineRoutes {
67
78
  connectors(): string;
68
79
  connector(id: string): string;
69
80
  runConnector(id: string): string;
81
+ /**
82
+ * What the source behind a connector looks like right now.
83
+ *
84
+ * A read that writes nothing: it runs the connector's own configured query
85
+ * with no rows asked for, and reports the columns. Here rather than on a
86
+ * generic "describe this database" route because the connector is what
87
+ * already holds the address, the credential reference and the statement —
88
+ * a route taking those as arguments would be a way to point the server at
89
+ * any database at all.
90
+ */
91
+ discoverConnectorSchema(id: string): string;
70
92
  runs(): string;
71
93
  transforms(): string;
72
94
  transform(id: string): string;
package/dist/routes.js CHANGED
@@ -55,6 +55,17 @@ export const embedRoutes = {
55
55
  };
56
56
  /** Where the pipeline endpoints sit unless the host says otherwise. */
57
57
  export const DEFAULT_PIPELINE_BASE_PATH = '/pipeline';
58
+ /**
59
+ * Where the publish endpoints sit unless the host says otherwise.
60
+ *
61
+ * A sibling of the pipeline's base, not a child, because that is how the
62
+ * library mounts them: one `path` given to `CatalogPipelineModule.forRoot`
63
+ * yields `<path>/pipeline` and `<path>/publish`. Its own constant rather than a
64
+ * string derived from the other, because deriving would mean rewriting
65
+ * `/pipeline` into `/publish` inside whatever the host passed — which is right
66
+ * until the day a host passes a base that contains the word twice.
67
+ */
68
+ export const DEFAULT_PUBLISH_BASE_PATH = '/publish';
58
69
  /** Where the access endpoints sit unless the host says otherwise. */
59
70
  export const DEFAULT_ACCESS_BASE_PATH = '/access';
60
71
  /**
@@ -79,6 +90,7 @@ export function pipelineRoutes(basePath = DEFAULT_PIPELINE_BASE_PATH) {
79
90
  connectors: () => `${base}/connectors`,
80
91
  connector: (id) => `${base}/connectors/${encodeURIComponent(id)}`,
81
92
  runConnector: (id) => `${base}/connectors/${encodeURIComponent(id)}/run`,
93
+ discoverConnectorSchema: (id) => `${base}/connectors/${encodeURIComponent(id)}/discover`,
82
94
  runs: () => `${base}/runs`,
83
95
  transforms: () => `${base}/transforms`,
84
96
  transform: (id) => `${base}/transforms/${encodeURIComponent(id)}`,
@@ -0,0 +1,23 @@
1
+ export interface CatalogSearchProps {
2
+ /**
3
+ * Where the model screen lives, given a type name. Omit and type and property
4
+ * rows render as plain rows rather than as links.
5
+ *
6
+ * The same prop, the same shape and the same name as `CatalogManager`'s,
7
+ * because it is the same navigation: the host owns its routing, and the
8
+ * shipped console answers `#objects?type=X`. A second spelling here would
9
+ * mean a host wiring the two screens differently for one destination.
10
+ */
11
+ explorerHref?: (typeName: string) => string;
12
+ /** Where a saved query opens. Omit to render saved-query rows as plain rows. */
13
+ savedQueryHref?: (id: string) => string;
14
+ /** Where a dashboard opens. Omit to render dashboard rows as plain rows. */
15
+ dashboardHref?: (id: string) => string;
16
+ /** How many rows to ask for. The server caps whatever this says. */
17
+ limit?: number;
18
+ placeholder?: string;
19
+ /** Heading copy, so the host can call this whatever its users call it. */
20
+ title?: string;
21
+ eyebrow?: string;
22
+ }
23
+ export declare function CatalogSearch({ explorerHref, savedQueryHref, dashboardHref, limit, placeholder, title, eyebrow, }: CatalogSearchProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,146 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useQuery } from '@tanstack/react-query';
3
+ import { ArrowUpRight, Search } from 'lucide-react';
4
+ import { useEffect, useMemo, useState } from 'react';
5
+ import { cn } from './cn';
6
+ import { catalogQueryKeys, useCatalogClient } from './context';
7
+ import { TextField } from './ui/field';
8
+ /**
9
+ * One box that crosses the catalog.
10
+ *
11
+ * Today, finding anything means knowing which screen it lives on: object types
12
+ * and their properties on the model screen, saved queries on the query screen,
13
+ * boards on the dashboards screen. At two hundred types that IS the experience,
14
+ * and the thing a person actually types is a word they half-remember.
15
+ *
16
+ * Everything about which rows come back, and in what order, is the server's —
17
+ * see `search.ts` in `@dudousxd/nestjs-catalog`. This screen deliberately does
18
+ * no ranking, no client-side filtering and no merging of its own. That is not
19
+ * deference for its own sake: the same ranking has to hold for a host that
20
+ * writes its own box against the same route, and a second copy of it here would
21
+ * be a second answer to the same question the day one of them is touched.
22
+ */
23
+ const MUTED = 'text-zinc-400 dark:text-zinc-500';
24
+ const SECONDARY = 'text-zinc-500 dark:text-zinc-400';
25
+ const RULE = 'border-zinc-200 dark:border-zinc-800';
26
+ /**
27
+ * The order the groups are drawn in, matching the server's own tie-break.
28
+ *
29
+ * Grouping is a trade and it is worth naming: it buys scannability — four short
30
+ * lists a reader recognises the shape of — and it costs the global ranking, so
31
+ * an exact property match no longer sits visually above a type that merely
32
+ * mentions the word. The `rank` chip on each row is what carries that back;
33
+ * without it the grouping would be lying by omission.
34
+ */
35
+ const KIND_ORDER = ['objectType', 'property', 'savedQuery', 'dashboard'];
36
+ const KIND_LABEL = {
37
+ objectType: 'Object types',
38
+ property: 'Properties',
39
+ savedQuery: 'Saved queries',
40
+ dashboard: 'Dashboards',
41
+ };
42
+ /**
43
+ * What the rank means, in words, because "prefix" is jargon for the reader and
44
+ * the whole argument for four named ranks over a number is that a person can
45
+ * predict them. A tooltip would hide it behind a hover; this is four words.
46
+ */
47
+ const RANK_LABEL = {
48
+ exact: 'exact name',
49
+ prefix: 'name starts with',
50
+ name: 'in the name',
51
+ text: 'in the text',
52
+ };
53
+ const RANK_TONE = {
54
+ exact: 'text-emerald-700 dark:text-emerald-300',
55
+ prefix: 'text-sky-700 dark:text-sky-300',
56
+ name: 'text-sky-700 dark:text-sky-300',
57
+ text: 'text-zinc-500 dark:text-zinc-400',
58
+ };
59
+ /**
60
+ * How long to wait after a keystroke before asking.
61
+ *
62
+ * Half the answer is free — the registry snapshot is already in memory — and
63
+ * half is two reads against the workspace store, so a request per keystroke
64
+ * would put a database under a typing load for rows that were going to be
65
+ * thrown away. 200ms is below the threshold at which a person notices the box
66
+ * is not instant, and above the interval at which anybody types.
67
+ */
68
+ const DEBOUNCE_MS = 200;
69
+ export function CatalogSearch({ explorerHref, savedQueryHref, dashboardHref, limit, placeholder = 'A type, a column, a report — whatever you remember', title = 'Search', eyebrow = 'Across the catalog', }) {
70
+ const client = useCatalogClient();
71
+ const [term, setTerm] = useState('');
72
+ const [debounced, setDebounced] = useState('');
73
+ useEffect(() => {
74
+ const handle = setTimeout(() => setDebounced(term), DEBOUNCE_MS);
75
+ return () => clearTimeout(handle);
76
+ }, [term]);
77
+ const trimmed = debounced.trim();
78
+ const { data, isFetching, isError } = useQuery({
79
+ queryKey: catalogQueryKeys.search(trimmed, limit),
80
+ queryFn: () => client.search(trimmed, limit),
81
+ // An empty box asks nothing. The route answers an empty term with an empty
82
+ // result rather than a 400, so this is politeness rather than protection —
83
+ // but a request fired on mount, before anybody has typed, is a request the
84
+ // server logs and nobody wanted.
85
+ enabled: trimmed.length > 0,
86
+ // The previous answer stays on screen while the next one is in flight, so
87
+ // the list does not blank between keystrokes. `isFetching` is what says so.
88
+ placeholderData: (previous) => previous,
89
+ staleTime: 15_000,
90
+ });
91
+ const grouped = useMemo(() => {
92
+ const hits = data?.hits ?? [];
93
+ return KIND_ORDER.map((kind) => [kind, hits.filter((hit) => hit.kind === kind)]).filter(([, rows]) => rows.length > 0);
94
+ }, [data]);
95
+ function hrefFor(hit) {
96
+ // A property navigates to the type it belongs to, not to a route of its
97
+ // own: there is no per-property screen, and inventing an anchor the host
98
+ // does not serve would be a link that goes nowhere.
99
+ if (hit.kind === 'objectType' || hit.kind === 'property') {
100
+ return hit.typeName && explorerHref ? explorerHref(hit.typeName) : undefined;
101
+ }
102
+ if (hit.kind === 'savedQuery')
103
+ return savedQueryHref?.(hit.id);
104
+ return dashboardHref?.(hit.id);
105
+ }
106
+ return (_jsxs("div", { className: "mx-auto flex h-full max-w-3xl flex-col px-6 py-8", children: [_jsxs("header", { className: "shrink-0", children: [_jsx("p", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: eyebrow }), _jsx("h2", { className: "mt-1 text-2xl font-semibold tracking-tight", children: title })] }), _jsxs("div", { className: "relative mt-5 shrink-0", children: [_jsx(Search, { size: 14, className: cn('pointer-events-none absolute right-2.5 top-[1.9rem] z-10', MUTED) }), _jsx(TextField, { label: "Search the catalog", value: term, onChange: setTerm, placeholder: placeholder })] }), _jsxs("div", { className: "mt-4 min-h-0 flex-1 overflow-y-auto", children: [_jsx(Status, { term: trimmed, isError: isError, isFetching: isFetching, total: data?.total, shown: data?.hits.length, truncated: data?.truncated }), grouped.map(([kind, rows]) => (_jsxs("section", { className: "mb-5", children: [_jsxs("div", { className: cn('flex items-baseline justify-between border-b px-1 pb-1', RULE), children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: KIND_LABEL[kind] }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: rows.length })] }), rows.map((hit) => (_jsx(Row, { hit: hit, href: hrefFor(hit) }, `${hit.kind}:${hit.typeName ?? ''}:${hit.id}`)))] }, kind)))] })] }));
107
+ }
108
+ /**
109
+ * The line above the results, which has four things to say and must not confuse
110
+ * two of them.
111
+ *
112
+ * "Nothing matched" and "we could not ask" lead a reader to opposite
113
+ * conclusions, and a refusal rendered as an empty list is the worse one — the
114
+ * same distinction `CatalogManager` makes, made again here because this screen
115
+ * has its own request.
116
+ */
117
+ function Status({ term, isError, isFetching, total, shown, truncated, }) {
118
+ if (!term) {
119
+ return (_jsx("p", { className: cn('px-1 py-8 text-center text-xs', MUTED), children: "Types, properties, saved queries and dashboards, all at once." }));
120
+ }
121
+ if (isError) {
122
+ return _jsx("p", { className: "px-1 py-8 text-center text-xs text-rose-600", children: "The search did not run" });
123
+ }
124
+ if (total === undefined) {
125
+ return _jsx("p", { className: cn('px-1 py-8 text-center text-xs', MUTED), children: "Searching\u2026" });
126
+ }
127
+ if (total === 0) {
128
+ return _jsxs("p", { className: cn('px-1 py-8 text-center text-xs', MUTED), children: ["Nothing matches \u201C", term, "\u201D."] });
129
+ }
130
+ return (_jsxs("p", { className: cn('mb-3 px-1 font-mono text-[10px]', MUTED), children: [truncated ? `${shown} of ${total} matches` : `${total} ${total === 1 ? 'match' : 'matches'}`, isFetching ? ' · updating' : ''] }));
131
+ }
132
+ /**
133
+ * One result.
134
+ *
135
+ * An `<a>` when the host said where the kind lives and a `<div>` when it did
136
+ * not — rather than a dead link or a link to `#`. A row that looks clickable and
137
+ * is not is worse than a row that does not, and a host that mounts no dashboard
138
+ * screen should not have this one inventing an anchor for it.
139
+ */
140
+ function Row({ hit, href }) {
141
+ const body = (_jsxs(_Fragment, { children: [_jsxs("span", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "block truncate text-sm", children: hit.label }), _jsxs("span", { className: cn('block truncate font-mono text-[10px]', MUTED), children: [hit.typeName && hit.typeName !== hit.label ? `${hit.typeName} · ` : '', hit.id, hit.detail ? ` · ${hit.detail}` : ''] })] }), _jsxs("span", { className: cn('shrink-0 font-mono text-[10px]', RANK_TONE[hit.rank]), children: [RANK_LABEL[hit.rank], _jsx("span", { className: cn('ml-1.5', SECONDARY), children: hit.field })] }), href && _jsx(ArrowUpRight, { size: 13, className: cn('shrink-0', MUTED), "aria-hidden": true })] }));
142
+ const className = cn('flex items-center gap-3 rounded-md px-2 py-2 text-left', href && 'transition-colors hover:bg-zinc-50 dark:hover:bg-zinc-800');
143
+ if (!href)
144
+ return _jsx("div", { className: className, children: body });
145
+ return (_jsx("a", { href: href, className: className, children: body }));
146
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudousxd/nestjs-catalog-react",
3
- "version": "0.9.0",
3
+ "version": "0.11.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",
@@ -106,7 +106,7 @@
106
106
  "@tiptap/pm": "3.29.2",
107
107
  "tiptap-markdown": "0.9.0",
108
108
  "@tiptap/core": "3.29.2",
109
- "@dudousxd/nestjs-catalog": "0.6.0"
109
+ "@dudousxd/nestjs-catalog": "0.8.0"
110
110
  },
111
111
  "dependencies": {
112
112
  "clsx": "2.1.1",