@malloy-publisher/sdk 0.9.13 → 0.9.14

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.
@@ -4,14 +4,21 @@ import { SavesTo } from './documentSession';
4
4
  import { TextSourceOptions } from './ReportEditor';
5
5
  import { ReportEventHandler } from '../Report/telemetry';
6
6
  import { BuilderControlsHandler } from './builderControls';
7
- export declare function EditorSurface({ textSource, environmentName, packageName, modelPath, versionId, opened, replaces, onSave, onDirtyChange, onExit, onOpenModel, onControlsChange, draftKey, onEvent, savesTo, saveLabel, note, }: {
7
+ export declare function EditorSurface({ textSource, environmentName, packageName, modelPath, versionId, queryVersionId, opened, replaces, onSave, onDirtyChange, onExit, onOpenModel, onControlsChange, draftKey, onEvent, savesTo, saveLabel, note, }: {
8
8
  textSource?: TextSourceOptions;
9
9
  environmentName: string;
10
10
  packageName: string;
11
11
  modelPath: string;
12
12
  /** A display label; the editor keys on `modelPath`. */
13
13
  slug: string;
14
+ /** The document's version, from its `resourceUri`: what its control state is keyed by. */
14
15
  versionId?: string;
16
+ /**
17
+ * The package version every query runs at: tiles, the manifest, filter
18
+ * options, the listing and the catalog. `ReportEditor` passes its
19
+ * `queryVersionId`, or the document's own version when there is none.
20
+ */
21
+ queryVersionId?: string;
15
22
  opened: {
16
23
  source: string;
17
24
  document: DashboardDocument;
@@ -118,6 +118,24 @@ export type ReportEditorProps = ({
118
118
  keepDraft?: boolean;
119
119
  /** Edit a document held as text; see {@link TextSourceOptions}. */
120
120
  textSource?: TextSourceOptions;
121
+ /**
122
+ * The package version the builder's queries run at, apart from the
123
+ * document's own identity: every tile, the report's manifest, filter
124
+ * options and suggestions, the report listing and the field catalog.
125
+ *
126
+ * The document is still the one `resourceUri` and `path` name, so the kept
127
+ * draft, where a save goes, the save caption and whether a save is a pinned
128
+ * one all follow `resourceUri` alone. A host editing a package that is
129
+ * republished on every change passes an unversioned `resourceUri` and the
130
+ * version its reader ran at here: the builder then reuses the reader's
131
+ * results instead of running every tile again, and kept edits survive the
132
+ * next republish.
133
+ *
134
+ * Unset, queries run at the `resourceUri`'s version, as before. A text-held
135
+ * document's compile has no version, so it is compiled as today; its tiles
136
+ * do run at this version.
137
+ */
138
+ queryVersionId?: string;
121
139
  };
122
140
  /**
123
141
  * Open a document the host keeps as TEXT, rather than a file in a package.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@malloy-publisher/sdk",
3
3
  "description": "Malloy Publisher SDK",
4
- "version": "0.9.13",
4
+ "version": "0.9.14",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
@@ -78,6 +78,7 @@ export function EditorSurface({
78
78
  packageName,
79
79
  modelPath,
80
80
  versionId,
81
+ queryVersionId,
81
82
  opened,
82
83
  replaces,
83
84
  onSave,
@@ -97,7 +98,14 @@ export function EditorSurface({
97
98
  modelPath: string;
98
99
  /** A display label; the editor keys on `modelPath`. */
99
100
  slug: string;
101
+ /** The document's version, from its `resourceUri`: what its control state is keyed by. */
100
102
  versionId?: string;
103
+ /**
104
+ * The package version every query runs at: tiles, the manifest, filter
105
+ * options, the listing and the catalog. `ReportEditor` passes its
106
+ * `queryVersionId`, or the document's own version when there is none.
107
+ */
108
+ queryVersionId?: string;
101
109
  opened: {
102
110
  source: string;
103
111
  document: DashboardDocument;
@@ -140,7 +148,7 @@ export function EditorSurface({
140
148
  environmentName,
141
149
  packageName,
142
150
  path: modelPath,
143
- versionId,
151
+ versionId: queryVersionId,
144
152
  },
145
153
  BUILDER_HANDOFF_STALE_MS,
146
154
  ),
@@ -198,7 +206,7 @@ export function EditorSurface({
198
206
  const { reports: reportList, settled: reportsSettled } = useReportListing(
199
207
  environmentName,
200
208
  packageName,
201
- versionId,
209
+ queryVersionId,
202
210
  );
203
211
  const otherDashboards = useMemo(
204
212
  () =>
@@ -216,7 +224,7 @@ export function EditorSurface({
216
224
  const catalog = useEditorCatalog({
217
225
  environmentName,
218
226
  packageName,
219
- ...(versionId !== undefined ? { versionId } : {}),
227
+ ...(queryVersionId !== undefined ? { versionId: queryVersionId } : {}),
220
228
  modelPath,
221
229
  reports: reportList,
222
230
  reportsSettled,
@@ -365,7 +373,7 @@ export function EditorSurface({
365
373
  environmentName,
366
374
  packageName,
367
375
  modelPath: textSource ? runModelPath : manifest?.path,
368
- versionId,
376
+ versionId: queryVersionId,
369
377
  documentName: modelPath,
370
378
  ...(preamble !== undefined ? { preamble } : {}),
371
379
  ...(hostGivens ? { hostGivens } : {}),
@@ -463,7 +471,7 @@ export function EditorSurface({
463
471
  <DashboardTile
464
472
  environmentName={environmentName}
465
473
  packageName={packageName}
466
- versionId={versionId}
474
+ versionId={queryVersionId}
467
475
  modelPath={runModelPath}
468
476
  {...(preamble !== undefined ? { preamble } : {})}
469
477
  {...(restrictedTiles.has(
@@ -508,7 +516,7 @@ export function EditorSurface({
508
516
  servedReads,
509
517
  environmentName,
510
518
  packageName,
511
- versionId,
519
+ queryVersionId,
512
520
  runModelPath,
513
521
  preamble,
514
522
  restrictedTiles,
@@ -529,7 +537,7 @@ export function EditorSurface({
529
537
  <DashboardTile
530
538
  environmentName={environmentName}
531
539
  packageName={packageName}
532
- versionId={versionId}
540
+ versionId={queryVersionId}
533
541
  modelPath={view.modelPath}
534
542
  tile={`${view.base} -> ${view.view}`}
535
543
  {...(view.chart
@@ -553,7 +561,7 @@ export function EditorSurface({
553
561
  [
554
562
  environmentName,
555
563
  packageName,
556
- versionId,
564
+ queryVersionId,
557
565
  applied,
558
566
  tileHostGivens,
559
567
  declaredTypes,
@@ -0,0 +1,292 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
5
+ import { beforeEach, describe, expect, it, mock } from "bun:test";
6
+ import {
7
+ cacheKeys,
8
+ clearCache,
9
+ mockServerProvider,
10
+ pending,
11
+ serverWrapper,
12
+ TEST_SERVER,
13
+ } from "../../../test/serverProvider";
14
+ import { BrowserDocumentStorage } from "../DocumentStorage/BrowserDocumentStorage";
15
+ import { DocumentStorageProvider } from "../DocumentStorage/DocumentStorageProvider";
16
+ import { editInline } from "./testing/inline";
17
+ import { reportDraftKey } from "./useReportDraft";
18
+
19
+ /**
20
+ * `queryVersionId`: the version the builder's queries run at, apart from the
21
+ * document's identity. A host whose package republishes on every change opens
22
+ * the builder on an unversioned `resourceUri` with its reader's version here,
23
+ * so the builder reuses the reader's results while the kept draft, the save
24
+ * target and the save caption stay with the unversioned document.
25
+ */
26
+ const REPORT = "dashboards/overview.malloy";
27
+ const PACKAGE_FILE = `## artifact { title="Storefront" tiles=["a -> by_cat"] } dashboard { columns=12 }
28
+ import { scoped_orders } from "../data_app.malloy"
29
+
30
+ source: a is scoped_orders extend {
31
+ # colspan=6
32
+ # label="By category"
33
+ view: by_cat is by_category
34
+ }`;
35
+
36
+ const getModel = mock(
37
+ (_env: string, _pkg: string, path: string, _versionId?: string) =>
38
+ Promise.resolve({
39
+ data:
40
+ path === REPORT
41
+ ? { modelPath: path, sourceText: PACKAGE_FILE }
42
+ : {
43
+ modelPath: path,
44
+ modelInfo: JSON.stringify({
45
+ entries: [{ kind: "source", name: "scoped_orders" }],
46
+ }),
47
+ sources: [
48
+ {
49
+ name: "scoped_orders",
50
+ views: [{ name: "by_category" }],
51
+ },
52
+ ],
53
+ sourceInfos: [
54
+ JSON.stringify({
55
+ name: "scoped_orders",
56
+ schema: { fields: [] },
57
+ }),
58
+ ],
59
+ },
60
+ }),
61
+ );
62
+ const getReport = mock(
63
+ (
64
+ _env: string,
65
+ _pkg: string,
66
+ _path: string,
67
+ _versionId?: string,
68
+ _options?: unknown,
69
+ ) =>
70
+ Promise.resolve({
71
+ data: {
72
+ path: REPORT,
73
+ name: "overview",
74
+ title: "Storefront",
75
+ layout: "grid",
76
+ givens: [],
77
+ tiles: [{ kind: "query", query: "a -> by_cat", givenNames: [] }],
78
+ },
79
+ }),
80
+ );
81
+ const listModels = mock((_env: string, _pkg: string, _versionId?: string) =>
82
+ Promise.resolve({ data: [{ path: "data_app.malloy" }] }),
83
+ );
84
+ const listReports = mock((_env: string, _pkg: string, _versionId?: string) =>
85
+ Promise.resolve({
86
+ data: [{ path: REPORT, name: "overview", layout: "grid" }],
87
+ }),
88
+ );
89
+ const updateModelSource = mock(
90
+ (_env: string, _pkg: string, path: string, body: { source: string }) =>
91
+ Promise.resolve({
92
+ data: {
93
+ path,
94
+ contentHash: `hash-of-${body.source.length}`,
95
+ created: false,
96
+ },
97
+ }),
98
+ );
99
+ // Answers by default, so the reader's tiles land in the cache; a test that
100
+ // wants nothing to settle swaps in `pending`.
101
+ let answer: () => Promise<unknown> = () =>
102
+ Promise.resolve({ data: { result: "{}" } });
103
+ const executeQueryModel = mock(
104
+ (
105
+ _env: string,
106
+ _pkg: string,
107
+ _path: string,
108
+ _body: { query?: string; givens?: unknown; versionId?: string },
109
+ ) => answer(),
110
+ );
111
+
112
+ const serverContext = { mutable: false };
113
+ mockServerProvider(
114
+ {
115
+ models: { getModel, executeQueryModel, updateModelSource, listModels },
116
+ reports: { getReport, listReports },
117
+ notebooks: { getNotebook: () => pending() },
118
+ },
119
+ serverContext,
120
+ );
121
+
122
+ const { ReportEditor } = await import("./ReportEditor");
123
+ const { Report } = await import("../Report/Report");
124
+
125
+ const URI = "publisher://environments/env/packages/pkg";
126
+
127
+ const mountEditor = (
128
+ props: { queryVersionId?: string; keepDraft?: boolean } = {},
129
+ resourceUri = URI,
130
+ ) =>
131
+ render(
132
+ <DocumentStorageProvider documentStorage={new BrowserDocumentStorage()}>
133
+ <ReportEditor resourceUri={resourceUri} path={REPORT} {...props} />
134
+ </DocumentStorageProvider>,
135
+ { wrapper: serverWrapper },
136
+ );
137
+
138
+ // The tile, as the reader and an untouched builder tile both ask for it.
139
+ const tileCalls = () =>
140
+ executeQueryModel.mock.calls.filter((call) =>
141
+ call[3].query?.includes("a -> by_cat"),
142
+ );
143
+
144
+ beforeEach(() => {
145
+ clearCache();
146
+ localStorage.clear();
147
+ for (const fn of [
148
+ getModel,
149
+ getReport,
150
+ listModels,
151
+ listReports,
152
+ updateModelSource,
153
+ executeQueryModel,
154
+ ])
155
+ fn.mockClear();
156
+ answer = () => Promise.resolve({ data: { result: "{}" } });
157
+ serverContext.mutable = false;
158
+ });
159
+
160
+ describe("queryVersionId", () => {
161
+ it("serves the builder's tile from the result the reader cached at that version", async () => {
162
+ const reader = render(
163
+ <Report resourceUri={`${URI}?versionId=v7`} path={REPORT} />,
164
+ { wrapper: serverWrapper },
165
+ );
166
+ await waitFor(() => expect(tileCalls()).toHaveLength(1));
167
+ expect(tileCalls()[0][3].versionId).toBe("v7");
168
+ await waitFor(() =>
169
+ expect(
170
+ cacheKeys("queryResult").some((key) => key.includes('"v7"')),
171
+ ).toBe(true),
172
+ );
173
+ reader.unmount();
174
+
175
+ mountEditor({ queryVersionId: "v7" });
176
+ expect(await screen.findByText("Storefront")).toBeDefined();
177
+ // Everything the builder reads besides the file itself has answered,
178
+ // so a tile that was going to run has run by now.
179
+ await waitFor(() =>
180
+ expect(
181
+ getModel.mock.calls.some((call) => call[2] === "data_app.malloy"),
182
+ ).toBe(true),
183
+ );
184
+ await new Promise((resolve) => setTimeout(resolve, 50));
185
+ expect(tileCalls()).toHaveLength(1);
186
+ // Nothing was asked unversioned: no second copy of the tile's result.
187
+ expect(
188
+ cacheKeys("queryResult").every((key) => key.includes('"v7"')),
189
+ ).toBe(true);
190
+ });
191
+
192
+ it("runs every query at that version, and reads the document unversioned", async () => {
193
+ answer = () => pending();
194
+ mountEditor({ queryVersionId: "v7" });
195
+ expect(await screen.findByText("Storefront")).toBeDefined();
196
+ await waitFor(() =>
197
+ expect(
198
+ getModel.mock.calls.some((call) => call[2] === "data_app.malloy"),
199
+ ).toBe(true),
200
+ );
201
+ await waitFor(() => expect(tileCalls().length).toBeGreaterThan(0));
202
+
203
+ // The document: the file the editor opens and saves.
204
+ expect(getModel.mock.calls.find((call) => call[2] === REPORT)).toEqual([
205
+ "env",
206
+ "pkg",
207
+ REPORT,
208
+ undefined,
209
+ ]);
210
+ // The queries: the manifest, the listing, the catalog and the tiles.
211
+ expect(getReport.mock.calls[0].slice(0, 4)).toEqual([
212
+ "env",
213
+ "pkg",
214
+ REPORT,
215
+ "v7",
216
+ ]);
217
+ expect(listReports.mock.calls[0]).toEqual(["env", "pkg", "v7"]);
218
+ expect(listModels.mock.calls[0]).toEqual(["env", "pkg", "v7"]);
219
+ expect(
220
+ getModel.mock.calls.find((call) => call[2] === "data_app.malloy"),
221
+ ).toEqual(["env", "pkg", "data_app.malloy", "v7"]);
222
+ for (const call of tileCalls()) expect(call[3].versionId).toBe("v7");
223
+ });
224
+
225
+ it("keeps the draft under the document's key, not the query version's", async () => {
226
+ answer = () => pending();
227
+ mountEditor({ queryVersionId: "v7", keepDraft: true });
228
+ await screen.findByText("Storefront");
229
+ editInline("By category", "Tile title", "Categories");
230
+
231
+ const unversioned = reportDraftKey({
232
+ server: TEST_SERVER,
233
+ environmentName: "env",
234
+ packageName: "pkg",
235
+ path: REPORT,
236
+ });
237
+ await waitFor(() =>
238
+ expect(
239
+ Object.keys(localStorage).some((key) => key.endsWith(unversioned)),
240
+ ).toBe(true),
241
+ );
242
+ expect(
243
+ Object.keys(localStorage).some((key) => key.includes("@v7/")),
244
+ ).toBe(false);
245
+ });
246
+
247
+ it("saves to the package as an unpinned document, with no pinned-version caption", async () => {
248
+ answer = () => pending();
249
+ serverContext.mutable = true;
250
+ mountEditor({ queryVersionId: "v7" });
251
+ await screen.findByText("Storefront");
252
+ expect(screen.queryByText(/Reading version/)).toBeNull();
253
+
254
+ editInline("By category", "Tile title", "Categories");
255
+ fireEvent.click(
256
+ screen.getByRole("button", { name: "Save", hidden: true }),
257
+ );
258
+ await waitFor(() => expect(updateModelSource).toHaveBeenCalledTimes(1));
259
+ expect(updateModelSource.mock.calls[0].slice(0, 3)).toEqual([
260
+ "env",
261
+ "pkg",
262
+ REPORT,
263
+ ]);
264
+ });
265
+
266
+ it("unset, runs the queries at the resourceUri's version, pinned as before", async () => {
267
+ answer = () => pending();
268
+ serverContext.mutable = true;
269
+ mountEditor({}, `${URI}?versionId=v7`);
270
+ await screen.findByText("Storefront");
271
+ await waitFor(() => expect(tileCalls().length).toBeGreaterThan(0));
272
+
273
+ expect(getModel.mock.calls.find((call) => call[2] === REPORT)?.[3]).toBe(
274
+ "v7",
275
+ );
276
+ for (const call of tileCalls()) expect(call[3].versionId).toBe("v7");
277
+ expect(
278
+ screen.getByText(
279
+ "Reading version v7: a version is a fixed point in history, so Save is off.",
280
+ ),
281
+ ).toBeDefined();
282
+ });
283
+
284
+ it("unset with no version anywhere, asks every query unversioned", async () => {
285
+ answer = () => pending();
286
+ mountEditor();
287
+ await screen.findByText("Storefront");
288
+ await waitFor(() => expect(tileCalls().length).toBeGreaterThan(0));
289
+ for (const call of tileCalls()) expect(call[3].versionId).toBeUndefined();
290
+ expect(getReport.mock.calls[0][3]).toBeUndefined();
291
+ });
292
+ });
@@ -155,6 +155,24 @@ export type ReportEditorProps = (
155
155
  keepDraft?: boolean;
156
156
  /** Edit a document held as text; see {@link TextSourceOptions}. */
157
157
  textSource?: TextSourceOptions;
158
+ /**
159
+ * The package version the builder's queries run at, apart from the
160
+ * document's own identity: every tile, the report's manifest, filter
161
+ * options and suggestions, the report listing and the field catalog.
162
+ *
163
+ * The document is still the one `resourceUri` and `path` name, so the kept
164
+ * draft, where a save goes, the save caption and whether a save is a pinned
165
+ * one all follow `resourceUri` alone. A host editing a package that is
166
+ * republished on every change passes an unversioned `resourceUri` and the
167
+ * version its reader ran at here: the builder then reuses the reader's
168
+ * results instead of running every tile again, and kept edits survive the
169
+ * next republish.
170
+ *
171
+ * Unset, queries run at the `resourceUri`'s version, as before. A text-held
172
+ * document's compile has no version, so it is compiled as today; its tiles
173
+ * do run at this version.
174
+ */
175
+ queryVersionId?: string;
158
176
  };
159
177
 
160
178
  /**
@@ -210,6 +228,7 @@ export function ReportEditor(props: ReportEditorProps) {
210
228
  kind,
211
229
  path,
212
230
  textSource,
231
+ queryVersionId,
213
232
  } = props;
214
233
  const layout: ReportLayout =
215
234
  props.layout ?? (kind ? layoutOfKind(kind) : "grid");
@@ -536,6 +555,9 @@ export function ReportEditor(props: ReportEditorProps) {
536
555
  {...(textSource ? { textSource } : {})}
537
556
  slug={dashboardName}
538
557
  {...(versionId !== undefined ? { versionId } : {})}
558
+ {...((queryVersionId ?? versionId) !== undefined
559
+ ? { queryVersionId: queryVersionId ?? versionId }
560
+ : {})}
539
561
  opened={opened}
540
562
  {...(fromDraft &&
541
563
  writer === "package" &&