@dudousxd/nestjs-catalog-react 0.14.0 → 0.16.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.
@@ -5,6 +5,7 @@ import { ArrowLeft, Play } from 'lucide-react';
5
5
  import { useRef, useState } from 'react';
6
6
  import { cn } from './cn';
7
7
  import { useCatalogClient } from './context';
8
+ import { RevisionHistoryButton, RevisionHistorySheet } from './diff/RevisionDiff';
8
9
  import { CodeEditor } from './ui/code-editor';
9
10
  import { TextField } from './ui/field';
10
11
  import { SelectField } from './ui/select';
@@ -89,6 +90,7 @@ export function TransformEditor({ transform, languages, pythonPackages = [], onC
89
90
  const [language, setLanguage] = useState(transform?.language ?? languages[0] ?? 'javascript');
90
91
  const [code, setCode] = useState(transform?.code ?? STARTERS[transform?.language ?? 'javascript']);
91
92
  const [sample, setSample] = useState(SAMPLE);
93
+ const [historyOpen, setHistoryOpen] = useState(false);
92
94
  const editorRef = useRef(null);
93
95
  const tryIt = useMutation({
94
96
  mutationFn: () => {
@@ -138,5 +140,10 @@ export function TransformEditor({ transform, languages, pythonPackages = [], onC
138
140
  label: option,
139
141
  })) })] }), _jsxs("div", { className: "grid gap-3 lg:grid-cols-2", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsxs("div", { className: cn('flex items-center justify-between border-b px-3 py-1.5', RULE), children: [_jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Code" }), _jsx("span", { className: cn('font-mono text-[10px]', MUTED), children: language === 'python' && pythonPackages.length > 0
140
142
  ? `imports: ${pythonPackages.join(', ')}`
141
- : '⌘↵ to try' })] }), _jsx(CodeEditor, { value: code, onChange: setCode, onKeyDown: onKeyDown, language: language === 'python' ? 'python' : 'tsx', label: "Transform code", textareaRef: editorRef, className: "h-72" })] }), _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Sample records" }) }), _jsx(CodeEditor, { value: sample, onChange: setSample, language: "json", label: "Sample records", className: "h-32" })] }), _jsxs("button", { type: "button", onClick: () => tryIt.mutate(), disabled: tryIt.isPending, className: "flex items-center gap-1.5 rounded-md bg-zinc-950 px-3 py-1.5 text-xs text-zinc-50 disabled:opacity-40 dark:bg-zinc-100 dark:text-zinc-950", children: [_jsx(Play, { size: 12 }), tryIt.isPending ? 'Running…' : 'Try it'] }), _jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Output" }) }), _jsx(TryOutput, { result: tryIt.data, error: tryIt.error })] })] })] }), _jsx(SaveBar, { transform: transform, nameIsEmpty: name.trim().length === 0, pending: save.isPending, error: save.error, onSave: () => save.mutate() })] }));
143
+ : '⌘↵ to try' })] }), _jsx(CodeEditor, { value: code, onChange: setCode, onKeyDown: onKeyDown, language: language === 'python' ? 'python' : 'tsx', label: "Transform code", textareaRef: editorRef, className: "h-72" })] }), _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Sample records" }) }), _jsx(CodeEditor, { value: sample, onChange: setSample, language: "json", label: "Sample records", className: "h-32" })] }), _jsxs("button", { type: "button", onClick: () => tryIt.mutate(), disabled: tryIt.isPending, className: "flex items-center gap-1.5 rounded-md bg-zinc-950 px-3 py-1.5 text-xs text-zinc-50 disabled:opacity-40 dark:bg-zinc-100 dark:text-zinc-950", children: [_jsx(Play, { size: 12 }), tryIt.isPending ? 'Running…' : 'Try it'] }), _jsxs("div", { className: cn('overflow-hidden rounded-lg border', RULE, PANEL), children: [_jsx("div", { className: cn('border-b px-3 py-1.5', RULE), children: _jsx("span", { className: cn('font-mono text-[10px] uppercase tracking-[0.14em]', MUTED), children: "Output" }) }), _jsx(TryOutput, { result: tryIt.data, error: tryIt.error })] })] })] }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx(SaveBar, { transform: transform, nameIsEmpty: name.trim().length === 0, pending: save.isPending, error: save.error, onSave: () => save.mutate() }), transform && (_jsx(RevisionHistoryButton, { className: "ml-auto", onClick: () => setHistoryOpen(true) }))] }), transform && (_jsx(RevisionHistorySheet, { open: historyOpen, onOpenChange: setHistoryOpen, subject: { kind: 'transform', id: transform.id, name: transform.name },
144
+ // The SAVED code, not what is in the editor above. A history is what
145
+ // this catalog has recorded; comparing against an unsaved buffer would
146
+ // put a version number on text that exists only in one browser tab,
147
+ // and no run will ever have used it.
148
+ current: { version: transform.version, body: transform.code } }))] }));
142
149
  }
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, DeleteReconciliation, LoadExpectation, LoadExpectationInput, ObjectQueryParams, PropertyPatch, ResolvedLoadExpectation, RowCountBound, SaveQueryInput, SavedQuery, StoredLoadExpectation, 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';
@@ -77,6 +77,28 @@ export interface PipelineCapabilities {
77
77
  */
78
78
  durable?: WorkflowDurability;
79
79
  }
80
+ /**
81
+ * What a load has to be true of before it becomes the data everybody reads.
82
+ *
83
+ * RE-EXPORTED rather than mirrored, and the distinction is the same one
84
+ * {@link CatalogRevision} above turns on: {@link PipelineCapabilities} is
85
+ * mirrored because naming it would mean importing
86
+ * `@dudousxd/nestjs-catalog-pipeline`, a package built for a Node process with
87
+ * database drivers behind optional imports. These shapes have no such problem —
88
+ * they are plain declarations on `@dudousxd/nestjs-catalog/client`, the entry
89
+ * point that exists precisely so a browser can name the catalog's own
90
+ * contracts, and a second copy here is what would drift.
91
+ *
92
+ * Named from this module at all, rather than left for a host to import from the
93
+ * other package, for the reason the whole of this file is: everything else this
94
+ * client returns is reachable from here, and typing a variable should not
95
+ * require knowing which of the two packages declares which shape.
96
+ *
97
+ * The enforcement functions are deliberately NOT reachable from a browser.
98
+ * They decide whether a load commits, they live in the pipeline package, and a
99
+ * console running its own copy would be a second answer to a question with one.
100
+ */
101
+ export type { DeleteReconciliation, LoadExpectation, LoadExpectationInput, ResolvedLoadExpectation, RowCountBound, StoredLoadExpectation, };
80
102
  /**
81
103
  * What a caller may set on a connection.
82
104
  *
@@ -116,6 +138,25 @@ export interface TransformInput {
116
138
  language: TransformLanguage;
117
139
  code: string;
118
140
  }
141
+ /**
142
+ * One saved version of the two things in this catalog whose text a person edits.
143
+ *
144
+ * RE-EXPORTED rather than mirrored, unlike `PipelineCapabilities` above. The
145
+ * distinction is worth keeping straight: `PipelineCapabilities` is mirrored
146
+ * because importing it would mean importing `@dudousxd/nestjs-catalog-pipeline`,
147
+ * a package built for a Node process with database drivers behind optional
148
+ * imports, into a browser bundle. `CatalogRevision` has no such problem — it is
149
+ * a plain shape on `@dudousxd/nestjs-catalog/client`, the entry point that
150
+ * exists precisely so a browser can name the catalog's own contracts, and
151
+ * restating it here would be the second copy of something two packages already
152
+ * serve.
153
+ *
154
+ * Named here at all, rather than left for callers to import from the client
155
+ * package, because everything else this file's `CatalogClient` returns is
156
+ * reachable from this module and a host should not have to know which of the two
157
+ * packages owns which shape to type a variable.
158
+ */
159
+ export type { CatalogRevision };
119
160
  /** The three answers a console can give somebody about what they may do. */
120
161
  export type CatalogPersonRole = 'viewer' | 'curator' | 'admin';
121
162
  /**
@@ -252,6 +293,23 @@ export interface CatalogClient {
252
293
  result: CatalogQueryResult;
253
294
  }>;
254
295
  exportUrl(id: string): string;
296
+ /**
297
+ * Every SQL this saved query has ever been, newest first.
298
+ *
299
+ * Beside {@link listTransformRevisions} rather than one polymorphic
300
+ * `listRevisions(kind, id)`, because the two are served by different things:
301
+ * a saved query is the catalog library's own resource and a transform is the
302
+ * host's. One method taking a kind would hide that a host can move one of the
303
+ * two endpoints and not the other, which is exactly the mistake `routes.ts`
304
+ * spends its header preventing.
305
+ *
306
+ * An EMPTY list is a real answer and not an error. Every saved query written
307
+ * before revisions existed has no history, and whether the store backfills a
308
+ * first revision from the current SQL is a decision belonging to the store.
309
+ * The screen has to read "nothing recorded" as "nothing recorded" — never as
310
+ * "nothing has changed".
311
+ */
312
+ listSavedQueryRevisions(id: string): Promise<CatalogRevision[]>;
255
313
  listDashboards(): Promise<Dashboard[]>;
256
314
  /**
257
315
  * `shared` is declared on both writes, and it is not decoration.
@@ -373,11 +431,46 @@ export interface CatalogClient {
373
431
  */
374
432
  publishType(name: string, schema: unknown): Promise<unknown>;
375
433
  listRuns(connectorId?: string): Promise<ConnectorRun[]>;
434
+ /**
435
+ * What one type promises about deletes and row counts, resolved.
436
+ *
437
+ * Per type and never per connector: the three ways rows arrive — a
438
+ * connector, a workflow sink, an application POSTing to the publish API —
439
+ * end at the same two publish methods, so a per-connector answer would cover
440
+ * one of the three and leave one dataset with two answers to one question.
441
+ */
442
+ loadExpectation(typeName: string): Promise<ResolvedLoadExpectation>;
443
+ /**
444
+ * Store one, or replace what is stored.
445
+ *
446
+ * The answer is typed `unknown` and callers are expected to refetch. That is
447
+ * not laziness: what a screen has to show is the RESOLVED expectation, which
448
+ * is a merge of this write with whatever the host declared in code, and the
449
+ * merge is the server's to perform. A screen that wrote this response into
450
+ * its cache would be claiming the stored row is the one in force, which is
451
+ * exactly what {@link ResolvedLoadExpectation.hostLocked} exists to deny.
452
+ *
453
+ * Refuses by name when the transport cannot `PUT`, rather than resolving
454
+ * having done nothing — see {@link CatalogTransport.put}.
455
+ */
456
+ setLoadExpectation(typeName: string, input: LoadExpectationInput): Promise<unknown>;
457
+ /** Drop the stored row. Anything the host declared in code survives it. */
458
+ clearLoadExpectation(typeName: string): Promise<unknown>;
376
459
  listTransforms(): Promise<CatalogTransform[]>;
377
460
  saveTransform(input: TransformInput): Promise<CatalogTransform>;
378
461
  deleteTransform(id: string): Promise<{
379
462
  deleted: boolean;
380
463
  }>;
464
+ /**
465
+ * Every version of this transform's code, newest first.
466
+ *
467
+ * The list rather than one version by number, because the screen that needs
468
+ * this is comparing two of them and has to know which exist before it can pick
469
+ * — including the case where the version a run recorded is NOT among them,
470
+ * which is what a transform older than the revision store looks like and is a
471
+ * thing the screen has to be able to say out loud.
472
+ */
473
+ listTransformRevisions(id: string): Promise<CatalogRevision[]>;
381
474
  /**
382
475
  * Run code against sample records without storing anything.
383
476
  *
@@ -478,7 +571,27 @@ export declare const catalogQueryKeys: {
478
571
  connections: readonly ["nestjs-catalog", "pipeline", "connections"];
479
572
  connectors: readonly ["nestjs-catalog", "pipeline", "connectors"];
480
573
  transforms: readonly ["nestjs-catalog", "pipeline", "transforms"];
574
+ /**
575
+ * A transform's history, keyed UNDER `transforms` on purpose.
576
+ *
577
+ * `catalogQueryKeys.transforms` is a prefix of this, so the invalidation the
578
+ * transform list already performs after a save reaches the history too — and
579
+ * it must, because saving new code is precisely what cuts a revision. Keyed
580
+ * anywhere else, the diff screen would keep showing yesterday's history beside
581
+ * today's code, which is the one thing it exists not to do.
582
+ */
583
+ transformRevisions: (id: string) => readonly ["nestjs-catalog", "pipeline", "transforms", string, "revisions"];
481
584
  runs: (connectorId?: string) => readonly ["nestjs-catalog", "pipeline", "runs", string];
585
+ /**
586
+ * One type's resolved load expectation.
587
+ *
588
+ * Under the `pipeline` prefix rather than beside `snapshot`, even though the
589
+ * screen that reads it is the Model screen: the endpoint is served by the
590
+ * host's pipeline controller, not by the catalog library, so a host
591
+ * invalidating "everything the pipeline knows" has to reach this too. Keyed
592
+ * per type because that is the grain of the answer.
593
+ */
594
+ loadExpectation: (typeName: string) => readonly ["nestjs-catalog", "pipeline", "expectations", string];
482
595
  workflows: readonly ["nestjs-catalog", "pipeline", "workflows"];
483
596
  /**
484
597
  * The embed keys, under one prefix so a host can invalidate every embedded
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
@@ -73,9 +74,20 @@ export function CatalogProvider({ transport, pipelineBasePath = DEFAULT_PIPELINE
73
74
  // run" into "runs of the connector whose id is the empty string", which
74
75
  // is an empty list that looks like a system that has never run anything.
75
76
  listRuns: (connectorId) => transport.get(pipeline.runs(), connectorId ? { connector: connectorId } : undefined),
77
+ loadExpectation: (typeName) => transport.get(pipeline.loadExpectation(typeName)),
78
+ setLoadExpectation: (typeName, input) => {
79
+ if (!transport.put) {
80
+ throw new Error('This transport cannot PUT, so it cannot store a load expectation. Implement `put` ' +
81
+ 'on the transport you passed to CatalogProvider — storing one is an idempotent ' +
82
+ 'upsert of the whole per-type row, which is why the route is a PUT and not a POST.');
83
+ }
84
+ return transport.put(pipeline.loadExpectation(typeName), input);
85
+ },
86
+ clearLoadExpectation: (typeName) => transport.delete(pipeline.loadExpectation(typeName)),
76
87
  listTransforms: () => transport.get(pipeline.transforms()),
77
88
  saveTransform: (input) => transport.post(pipeline.transforms(), input),
78
89
  deleteTransform: (id) => transport.delete(pipeline.transform(id)),
90
+ listTransformRevisions: (id) => transport.get(pipeline.transformRevisions(id)),
79
91
  tryTransform: (input) => transport.post(pipeline.tryTransform(), input),
80
92
  listWorkflows: () => transport.get(pipeline.workflows()),
81
93
  saveWorkflow: (input) => transport.post(pipeline.workflows(), input),
@@ -125,7 +137,27 @@ export const catalogQueryKeys = {
125
137
  connections: ['nestjs-catalog', 'pipeline', 'connections'],
126
138
  connectors: ['nestjs-catalog', 'pipeline', 'connectors'],
127
139
  transforms: ['nestjs-catalog', 'pipeline', 'transforms'],
140
+ /**
141
+ * A transform's history, keyed UNDER `transforms` on purpose.
142
+ *
143
+ * `catalogQueryKeys.transforms` is a prefix of this, so the invalidation the
144
+ * transform list already performs after a save reaches the history too — and
145
+ * it must, because saving new code is precisely what cuts a revision. Keyed
146
+ * anywhere else, the diff screen would keep showing yesterday's history beside
147
+ * today's code, which is the one thing it exists not to do.
148
+ */
149
+ transformRevisions: (id) => ['nestjs-catalog', 'pipeline', 'transforms', id, 'revisions'],
128
150
  runs: (connectorId) => ['nestjs-catalog', 'pipeline', 'runs', connectorId ?? 'all'],
151
+ /**
152
+ * One type's resolved load expectation.
153
+ *
154
+ * Under the `pipeline` prefix rather than beside `snapshot`, even though the
155
+ * screen that reads it is the Model screen: the endpoint is served by the
156
+ * host's pipeline controller, not by the catalog library, so a host
157
+ * invalidating "everything the pipeline knows" has to reach this too. Keyed
158
+ * per type because that is the grain of the answer.
159
+ */
160
+ loadExpectation: (typeName) => ['nestjs-catalog', 'pipeline', 'expectations', typeName],
129
161
  workflows: ['nestjs-catalog', 'pipeline', 'workflows'],
130
162
  /**
131
163
  * The embed keys, under one prefix so a host can invalidate every embedded
@@ -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
+ }