@dudousxd/nestjs-catalog-react 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/context.d.ts CHANGED
@@ -1,4 +1,4 @@
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';
1
+ import type { CatalogAuditEvent, CatalogConnection, CatalogConnector, CatalogObjectPage, CatalogQueryRelation, CatalogQueryResult, CatalogRevision, 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';
@@ -116,6 +116,25 @@ export interface TransformInput {
116
116
  language: TransformLanguage;
117
117
  code: string;
118
118
  }
119
+ /**
120
+ * One saved version of the two things in this catalog whose text a person edits.
121
+ *
122
+ * RE-EXPORTED rather than mirrored, unlike `PipelineCapabilities` above. The
123
+ * distinction is worth keeping straight: `PipelineCapabilities` is mirrored
124
+ * because importing it would mean importing `@dudousxd/nestjs-catalog-pipeline`,
125
+ * a package built for a Node process with database drivers behind optional
126
+ * imports, into a browser bundle. `CatalogRevision` has no such problem — it is
127
+ * a plain shape on `@dudousxd/nestjs-catalog/client`, the entry point that
128
+ * exists precisely so a browser can name the catalog's own contracts, and
129
+ * restating it here would be the second copy of something two packages already
130
+ * serve.
131
+ *
132
+ * Named here at all, rather than left for callers to import from the client
133
+ * package, because everything else this file's `CatalogClient` returns is
134
+ * reachable from this module and a host should not have to know which of the two
135
+ * packages owns which shape to type a variable.
136
+ */
137
+ export type { CatalogRevision };
119
138
  /** The three answers a console can give somebody about what they may do. */
120
139
  export type CatalogPersonRole = 'viewer' | 'curator' | 'admin';
121
140
  /**
@@ -252,6 +271,23 @@ export interface CatalogClient {
252
271
  result: CatalogQueryResult;
253
272
  }>;
254
273
  exportUrl(id: string): string;
274
+ /**
275
+ * Every SQL this saved query has ever been, newest first.
276
+ *
277
+ * Beside {@link listTransformRevisions} rather than one polymorphic
278
+ * `listRevisions(kind, id)`, because the two are served by different things:
279
+ * a saved query is the catalog library's own resource and a transform is the
280
+ * host's. One method taking a kind would hide that a host can move one of the
281
+ * two endpoints and not the other, which is exactly the mistake `routes.ts`
282
+ * spends its header preventing.
283
+ *
284
+ * An EMPTY list is a real answer and not an error. Every saved query written
285
+ * before revisions existed has no history, and whether the store backfills a
286
+ * first revision from the current SQL is a decision belonging to the store.
287
+ * The screen has to read "nothing recorded" as "nothing recorded" — never as
288
+ * "nothing has changed".
289
+ */
290
+ listSavedQueryRevisions(id: string): Promise<CatalogRevision[]>;
255
291
  listDashboards(): Promise<Dashboard[]>;
256
292
  /**
257
293
  * `shared` is declared on both writes, and it is not decoration.
@@ -378,6 +414,16 @@ export interface CatalogClient {
378
414
  deleteTransform(id: string): Promise<{
379
415
  deleted: boolean;
380
416
  }>;
417
+ /**
418
+ * Every version of this transform's code, newest first.
419
+ *
420
+ * The list rather than one version by number, because the screen that needs
421
+ * this is comparing two of them and has to know which exist before it can pick
422
+ * — including the case where the version a run recorded is NOT among them,
423
+ * which is what a transform older than the revision store looks like and is a
424
+ * thing the screen has to be able to say out loud.
425
+ */
426
+ listTransformRevisions(id: string): Promise<CatalogRevision[]>;
381
427
  /**
382
428
  * Run code against sample records without storing anything.
383
429
  *
@@ -478,6 +524,16 @@ export declare const catalogQueryKeys: {
478
524
  connections: readonly ["nestjs-catalog", "pipeline", "connections"];
479
525
  connectors: readonly ["nestjs-catalog", "pipeline", "connectors"];
480
526
  transforms: readonly ["nestjs-catalog", "pipeline", "transforms"];
527
+ /**
528
+ * A transform's history, keyed UNDER `transforms` on purpose.
529
+ *
530
+ * `catalogQueryKeys.transforms` is a prefix of this, so the invalidation the
531
+ * transform list already performs after a save reaches the history too — and
532
+ * it must, because saving new code is precisely what cuts a revision. Keyed
533
+ * anywhere else, the diff screen would keep showing yesterday's history beside
534
+ * today's code, which is the one thing it exists not to do.
535
+ */
536
+ transformRevisions: (id: string) => readonly ["nestjs-catalog", "pipeline", "transforms", string, "revisions"];
481
537
  runs: (connectorId?: string) => readonly ["nestjs-catalog", "pipeline", "runs", string];
482
538
  workflows: readonly ["nestjs-catalog", "pipeline", "workflows"];
483
539
  /**
package/dist/context.js CHANGED
@@ -32,6 +32,7 @@ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE
32
32
  updateSavedQuery: (id, input) => transport.patch(catalogRoutes.savedQuery(id), input),
33
33
  deleteSavedQuery: (id) => transport.delete(catalogRoutes.savedQuery(id)),
34
34
  runSavedQuery: (id) => transport.post(catalogRoutes.runSavedQuery(id), {}),
35
+ listSavedQueryRevisions: (id) => transport.get(catalogRoutes.savedQueryRevisions(id)),
35
36
  // A URL rather than a fetch: an export the browser downloads itself can
36
37
  // be a link, and a link can be copied, bookmarked or scheduled. Where
37
38
  // that link points is the transport's answer, exactly like every other
@@ -76,6 +77,7 @@ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE
76
77
  listTransforms: () => transport.get(pipeline.transforms()),
77
78
  saveTransform: (input) => transport.post(pipeline.transforms(), input),
78
79
  deleteTransform: (id) => transport.delete(pipeline.transform(id)),
80
+ listTransformRevisions: (id) => transport.get(pipeline.transformRevisions(id)),
79
81
  tryTransform: (input) => transport.post(pipeline.tryTransform(), input),
80
82
  listWorkflows: () => transport.get(pipeline.workflows()),
81
83
  saveWorkflow: (input) => transport.post(pipeline.workflows(), input),
@@ -125,6 +127,16 @@ export const catalogQueryKeys = {
125
127
  connections: ['nestjs-catalog', 'pipeline', 'connections'],
126
128
  connectors: ['nestjs-catalog', 'pipeline', 'connectors'],
127
129
  transforms: ['nestjs-catalog', 'pipeline', 'transforms'],
130
+ /**
131
+ * A transform's history, keyed UNDER `transforms` on purpose.
132
+ *
133
+ * `catalogQueryKeys.transforms` is a prefix of this, so the invalidation the
134
+ * transform list already performs after a save reaches the history too — and
135
+ * it must, because saving new code is precisely what cuts a revision. Keyed
136
+ * anywhere else, the diff screen would keep showing yesterday's history beside
137
+ * today's code, which is the one thing it exists not to do.
138
+ */
139
+ transformRevisions: (id) => ['nestjs-catalog', 'pipeline', 'transforms', id, 'revisions'],
128
140
  runs: (connectorId) => ['nestjs-catalog', 'pipeline', 'runs', connectorId ?? 'all'],
129
141
  workflows: ['nestjs-catalog', 'pipeline', 'workflows'],
130
142
  /**
@@ -0,0 +1,63 @@
1
+ import { type DiffLine, type DiffSection } from './line-diff';
2
+ /** Which of the two editable things in this catalog is being compared. */
3
+ export type RevisionSubjectKind = 'transform' | 'saved-query';
4
+ export interface RevisionSubject {
5
+ kind: RevisionSubjectKind;
6
+ id: string;
7
+ /** For the heading. A history sheet titled by an id helps nobody. */
8
+ name: string;
9
+ }
10
+ export interface RevisionHistoryProps {
11
+ subject: RevisionSubject;
12
+ /**
13
+ * What is live right now, from the row the caller is already holding.
14
+ *
15
+ * Every entry point has it — the transform editor has the transform, the
16
+ * connector card has it too, and the saved-query panel has the query — so
17
+ * asking for it costs nobody a request, and without it this screen cannot
18
+ * tell a history that is complete from one that stops short of the code
19
+ * running in production.
20
+ */
21
+ current?: {
22
+ version: number;
23
+ body: string;
24
+ } | undefined;
25
+ /**
26
+ * The version a connector run recorded, pinned on the left.
27
+ *
28
+ * The whole reason the runs list is an entry point. Given one, this opens on
29
+ * "what changed between the code that produced that load and the code that
30
+ * would produce one now" without anybody choosing anything from a dropdown.
31
+ */
32
+ ranVersion?: number | undefined;
33
+ }
34
+ export declare function RevisionHistory({ subject, current, ranVersion }: RevisionHistoryProps): import("react/jsx-runtime").JSX.Element;
35
+ export declare function DiffBody({ before, after }: {
36
+ before: string;
37
+ after: string;
38
+ }): import("react/jsx-runtime").JSX.Element;
39
+ export interface RevisionHistorySheetProps extends RevisionHistoryProps {
40
+ open: boolean;
41
+ onOpenChange: (open: boolean) => void;
42
+ }
43
+ /**
44
+ * The history, in the panel every entry point opens it in.
45
+ *
46
+ * A `Sheet` rather than a route or a full-screen view, for the reason the sheet
47
+ * was built: the screen underneath — a half-edited transform, a connector list
48
+ * scrolled to the run somebody was reading — stays mounted, so closing this puts
49
+ * them back exactly where the question occurred to them rather than at the top
50
+ * of a list. `wide`, because a diff at 24rem wraps every line and stops being a
51
+ * diff.
52
+ */
53
+ export declare function RevisionHistorySheet({ open, onOpenChange, ...props }: RevisionHistorySheetProps): import("react/jsx-runtime").JSX.Element;
54
+ /**
55
+ * The control that opens it, so the three entry points cannot drift into three
56
+ * different affordances for one thing.
57
+ */
58
+ export declare function RevisionHistoryButton({ label, onClick, className, }: {
59
+ label?: string;
60
+ onClick: () => void;
61
+ className?: string;
62
+ }): import("react/jsx-runtime").JSX.Element;
63
+ export type { DiffLine, DiffSection };
@@ -0,0 +1,279 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { CATALOG_REVISION_LIMIT } from '@dudousxd/nestjs-catalog/client';
3
+ import { useQuery } from '@tanstack/react-query';
4
+ import { GitCompare, History } from 'lucide-react';
5
+ import { useMemo, useState } from 'react';
6
+ import { cn } from '../cn';
7
+ import { catalogQueryKeys, useCatalogClient } from '../context';
8
+ import { Button } from '../ui/button';
9
+ import { SelectField } from '../ui/select';
10
+ import { Sheet } from '../ui/sheet';
11
+ import { diffLines, foldUnchanged } from './line-diff';
12
+ /**
13
+ * Why a load came out different from the last one.
14
+ *
15
+ * THE QUESTION THIS SCREEN ANSWERS
16
+ * --------------------------------
17
+ * Not "show me two texts". A connector run records `transformVersion` and the
18
+ * runs list renders it as `code v3`, so somebody looking at a surprising load
19
+ * already has a version number in front of them — and until now that number
20
+ * named code that existed nowhere, because `CatalogTransform.version` counts
21
+ * saves of a row that is overwritten in place. The valuable comparison is
22
+ * therefore the version that RAN against the version that is CURRENT, reached
23
+ * from the run where the question occurs to somebody, and that is what
24
+ * {@link RevisionHistory} opens on by default. The two selects are the fallback
25
+ * for the other question, not the way in.
26
+ *
27
+ * WHAT IS HONEST ABOUT AN EMPTY HISTORY
28
+ * -------------------------------------
29
+ * Every transform and saved query that predates revisions may have one recorded
30
+ * version or none, depending on what the store decided about backfill. Three
31
+ * different nothings live in here and they are rendered as three different
32
+ * things, because collapsing any pair of them tells somebody a lie about their
33
+ * own code:
34
+ *
35
+ * - **Nothing recorded.** There is no history. It is NOT a claim that nothing
36
+ * changed — the changes happened, they were simply not kept.
37
+ * - **One version recorded.** There is history and there is nothing before it to
38
+ * compare against. Also not a claim that nothing changed.
39
+ * - **Two versions that are byte-identical.** THIS is the one that means nothing
40
+ * changed, and it is the only one that gets to say so.
41
+ *
42
+ * And a fourth, which the run entry point can produce on its own: a run naming a
43
+ * version the recorded history does not contain. That is said out loud with the
44
+ * number in it, because it is the difference between "the code that ran is not
45
+ * here" and "the code that ran is the code you are looking at".
46
+ */
47
+ const MUTED = 'text-zinc-400 dark:text-zinc-500';
48
+ const RULE = 'border-zinc-200 dark:border-zinc-800';
49
+ const PANEL = 'bg-white dark:bg-zinc-900';
50
+ /**
51
+ * How many diff rows are painted before the rest go behind a control.
52
+ *
53
+ * The same number `QueryConsole` caps a result set at, and for the same reason:
54
+ * past a few hundred rows a browser is painting a wall nobody reads, and the
55
+ * screen appears frozen — which is its own kind of dishonesty about what is
56
+ * happening. The remaining rows are one click away and the control says how many
57
+ * there are.
58
+ *
59
+ * WHY THIS IS NOT `capLines`, and it is worth being precise. `capLines` in the
60
+ * pipeline package bounds both axes — lines AND characters within a line — of
61
+ * text on its way into a durable checkpoint and a run row, because an unbounded
62
+ * string there makes the size of a write a property of somebody's source data.
63
+ * Neither half of that argument reaches here. The bodies have already been
64
+ * fetched whole, so nothing is saved by rendering fewer, and — this is the part
65
+ * that matters — a character cap would be actively WRONG: two lines that differ
66
+ * only past the cap would be truncated into equality and the diff would report
67
+ * them as unchanged. A diff view must never compare anything but the whole line.
68
+ * So long lines wrap, exactly as they do in the code editor, and the only cap is
69
+ * on rows.
70
+ */
71
+ const DIFF_MAX_ROWS = 500;
72
+ export function RevisionHistory({ subject, current, ranVersion }) {
73
+ const client = useCatalogClient();
74
+ const revisions = useQuery({
75
+ queryKey: subject.kind === 'transform'
76
+ ? catalogQueryKeys.transformRevisions(subject.id)
77
+ : savedQueryRevisionKey(subject.id),
78
+ queryFn: () => subject.kind === 'transform'
79
+ ? client.listTransformRevisions(subject.id)
80
+ : client.listSavedQueryRevisions(subject.id),
81
+ });
82
+ const sides = useMemo(() => sidesFrom(revisions.data ?? [], current), [revisions.data, current]);
83
+ /**
84
+ * Which two are on screen, as VERSION NUMBERS rather than indices.
85
+ *
86
+ * `null` means "whatever the default is", so a background refetch that adds a
87
+ * newer revision moves the right-hand side onto it — which is what somebody
88
+ * who has not touched the selects expects. Storing an index instead would
89
+ * silently repoint both sides at different versions when the list grew, and an
90
+ * index is not a thing anybody chose.
91
+ */
92
+ const [leftVersion, setLeftVersion] = useState(null);
93
+ const [rightVersion, setRightVersion] = useState(null);
94
+ const right = pick(sides, rightVersion) ?? sides[0];
95
+ const left = pick(sides, leftVersion) ?? pick(sides, ranVersion ?? null) ?? sides[1];
96
+ if (revisions.isPending) {
97
+ return _jsx(Notice, { children: "Reading the history\u2026" });
98
+ }
99
+ if (revisions.isError) {
100
+ return (_jsxs(Notice, { tone: "bad", children: [revisions.error instanceof Error ? revisions.error.message : 'Could not read the history.', _jsx("div", { className: "mt-2", children: _jsx(Button, { variant: "outline", size: "sm", onClick: () => revisions.refetch(), children: "Try again" }) })] }));
101
+ }
102
+ if (sides.length === 0) {
103
+ return _jsx(NoHistory, { subject: subject });
104
+ }
105
+ if (sides.length === 1 || !left || !right) {
106
+ return _jsx(OnlyOneVersion, { subject: subject, only: sides[0] });
107
+ }
108
+ return (_jsxs("div", { className: "space-y-3", children: [ranVersion !== undefined && !sides.some((side) => side.version === ranVersion) && (_jsxs(Notice, { tone: "warn", children: ["This load ran ", _jsxs("span", { className: "font-mono", children: ["v", ranVersion] }), ", which the recorded history does not contain \u2014 it predates this catalog keeping revisions, or it has been pushed out by the ", CATALOG_REVISION_LIMIT, " newer ones that are kept. Nothing below is the", ' ', body(subject.kind), " that produced that load."] })), _jsxs("div", { className: "flex flex-wrap items-end gap-2", children: [_jsx(SidePicker, { label: "Compare", ariaLabel: "Compare version", sides: sides, value: left.version, onChange: setLeftVersion }), _jsx("span", { className: cn('pb-1.5 font-mono text-[11px]', MUTED), children: "\u2192" }), _jsx(SidePicker, { label: "Against", ariaLabel: "Against version", sides: sides, value: right.version, onChange: setRightVersion })] }), _jsx(Authorship, { left: left, right: right }), _jsx(DiffBody, { before: left.body, after: right.body })] }));
109
+ }
110
+ /**
111
+ * The saved-query history key, which lives on the OTHER prefix.
112
+ *
113
+ * `savedQueryKeys.all` is `['catalog', 'saved-queries']` while everything in
114
+ * `catalogQueryKeys` is under `['nestjs-catalog', …]`. That split predates this
115
+ * screen and is not worth changing from here — what matters is that a query's
116
+ * history sits UNDER the key its list already uses, so the invalidation the save
117
+ * form already performs reaches the history too. Saving new SQL is exactly what
118
+ * cuts a revision, and a history that lagged its own subject would be showing
119
+ * yesterday's answer to today's question.
120
+ */
121
+ function savedQueryRevisionKey(id) {
122
+ return ['catalog', 'saved-queries', id, 'revisions'];
123
+ }
124
+ /**
125
+ * The recorded versions, newest first, with the live row folded in when it is
126
+ * ahead of all of them.
127
+ *
128
+ * Sorted here rather than trusted from the route. The contract says newest
129
+ * first and the bundled store will honour it; a store somebody else wrote might
130
+ * not, and a diff screen that put v2 on the right and v7 on the left would show
131
+ * every addition as a deletion — a comparison that is exactly backwards and
132
+ * looks entirely plausible.
133
+ */
134
+ function sidesFrom(revisions, current) {
135
+ const sides = revisions
136
+ .map((revision) => ({
137
+ version: revision.version,
138
+ body: revision.body,
139
+ authoredBy: revision.authoredBy,
140
+ authoredAt: revision.authoredAt,
141
+ live: false,
142
+ }))
143
+ .sort((a, b) => b.version - a.version);
144
+ if (current && !sides.some((side) => side.version === current.version)) {
145
+ sides.unshift({
146
+ version: current.version,
147
+ body: current.body,
148
+ authoredBy: null,
149
+ authoredAt: null,
150
+ live: true,
151
+ });
152
+ }
153
+ return sides;
154
+ }
155
+ function pick(sides, version) {
156
+ if (version === null)
157
+ return undefined;
158
+ return sides.find((side) => side.version === version);
159
+ }
160
+ function SidePicker({ label, ariaLabel, sides, value, onChange, }) {
161
+ return (_jsx(SelectField, { label: label, ariaLabel: ariaLabel, value: String(value),
162
+ // The select speaks strings and versions are numbers, so the parse happens
163
+ // here rather than anywhere a type assertion could hide it. A value that
164
+ // did not come from the options below cannot arrive, and if one somehow
165
+ // did, `Number` would produce NaN, `pick` would find nothing, and the
166
+ // default comparison would stand — rather than a blank panel.
167
+ onValueChange: (next) => onChange(Number(next)), className: "min-w-[10rem]", options: sides.map((side) => ({
168
+ value: String(side.version),
169
+ label: `v${side.version}`,
170
+ hint: side.live ? 'current, not yet recorded' : (side.authoredBy ?? undefined),
171
+ })) }));
172
+ }
173
+ /** Who wrote each side and when, which is half of what "why did this change" means. */
174
+ function Authorship({ left, right }) {
175
+ return (_jsxs("p", { className: cn('font-mono text-[10px] leading-relaxed', MUTED), children: ["v", left.version, " ", describeAuthor(left), " \u2192 v", right.version, " ", describeAuthor(right)] }));
176
+ }
177
+ function describeAuthor(side) {
178
+ if (side.live)
179
+ return '(current)';
180
+ const who = side.authoredBy ?? 'unknown';
181
+ // The locale's own format. A console rendering an ISO string at somebody is
182
+ // making them do arithmetic about their own timezone.
183
+ const when = side.authoredAt ? new Date(side.authoredAt).toLocaleString() : 'unknown date';
184
+ return `by ${who}, ${when}`;
185
+ }
186
+ export function DiffBody({ before, after }) {
187
+ const diff = useMemo(() => diffLines(before, after), [before, after]);
188
+ const sections = useMemo(() => foldUnchanged(diff.lines), [diff.lines]);
189
+ const [expanded, setExpanded] = useState(() => new Set());
190
+ const [showAllRows, setShowAllRows] = useState(false);
191
+ const rows = useMemo(() => sections.flatMap((section, index) => section.kind === 'shown' || expanded.has(index)
192
+ ? section.lines.map((line) => ({ kind: 'line', line }))
193
+ : [{ kind: 'fold', index, count: section.lines.length }]), [sections, expanded]);
194
+ const visible = showAllRows ? rows : rows.slice(0, DIFF_MAX_ROWS);
195
+ const withheld = rows.length - visible.length;
196
+ return (_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsxs("div", { className: cn('flex items-center gap-3 border-b px-3 py-1.5', RULE), children: [_jsx(GitCompare, { size: 11, className: MUTED }), diff.identical ? (
197
+ // The ONLY state that gets to say nothing changed, and it earns it:
198
+ // the two bodies are byte-for-byte the same. See this file's header
199
+ // for the three other nothings that must not borrow this sentence.
200
+ _jsx("span", { className: "font-mono text-[10px] text-zinc-500 dark:text-zinc-400", children: "These two versions are identical." })) : (_jsxs("span", { className: "font-mono text-[10px]", children: [_jsxs("span", { className: "text-emerald-600", children: ["+", diff.added] }), ' ', _jsxs("span", { className: "text-red-600", children: ["\u2212", diff.removed] })] }))] }), diff.alignment === 'coarse' && (_jsx("p", { className: "border-b border-amber-200 bg-amber-50/70 px-3 py-1.5 text-[11px] text-amber-800 dark:border-amber-900 dark:bg-amber-950/25 dark:text-amber-300", children: "These two versions are too far apart to line up line by line, so the whole changed region is shown as removed and re-added. Nothing below is wrong; it is blunter than usual." })), _jsx("div", { className: "overflow-x-auto", children: visible.map((row) => row.kind === 'fold' ? (_jsx(FoldRow, { count: row.count, onExpand: () => setExpanded((current) => new Set(current).add(row.index)) }, `fold-${row.index}`)) : (_jsx(DiffRow, { line: row.line }, rowKey(row.line)))) }), withheld > 0 && (_jsx("div", { className: cn('border-t px-3 py-2', RULE), children: _jsxs(Button, { variant: "outline", size: "sm", onClick: () => setShowAllRows(true), children: ["Show the remaining ", withheld, " lines"] }) }))] }));
201
+ }
202
+ /**
203
+ * A stable key for a diff row, out of the numbering it already carries.
204
+ *
205
+ * Not the array index, which is what this looked like first. A row's pair of
206
+ * line numbers is unique across the whole comparison and does not move when a
207
+ * fold above it opens: two removed lines have different `before`, two added
208
+ * lines have different `after`, and an unchanged line has both. An index key
209
+ * would renumber every row below an expanded fold, so React would reconcile
210
+ * hundreds of rows that did not change.
211
+ */
212
+ function rowKey(line) {
213
+ return `${line.before ?? '-'}:${line.after ?? '-'}`;
214
+ }
215
+ /**
216
+ * One line.
217
+ *
218
+ * The `+`/`−`/space gutter is not decoration and it is not a duplicate of the
219
+ * colour: it is the only marker that survives a colourblind reader, a printout,
220
+ * a high-contrast theme and a screen reader, all of which the background tint
221
+ * does not. Diffs have been read this way for forty years, so it is also the
222
+ * marker nobody has to learn.
223
+ *
224
+ * `whitespace-pre-wrap break-words` matches the code editor exactly, which is
225
+ * what lets a four-hundred-character line be READ rather than truncated. See
226
+ * `DIFF_MAX_ROWS` for why truncating a line here would make the comparison lie.
227
+ */
228
+ function DiffRow({ line }) {
229
+ return (_jsxs("div", { className: cn('flex items-start gap-2 px-2 font-mono text-[11px] leading-[1.5]', line.op === 'added' && 'bg-emerald-50 dark:bg-emerald-950/30', line.op === 'removed' && 'bg-red-50 dark:bg-red-950/30'), children: [_jsx("span", { className: cn('w-8 shrink-0 select-none text-right', MUTED), children: line.before ?? '' }), _jsx("span", { className: cn('w-8 shrink-0 select-none text-right', MUTED), children: line.after ?? '' }), _jsx("span", { className: cn('w-3 shrink-0 select-none', line.op === 'added' && 'text-emerald-600', line.op === 'removed' && 'text-red-600'), children: line.op === 'added' ? '+' : line.op === 'removed' ? '−' : ' ' }), _jsx("span", { className: "min-w-0 whitespace-pre-wrap break-words", children: line.text })] }));
230
+ }
231
+ /** A collapsed run of unchanged lines, and the way to see it anyway. */
232
+ function FoldRow({ count, onExpand }) {
233
+ return (_jsx("div", { className: cn('border-y bg-zinc-50/60 px-2 py-0.5 dark:bg-zinc-800/30', RULE), children: _jsxs(Button, { variant: "ghost", size: "sm", onClick: onExpand, className: "font-mono text-[10px] font-normal", children: ["\u22EF ", count, " unchanged ", count === 1 ? 'line' : 'lines'] }) }));
234
+ }
235
+ function Notice({ children, tone = 'plain', }) {
236
+ return (_jsx("div", { className: cn('rounded-lg border px-3 py-2 text-[11px] leading-relaxed', tone === 'plain' && cn(RULE, MUTED), tone === 'warn' &&
237
+ 'border-amber-200 bg-amber-50/70 text-amber-800 dark:border-amber-900 dark:bg-amber-950/25 dark:text-amber-300', tone === 'bad' &&
238
+ 'border-red-200 bg-red-50 text-red-700 dark:border-red-900 dark:bg-red-950/40 dark:text-red-300'), children: children }));
239
+ }
240
+ /** The word for the thing, so the empty states can be written once. */
241
+ function noun(kind) {
242
+ return kind === 'transform' ? 'transform' : 'saved query';
243
+ }
244
+ function body(kind) {
245
+ return kind === 'transform' ? 'code' : 'SQL';
246
+ }
247
+ /**
248
+ * Nothing recorded — and the second sentence is the entire point of this
249
+ * component existing separately from the one below it.
250
+ */
251
+ function NoHistory({ subject }) {
252
+ return (_jsxs("div", { className: cn('rounded-lg border border-dashed px-4 py-8 text-center text-sm', RULE, MUTED), children: [_jsx(History, { size: 16, className: "mx-auto mb-2", "aria-hidden": true }), _jsxs("p", { children: ["No history is recorded for ", _jsx("span", { className: "font-medium", children: subject.name }), "."] }), _jsxs("p", { className: "mx-auto mt-2 max-w-md text-[11px] leading-relaxed", children: ["That is not the same as saying nothing has changed. This ", noun(subject.kind), " was last edited before this catalog kept revisions, so the earlier ", body(subject.kind), " was overwritten and there is nothing left to compare against. The next save is recorded, and the", ' ', CATALOG_REVISION_LIMIT, " most recent are kept from then on."] })] }));
253
+ }
254
+ /** One version recorded. Also not a claim that nothing changed. */
255
+ function OnlyOneVersion({ subject, only }) {
256
+ return (_jsxs("div", { className: cn('rounded-lg border border-dashed px-4 py-8 text-center text-sm', RULE, MUTED), children: [_jsx(History, { size: 16, className: "mx-auto mb-2", "aria-hidden": true }), _jsxs("p", { children: ["One version of ", _jsx("span", { className: "font-medium", children: subject.name }), " is recorded", only ? _jsxs("span", { className: "font-mono", children: [" (v", only.version, ")"] }) : null, ", so there is nothing before it to compare against."] }), _jsxs("p", { className: "mx-auto mt-2 max-w-md text-[11px] leading-relaxed", children: ["Any earlier ", body(subject.kind), " was overwritten before this catalog kept revisions \u2014 again, not a statement that it never changed. The next save gives this screen two versions to work with; the ", CATALOG_REVISION_LIMIT, " most recent are kept."] })] }));
257
+ }
258
+ /**
259
+ * The history, in the panel every entry point opens it in.
260
+ *
261
+ * A `Sheet` rather than a route or a full-screen view, for the reason the sheet
262
+ * was built: the screen underneath — a half-edited transform, a connector list
263
+ * scrolled to the run somebody was reading — stays mounted, so closing this puts
264
+ * them back exactly where the question occurred to them rather than at the top
265
+ * of a list. `wide`, because a diff at 24rem wraps every line and stops being a
266
+ * diff.
267
+ */
268
+ export function RevisionHistorySheet({ open, onOpenChange, ...props }) {
269
+ return (_jsx(Sheet, { open: open, onOpenChange: onOpenChange, title: `History · ${props.subject.name}`, width: "wide", description: props.ranVersion === undefined
270
+ ? 'Every version saved, newest first.'
271
+ : `What changed between the ${body(props.subject.kind)} that ran and what would run now.`, children: open && _jsx(RevisionHistory, { ...props }) }));
272
+ }
273
+ /**
274
+ * The control that opens it, so the three entry points cannot drift into three
275
+ * different affordances for one thing.
276
+ */
277
+ export function RevisionHistoryButton({ label = 'History', onClick, className, }) {
278
+ return (_jsxs(Button, { variant: "outline", size: "sm", onClick: onClick, className: className, children: [_jsx(History, { size: 12 }), label] }));
279
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Two texts, lined up, computed in this file and nowhere else.
3
+ *
4
+ * WHY THIS IS HAND-ROLLED
5
+ * -----------------------
6
+ * The two strings this console ever diffs are a transform's code and a saved
7
+ * query's SQL. Those are the most sensitive strings in the product: a transform
8
+ * is executable code with the catalog's own database reachable from it, and a
9
+ * saved query is somebody's SQL against military logistics data — the column
10
+ * names alone describe a fleet. A diff library is a dependency that gets to see
11
+ * both, on every render, and "it only renders locally" is a property of the
12
+ * version you audited rather than of the package. There is no version of this
13
+ * feature worth a supply-chain question mark on that content, so there is no
14
+ * dependency here at all: `diffLines` is forty lines of dynamic programming with
15
+ * no imports, and the whole of what it can do is visible on this screen.
16
+ *
17
+ * It is also the cheaper answer. This package already declines dependencies it
18
+ * could plausibly justify — `charts/css.tsx` draws bars with divs, `ui/button.tsx`
19
+ * hand-rolls what `class-variance-authority` would compile to, and `export/pdf.ts`
20
+ * is a seam rather than a renderer — for the same reason each time: every
21
+ * consumer pays for it whether or not they render this screen.
22
+ *
23
+ * WHAT IT DOES NOT DO
24
+ * -------------------
25
+ * No word- or character-level diff inside a changed line, and no move detection.
26
+ * A changed line is reported as a removal and an addition, which is what a
27
+ * unified diff has always done and what the renderer colours. Both are real
28
+ * improvements somebody could make; neither is the question this screen exists
29
+ * to answer, which is "which lines are different between the version that ran
30
+ * and the version that is current".
31
+ */
32
+ /**
33
+ * The largest DP table this will build, in cells.
34
+ *
35
+ * The comparison is O(n·m) in the CHANGED region only — the common prefix and
36
+ * suffix are trimmed first, so the ordinary case (somebody edited four lines of
37
+ * a three-hundred-line transform) is a handful of cells regardless of file size.
38
+ * This bound exists for the case that survives the trim: two bodies that share
39
+ * almost nothing, which is what a rewrite looks like.
40
+ *
41
+ * 1.5M cells is a `Uint32Array` of 6MB and roughly a 1,200×1,200 changed region.
42
+ * Past that the table costs more memory than the browser tab should spend on a
43
+ * comparison nobody could read anyway, so {@link diffLines} stops computing and
44
+ * SAYS it stopped — see `alignment`. A silent fallback would be the same failure
45
+ * `capLines` names one package over: a truncation nobody is told about.
46
+ */
47
+ export declare const DIFF_MAX_CELLS = 1500000;
48
+ /** What happened to one line between the two bodies. */
49
+ export type DiffOp = 'same' | 'added' | 'removed';
50
+ export interface DiffLine {
51
+ op: DiffOp;
52
+ /** 1-based line number in the earlier body. Null on an added line. */
53
+ before: number | null;
54
+ /** 1-based line number in the later body. Null on a removed line. */
55
+ after: number | null;
56
+ text: string;
57
+ }
58
+ export interface LineDiff {
59
+ lines: DiffLine[];
60
+ added: number;
61
+ removed: number;
62
+ /**
63
+ * The two bodies are byte-for-byte the same.
64
+ *
65
+ * A separate field rather than `added === 0 && removed === 0`, because the
66
+ * caller has to distinguish "these two versions are identical" from "there is
67
+ * no second version to compare against", and only one of those is a statement
68
+ * about the texts. See `RevisionDiff`, where conflating them is the exact
69
+ * thing the empty states are written to avoid.
70
+ */
71
+ identical: boolean;
72
+ /**
73
+ * How the lines were matched up.
74
+ *
75
+ * `exact` means every line was lined up against its counterpart. `coarse`
76
+ * means the changed region was past {@link DIFF_MAX_CELLS} and the whole of it
77
+ * is reported as removed-then-added — true, but blunter than it could be, and
78
+ * the screen says so rather than letting somebody read "everything changed" as
79
+ * a finding about their code.
80
+ */
81
+ alignment: 'exact' | 'coarse';
82
+ }
83
+ /**
84
+ * Line up two bodies.
85
+ *
86
+ * `before` is the earlier version, `after` the later one. The order matters to
87
+ * the reading and not to the algorithm: swapping them turns every addition into
88
+ * a removal, which is why the caller that pins "the version that ran" on the
89
+ * left is the one that gets a screen answering "what changed since".
90
+ */
91
+ export declare function diffLines(before: string, after: string): LineDiff;
92
+ /** Lines to keep either side of a change before folding the rest away. */
93
+ export declare const DIFF_CONTEXT_LINES = 3;
94
+ /**
95
+ * The smallest run worth putting a button on.
96
+ *
97
+ * Folding two lines behind a control that says "2 unchanged lines" costs a row
98
+ * to save two, and it costs a click. Below this the run is simply shown.
99
+ */
100
+ export declare const DIFF_MIN_FOLD = 4;
101
+ export type DiffSection = {
102
+ kind: 'shown';
103
+ lines: DiffLine[];
104
+ } | {
105
+ kind: 'folded';
106
+ lines: DiffLine[];
107
+ };
108
+ /**
109
+ * Collapse the long unchanged stretches, keeping context around every change.
110
+ *
111
+ * A transform can be hundreds of lines and the answer to "why did Tuesday's load
112
+ * differ from Monday's" is almost never more than a handful of them. Rendering
113
+ * all of it puts the four lines that matter somewhere in the middle of a wall
114
+ * and makes the reader scroll for them.
115
+ *
116
+ * Folded rather than dropped, and the sections carry their lines rather than a
117
+ * count, so the renderer can expand one in place. A diff that hides code with no
118
+ * way to see it is a diff you cannot trust, and this is code somebody is about
119
+ * to make a decision about.
120
+ *
121
+ * A run at the very start or end of the file gets no context on that side —
122
+ * there is no change up there to be in the context of.
123
+ */
124
+ export declare function foldUnchanged(lines: DiffLine[], context?: number, minFold?: number): DiffSection[];