@malloy-publisher/sdk 0.8.0 → 0.8.2

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.
Files changed (40) hide show
  1. package/dist/{DocumentStorage-D7yF4_T3.cjs.js → DocumentStorage-B0_YgSzt.cjs.js} +32 -32
  2. package/dist/{DocumentStorage-BypSIWDg.es.js → DocumentStorage-BZqn0x5r.es.js} +3826 -3741
  3. package/dist/{RenderedResult-ChkvK7b2.cjs.js → RenderedResult-Bu25oAAr.cjs.js} +1 -1
  4. package/dist/{RenderedResult-CYyhQekT.es.js → RenderedResult-DKOl0FQ8.es.js} +2 -2
  5. package/dist/{ServerProvider-AsUiy22k.es.js → ServerProvider-CfUFleYe.es.js} +24 -24
  6. package/dist/builder/index.cjs.js +31 -31
  7. package/dist/builder/index.es.js +1167 -1142
  8. package/dist/client/api.d.ts +36 -30
  9. package/dist/client/index.es.js +1 -1
  10. package/dist/components/Dashboard/ExploreDialog.d.ts +3 -1
  11. package/dist/components/DashboardBuilder/catalog.d.ts +18 -0
  12. package/dist/components/Model/Model.d.ts +10 -3
  13. package/dist/components/Model/ModelExplorer.d.ts +21 -1
  14. package/dist/components/Model/ModelExplorerDialog.d.ts +4 -1
  15. package/dist/components/Model/SourcesExplorer.d.ts +8 -1
  16. package/dist/components/Model/index.d.ts +1 -0
  17. package/dist/components/Model/runGate.d.ts +19 -0
  18. package/dist/components/Notebook/NotebookCell.d.ts +10 -1
  19. package/dist/index.cjs.js +13 -13
  20. package/dist/index.es.js +3754 -3732
  21. package/package.json +1 -1
  22. package/src/components/Dashboard/Dashboard.spec.tsx +58 -2
  23. package/src/components/Dashboard/Dashboard.tsx +8 -1
  24. package/src/components/Dashboard/ExploreDialog.tsx +5 -0
  25. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +6 -1
  26. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +60 -30
  27. package/src/components/DashboardBuilder/DashboardEditor.tsx +35 -16
  28. package/src/components/DashboardBuilder/catalog.spec.ts +44 -0
  29. package/src/components/DashboardBuilder/catalog.ts +36 -0
  30. package/src/components/Model/Model.tsx +28 -1
  31. package/src/components/Model/ModelExplorer.spec.tsx +404 -0
  32. package/src/components/Model/ModelExplorer.tsx +65 -2
  33. package/src/components/Model/ModelExplorerDialog.tsx +12 -0
  34. package/src/components/Model/SourcesExplorer.tsx +70 -15
  35. package/src/components/Model/index.ts +1 -0
  36. package/src/components/Model/runGate.spec.ts +102 -0
  37. package/src/components/Model/runGate.ts +67 -0
  38. package/src/components/Notebook/Notebook.spec.tsx +67 -3
  39. package/src/components/Notebook/Notebook.tsx +12 -2
  40. package/src/components/Notebook/NotebookCell.tsx +26 -7
@@ -0,0 +1,404 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The Explorer sends the control row's values with every Run, and surfaces a
6
+ * default note, a server error and a missing-given hint as banners rather than
7
+ * swallowing them.
8
+ *
9
+ * `@malloydata/malloy-explorer` is stubbed because it is lazy-loaded (a
10
+ * dynamic `import()` inside `SourceExplorerComponent`) and pulls in a real
11
+ * query-builder and renderer this spec has no business exercising; only
12
+ * `mock.module` reaches a dynamic import the same way it reaches a static one.
13
+ * It is process-global, so this is the one spec in the package allowed to
14
+ * import either module — see test/README.md.
15
+ */
16
+ import { beforeEach, describe, expect, it, mock } from "bun:test";
17
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
18
+ import type { ReactNode } from "react";
19
+ import {
20
+ clearCache,
21
+ mockServerProvider,
22
+ pending,
23
+ serverWrapper,
24
+ } from "../../../test/serverProvider";
25
+ import type { CompiledModel } from "../../client";
26
+
27
+ mock.module("@malloydata/malloy-explorer", () => ({
28
+ MalloyExplorerProvider: ({ children }: { children: ReactNode }) => (
29
+ <>{children}</>
30
+ ),
31
+ QueryPanel: ({ runQuery }: { runQuery: () => void }) => (
32
+ <button onClick={runQuery}>Run</button>
33
+ ),
34
+ ResizableCollapsiblePanel: ({ children }: { children: ReactNode }) => (
35
+ <>{children}</>
36
+ ),
37
+ SourcePanel: () => null,
38
+ ResultPanel: ({
39
+ submittedQuery,
40
+ }: {
41
+ submittedQuery?: {
42
+ response?: { messages?: { title: string }[] };
43
+ onCancel: () => void;
44
+ };
45
+ }) => (
46
+ <div data-testid="result-panel">
47
+ {submittedQuery && (
48
+ <button onClick={submittedQuery.onCancel}>Cancel</button>
49
+ )}
50
+ {submittedQuery?.response?.messages?.map((message) => (
51
+ <div key={message.title}>{message.title}</div>
52
+ ))}
53
+ </div>
54
+ ),
55
+ }));
56
+
57
+ // Never reached when every test's query is a plain string (see below), but
58
+ // stubbed anyway so the module's own dynamic import resolves to something
59
+ // light rather than the real WASM-backed builder.
60
+ mock.module("@malloydata/malloy-query-builder", () => ({
61
+ ASTQuery: class {
62
+ toMalloy() {
63
+ return "run: orders -> by_month";
64
+ }
65
+ },
66
+ }));
67
+
68
+ const executeQueryModel = mock(
69
+ (
70
+ _environmentName: string,
71
+ _packageName: string,
72
+ _modelPath: string,
73
+ _request: { versionId?: string; givens?: Record<string, unknown> },
74
+ ) => pending<{ data: { result: string } }>(),
75
+ );
76
+
77
+ mockServerProvider({ models: { executeQueryModel } });
78
+
79
+ // Imported after the stubs above: a static import would hoist above them.
80
+ const { ModelExplorer } = await import("./ModelExplorer");
81
+
82
+ const URI = "publisher://environments/env/packages/pkg/models/orders.malloy";
83
+
84
+ const modelWith = (givens?: CompiledModel["givens"]): CompiledModel => ({
85
+ sourceInfos: [JSON.stringify({ name: "orders" })],
86
+ ...(givens ? { givens } : {}),
87
+ });
88
+
89
+ /** As a string, so `SourceExplorerComponentInner` never reaches `ASTQuery`. */
90
+ const EXISTING_QUERY = {
91
+ query: "run: orders -> by_month",
92
+ malloyQuery: "run: orders -> by_month",
93
+ malloyResult: undefined,
94
+ };
95
+
96
+ const run = () => fireEvent.click(screen.getByRole("button", { name: "Run" }));
97
+
98
+ beforeEach(() => {
99
+ clearCache();
100
+ executeQueryModel.mockReset();
101
+ executeQueryModel.mockImplementation(() => pending());
102
+ });
103
+
104
+ const reject = (status: number, message: string) =>
105
+ executeQueryModel.mockImplementation(() =>
106
+ Promise.reject(
107
+ Object.assign(new Error("fallback"), {
108
+ status,
109
+ data: { code: status, message },
110
+ }),
111
+ ),
112
+ );
113
+
114
+ describe("a given with no value and no default", () => {
115
+ // Givens are model-wide but read per source, so a blank one may be fine for
116
+ // the source being explored: the server decides, not the client.
117
+ it("still sends Run, and names the given when the server refuses", async () => {
118
+ reject(403, 'Access denied for source "regions".');
119
+ render(
120
+ <ModelExplorer
121
+ data={modelWith([{ name: "TENANT", type: "string" }])}
122
+ existingQuery={EXISTING_QUERY}
123
+ resourceUri={URI}
124
+ />,
125
+ { wrapper: serverWrapper },
126
+ );
127
+
128
+ await screen.findByLabelText("TENANT");
129
+ run();
130
+
131
+ expect(
132
+ await screen.findByText('Access denied for source "regions".'),
133
+ ).toBeTruthy();
134
+ expect(
135
+ screen.getByText(
136
+ "This source may need a value for the given TENANT. Set it in the parameters above.",
137
+ ),
138
+ ).toBeTruthy();
139
+ expect(executeQueryModel).toHaveBeenCalledTimes(1);
140
+ });
141
+
142
+ // The refusal check is status OR message; each case below pins one half alone.
143
+ it("names the given on a 403 whatever its message says", async () => {
144
+ reject(403, "Forbidden");
145
+ render(
146
+ <ModelExplorer
147
+ data={modelWith([{ name: "TENANT", type: "string" }])}
148
+ existingQuery={EXISTING_QUERY}
149
+ resourceUri={URI}
150
+ />,
151
+ { wrapper: serverWrapper },
152
+ );
153
+
154
+ await screen.findByLabelText("TENANT");
155
+ run();
156
+
157
+ expect(await screen.findByText("Forbidden")).toBeTruthy();
158
+ expect(
159
+ screen.getByText(/may need a value for the given TENANT/),
160
+ ).toBeTruthy();
161
+ });
162
+
163
+ it("names the given on a gate's message that carries no status", async () => {
164
+ executeQueryModel.mockImplementation(() =>
165
+ Promise.reject(new Error('Access denied for source "regions".')),
166
+ );
167
+ render(
168
+ <ModelExplorer
169
+ data={modelWith([{ name: "TENANT", type: "string" }])}
170
+ existingQuery={EXISTING_QUERY}
171
+ resourceUri={URI}
172
+ />,
173
+ { wrapper: serverWrapper },
174
+ );
175
+
176
+ await screen.findByLabelText("TENANT");
177
+ run();
178
+
179
+ expect(
180
+ await screen.findByText('Access denied for source "regions".'),
181
+ ).toBeTruthy();
182
+ expect(
183
+ screen.getByText(/may need a value for the given TENANT/),
184
+ ).toBeTruthy();
185
+ });
186
+
187
+ it("adds no hint to an error that is not a refusal", async () => {
188
+ reject(400, "syntax error near 'aggregat'");
189
+ render(
190
+ <ModelExplorer
191
+ data={modelWith([{ name: "TENANT", type: "string" }])}
192
+ existingQuery={EXISTING_QUERY}
193
+ resourceUri={URI}
194
+ />,
195
+ { wrapper: serverWrapper },
196
+ );
197
+
198
+ await screen.findByLabelText("TENANT");
199
+ run();
200
+
201
+ expect(
202
+ await screen.findByText("syntax error near 'aggregat'"),
203
+ ).toBeTruthy();
204
+ expect(screen.queryByText(/may need a value/)).toBeNull();
205
+ });
206
+ });
207
+
208
+ describe("a given left blank with a default", () => {
209
+ it("runs, and notes the default that was used", async () => {
210
+ executeQueryModel.mockImplementation(() =>
211
+ Promise.resolve({ data: { result: JSON.stringify({}) } }),
212
+ );
213
+ render(
214
+ <ModelExplorer
215
+ data={modelWith([
216
+ { name: "TENANT", type: "string", default: "'acme'" },
217
+ ])}
218
+ existingQuery={EXISTING_QUERY}
219
+ resourceUri={URI}
220
+ />,
221
+ { wrapper: serverWrapper },
222
+ );
223
+
224
+ await screen.findByLabelText("TENANT");
225
+ run();
226
+
227
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
228
+ expect(
229
+ await screen.findByText("Ran with the default TENANT = acme"),
230
+ ).toBeTruthy();
231
+ });
232
+ });
233
+
234
+ describe("a model that declares givens", () => {
235
+ it("sends the control's value with Run", async () => {
236
+ executeQueryModel.mockImplementation(() =>
237
+ Promise.resolve({ data: { result: JSON.stringify({}) } }),
238
+ );
239
+ render(
240
+ <ModelExplorer
241
+ data={modelWith([{ name: "TENANT", type: "string" }])}
242
+ existingQuery={EXISTING_QUERY}
243
+ resourceUri={URI}
244
+ />,
245
+ { wrapper: serverWrapper },
246
+ );
247
+
248
+ fireEvent.change(await screen.findByLabelText("TENANT"), {
249
+ target: { value: "acme" },
250
+ });
251
+ run();
252
+
253
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
254
+ expect(executeQueryModel.mock.calls[0][3].givens).toEqual({
255
+ TENANT: "acme",
256
+ });
257
+ });
258
+ });
259
+
260
+ describe("a model with no givens", () => {
261
+ it("renders no Parameters row, and sends no givens key", async () => {
262
+ executeQueryModel.mockImplementation(() =>
263
+ Promise.resolve({ data: { result: JSON.stringify({}) } }),
264
+ );
265
+ render(
266
+ <ModelExplorer
267
+ data={modelWith()}
268
+ existingQuery={EXISTING_QUERY}
269
+ resourceUri={URI}
270
+ />,
271
+ { wrapper: serverWrapper },
272
+ );
273
+
274
+ // Nothing to wait on the label for, so wait on the button instead.
275
+ await screen.findByRole("button", { name: "Run" });
276
+ expect(screen.queryByText("Parameters")).toBeNull();
277
+ run();
278
+
279
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
280
+ expect(executeQueryModel.mock.calls[0][3]).not.toHaveProperty("givens");
281
+ });
282
+ });
283
+
284
+ describe("a rejected run", () => {
285
+ it("shows the server's message rather than clearing the pane", async () => {
286
+ const apiError = Object.assign(new Error("fallback"), {
287
+ status: 403,
288
+ data: { code: 403, message: "Not authorized: missing TENANT" },
289
+ });
290
+ executeQueryModel.mockImplementation(() => Promise.reject(apiError));
291
+ render(
292
+ <ModelExplorer
293
+ data={modelWith([
294
+ { name: "TENANT", type: "string", default: "'x'" },
295
+ ])}
296
+ existingQuery={EXISTING_QUERY}
297
+ resourceUri={URI}
298
+ />,
299
+ { wrapper: serverWrapper },
300
+ );
301
+
302
+ await screen.findByLabelText("TENANT");
303
+ run();
304
+
305
+ expect(
306
+ await screen.findByText("Not authorized: missing TENANT"),
307
+ ).toBeTruthy();
308
+ });
309
+ });
310
+
311
+ describe("a cancelled run", () => {
312
+ it("stays cleared when its request fails afterwards", async () => {
313
+ let fail: (reason: unknown) => void = () => {};
314
+ executeQueryModel.mockImplementation(
315
+ () =>
316
+ new Promise((_resolve, reject) => {
317
+ fail = reject;
318
+ }),
319
+ );
320
+ render(
321
+ <ModelExplorer
322
+ data={modelWith()}
323
+ existingQuery={EXISTING_QUERY}
324
+ resourceUri={URI}
325
+ />,
326
+ { wrapper: serverWrapper },
327
+ );
328
+
329
+ await screen.findByRole("button", { name: "Run" });
330
+ run();
331
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel" }));
332
+ fail(
333
+ Object.assign(new Error("fallback"), {
334
+ status: 500,
335
+ data: { code: 500, message: "late failure" },
336
+ }),
337
+ );
338
+
339
+ // Give the rejection a chance to land before asserting it changed nothing.
340
+ await new Promise((resolve) => setTimeout(resolve, 50));
341
+ expect(screen.queryByText("late failure")).toBeNull();
342
+ expect(screen.queryByRole("button", { name: "Cancel" })).toBeNull();
343
+ });
344
+ });
345
+
346
+ describe("host-supplied givens", () => {
347
+ it("seeds the control, and reports a change with the given in `managed`", async () => {
348
+ const onGivensChange = mock(
349
+ (_givens: Record<string, string>, _managed: readonly string[]) => {},
350
+ );
351
+ render(
352
+ <ModelExplorer
353
+ data={modelWith([{ name: "TENANT", type: "string" }])}
354
+ existingQuery={EXISTING_QUERY}
355
+ resourceUri={URI}
356
+ givens={{ TENANT: "acme" }}
357
+ onGivensChange={onGivensChange}
358
+ />,
359
+ { wrapper: serverWrapper },
360
+ );
361
+
362
+ const input = (await screen.findByLabelText(
363
+ "TENANT",
364
+ )) as HTMLInputElement;
365
+ expect(input.value).toBe("acme");
366
+
367
+ fireEvent.change(input, { target: { value: "beta" } });
368
+
369
+ await waitFor(() =>
370
+ expect(onGivensChange).toHaveBeenCalledWith({ TENANT: "beta" }, [
371
+ "TENANT",
372
+ ]),
373
+ );
374
+ });
375
+ });
376
+
377
+ describe("startingGivens", () => {
378
+ it("seeds the control, and Run sends it", async () => {
379
+ executeQueryModel.mockImplementation(() =>
380
+ Promise.resolve({ data: { result: JSON.stringify({}) } }),
381
+ );
382
+ render(
383
+ <ModelExplorer
384
+ data={modelWith([{ name: "TENANT", type: "string" }])}
385
+ existingQuery={EXISTING_QUERY}
386
+ resourceUri={URI}
387
+ startingGivens={{ TENANT: "acme" }}
388
+ />,
389
+ { wrapper: serverWrapper },
390
+ );
391
+
392
+ const input = (await screen.findByLabelText(
393
+ "TENANT",
394
+ )) as HTMLInputElement;
395
+ expect(input.value).toBe("acme");
396
+
397
+ run();
398
+
399
+ await waitFor(() => expect(executeQueryModel).toHaveBeenCalled());
400
+ expect(executeQueryModel.mock.calls[0][3].givens).toEqual({
401
+ TENANT: "acme",
402
+ });
403
+ });
404
+ });
@@ -4,12 +4,16 @@
4
4
  import { Box, Stack } from "@mui/material";
5
5
  import Autocomplete from "@mui/material/Autocomplete";
6
6
  import TextField from "@mui/material/TextField";
7
- import React from "react";
7
+ import React, { useMemo } from "react";
8
8
  import { CompiledModel } from "../../client";
9
+ import { useDocumentControls } from "../../hooks/useDocumentControls";
9
10
  import { parseResourceUri } from "../../utils/formatting";
10
11
  import { ApiErrorDisplay } from "../ApiErrorDisplay";
12
+ import { GivensPanel } from "../given";
13
+ import { givensToRequest } from "../given/paramCodec";
11
14
  import { Loading } from "../Loading";
12
15
  import { StyledCard, StyledCardContent, StyledCardMedia } from "../styles";
16
+ import { runGate } from "./runGate";
13
17
  import { QueryExplorerResult, SourcesExplorer } from "./SourcesExplorer";
14
18
  import { useModelData } from "./useModelData";
15
19
 
@@ -53,6 +57,29 @@ export interface ModelExplorerProps {
53
57
  /** Callback when source selection changes */
54
58
  onSourceChange?: (index: number) => void;
55
59
  resourceUri: string;
60
+ /**
61
+ * Control values from the host, typically its URL query parameters. These
62
+ * beat the model's own starting values, so a shared link shows what the
63
+ * sender was looking at.
64
+ */
65
+ givens?: Record<string, string>;
66
+ /**
67
+ * Applied control values, for a host that wants them in its URL.
68
+ *
69
+ * `managed` is every given this model declares, whether or not it currently
70
+ * holds a value, and a host writing to a shared query string needs it.
71
+ * `givens` alone says which parameters to write but not which to REMOVE, so
72
+ * a host that guesses by deleting everything it did not just receive
73
+ * deletes the unrelated parameters it has no business touching. Same
74
+ * contract as `Dashboard` and `Notebook`, so a host can treat every surface
75
+ * alike.
76
+ */
77
+ onGivensChange?: (
78
+ givens: Record<string, string>,
79
+ managed: readonly string[],
80
+ ) => void;
81
+ /** Where the controls start, from the host, e.g. a dashboard tile's values. */
82
+ startingGivens?: Record<string, string>;
56
83
  }
57
84
 
58
85
  /**
@@ -68,6 +95,9 @@ export function ModelExplorer({
68
95
  initialSelectedSourceIndex = 0,
69
96
  onSourceChange,
70
97
  resourceUri,
98
+ givens,
99
+ onGivensChange,
100
+ startingGivens,
71
101
  }: ModelExplorerProps) {
72
102
  const [selectedTab, setSelectedTab] = React.useState(
73
103
  initialSelectedSourceIndex,
@@ -85,10 +115,40 @@ export function ModelExplorer({
85
115
  isLoading,
86
116
  error,
87
117
  } = useModelData(resourceUri, !data); // we shld only fetch when data is not provided
88
- const { modelPath } = parseResourceUri(resourceUri);
118
+ const { environmentName, packageName, modelPath, versionId } =
119
+ parseResourceUri(resourceUri);
89
120
 
90
121
  const effectiveData = data || fetchedData;
91
122
 
123
+ // Above the early returns, which would otherwise skip these hooks.
124
+ const specs = React.useMemo(
125
+ () => effectiveData?.givens ?? [],
126
+ [effectiveData],
127
+ );
128
+ const controls = useDocumentControls({
129
+ specs,
130
+ loaded: !!effectiveData,
131
+ params: givens,
132
+ onGivensChange,
133
+ startingValues: startingGivens,
134
+ documentKey: resourceUri,
135
+ // No Apply button: the Explorer already waits for an explicit Run.
136
+ autorun: true,
137
+ environmentName: environmentName ?? "",
138
+ packageName: packageName ?? "",
139
+ modelPath,
140
+ versionId,
141
+ documentName: modelPath,
142
+ });
143
+ const requestGivens = useMemo(
144
+ () => givensToRequest(controls.applied, controls.declaredTypes),
145
+ [controls.applied, controls.declaredTypes],
146
+ );
147
+ const gate = useMemo(
148
+ () => runGate(specs, controls.applied),
149
+ [specs, controls.applied],
150
+ );
151
+
92
152
  if (isLoading && !data) {
93
153
  return <Loading text="Fetching Model..." />;
94
154
  }
@@ -180,6 +240,7 @@ export function ModelExplorer({
180
240
  />
181
241
  </Stack>
182
242
  </StyledCardContent>
243
+ <GivensPanel {...controls.panel} />
183
244
  <StyledCardMedia>
184
245
  <Stack spacing={2} component="section">
185
246
  {/* Render the selected source info */}
@@ -199,6 +260,8 @@ export function ModelExplorer({
199
260
  existingQuery={existingQuery}
200
261
  onQueryChange={onChange}
201
262
  resourceUri={resourceUri}
263
+ givens={requestGivens}
264
+ gate={gate}
202
265
  />
203
266
  )}
204
267
 
@@ -19,6 +19,12 @@ interface ModelExplorerDialogProps {
19
19
  initialSelectedSourceIndex?: number;
20
20
  onChange?: (query: QueryExplorerResult) => void;
21
21
  onSourceChange?: (index: number) => void;
22
+ givens?: Record<string, string>;
23
+ onGivensChange?: (
24
+ givens: Record<string, string>,
25
+ managed: readonly string[],
26
+ ) => void;
27
+ startingGivens?: Record<string, string>;
22
28
  }
23
29
 
24
30
  export function ModelExplorerDialog({
@@ -32,6 +38,9 @@ export function ModelExplorerDialog({
32
38
  initialSelectedSourceIndex,
33
39
  onChange,
34
40
  onSourceChange,
41
+ givens,
42
+ onGivensChange,
43
+ startingGivens,
35
44
  }: ModelExplorerDialogProps) {
36
45
  return (
37
46
  <Dialog open={open} onClose={onClose} fullScreen>
@@ -56,6 +65,9 @@ export function ModelExplorerDialog({
56
65
  initialSelectedSourceIndex={initialSelectedSourceIndex}
57
66
  onChange={onChange}
58
67
  onSourceChange={onSourceChange}
68
+ givens={givens}
69
+ onGivensChange={onGivensChange}
70
+ startingGivens={startingGivens}
59
71
  />
60
72
  ) : (
61
73
  <div>No valid import statement found in cell</div>