@malloy-publisher/sdk 0.12.5 → 0.13.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.
@@ -259,7 +259,13 @@ describe("createDocument names", () => {
259
259
  expect(result.slug).toBe("sales-2");
260
260
  });
261
261
 
262
- it("on the package route, moves to the next name when the server answers 409", async () => {
262
+ it("on the package route, moves to the next name when a server from before the reason says the file exists", async () => {
263
+ // Both wordings an older server answered a create collision with, as a
264
+ // 409 with no `reason`.
265
+ const said = [
266
+ "`sales.malloy` already exists in the package. Send the `expectedHash` of the text you opened to replace it.",
267
+ "`sales-2.malloy` already exists in the package, so nothing was written. Choose another path, or, to replace a report, send the `expectedHash` of the text you opened.",
268
+ ];
263
269
  const tried: string[] = [];
264
270
  const result = await createDocument({
265
271
  layout: "grid",
@@ -271,7 +277,10 @@ describe("createDocument names", () => {
271
277
  tried.push(path);
272
278
  if (tried.length < 3)
273
279
  throw Object.assign(new Error("exists"), {
274
- response: { status: 409 },
280
+ response: {
281
+ status: 409,
282
+ data: { code: 409, message: said[tried.length - 1] },
283
+ },
275
284
  });
276
285
  },
277
286
  },
@@ -284,6 +293,119 @@ describe("createDocument names", () => {
284
293
  expect(result.slug).toBe("sales-3");
285
294
  });
286
295
 
296
+ it.each([
297
+ ["a package loading", "Package pkg is loading; try again shortly."],
298
+ [
299
+ "a materialization conflict",
300
+ "A materialization build of pkg is already running.",
301
+ ],
302
+ ["no message at all", undefined],
303
+ ])(
304
+ "on the package route, a reasonless 409 for %s is thrown at once, not read as a taken name",
305
+ async (_what, message) => {
306
+ let writes = 0;
307
+ const error = (await createDocument({
308
+ layout: "grid",
309
+ document: DOC,
310
+ target: {
311
+ route: "package",
312
+ existing: [],
313
+ write: async () => {
314
+ writes++;
315
+ throw Object.assign(new Error("Request failed with 409"), {
316
+ response: { status: 409, data: { code: 409, message } },
317
+ });
318
+ },
319
+ },
320
+ }).catch((e: unknown) => e)) as {
321
+ response?: { data?: { message?: string } };
322
+ };
323
+ expect(error.response?.data?.message).toBe(message);
324
+ expect(writes).toBe(1);
325
+ },
326
+ );
327
+
328
+ it("on the package route, moves to the next name only when the 409 says the file exists", async () => {
329
+ const tried: string[] = [];
330
+ const result = await createDocument({
331
+ layout: "grid",
332
+ document: DOC,
333
+ target: {
334
+ route: "package",
335
+ existing: [],
336
+ write: async (path) => {
337
+ tried.push(path);
338
+ if (tried.length < 2)
339
+ throw Object.assign(new Error("exists"), {
340
+ response: {
341
+ status: 409,
342
+ data: { code: 409, reason: "FILE_EXISTS" },
343
+ },
344
+ });
345
+ },
346
+ },
347
+ });
348
+ expect(tried).toEqual(["sales.malloy", "sales-2.malloy"]);
349
+ expect(result.slug).toBe("sales-2");
350
+ });
351
+
352
+ it.each(["PACKAGE_INSTALLED_FROM_LOCATION", "PACKAGE_IS_VERSIONED"])(
353
+ "on the package route, a 409 with reason %s is thrown at once with the server's message",
354
+ async (reason) => {
355
+ const message = `Package pkg cannot take this write (${reason}).`;
356
+ let writes = 0;
357
+ const events: unknown[] = [];
358
+ const refusal = createDocument({
359
+ layout: "grid",
360
+ document: DOC,
361
+ target: {
362
+ route: "package",
363
+ existing: [],
364
+ write: async () => {
365
+ writes++;
366
+ throw Object.assign(new Error("Request failed with 409"), {
367
+ response: {
368
+ status: 409,
369
+ data: { code: 409, message, reason },
370
+ },
371
+ });
372
+ },
373
+ },
374
+ onEvent: (e) => events.push(e),
375
+ });
376
+ // The error itself, so the dialog reads the server's message from it.
377
+ const error = (await refusal.catch((e: unknown) => e)) as {
378
+ response?: { data?: { message?: string } };
379
+ };
380
+ expect(error.response?.data?.message).toBe(message);
381
+ expect(writes).toBe(1);
382
+ expect(events).toHaveLength(1);
383
+ expect(events[0]).toMatchObject({ type: "report.create_refused" });
384
+ },
385
+ );
386
+
387
+ it("on the package route, a path given outright that a 409 refuses for another reason is not reported as taken", async () => {
388
+ await expect(
389
+ createDocument({
390
+ layout: "grid",
391
+ path: "team/sales.malloy",
392
+ document: DOC,
393
+ target: {
394
+ route: "package",
395
+ existing: [],
396
+ write: async () => {
397
+ throw Object.assign(new Error("installed from a location"), {
398
+ response: {
399
+ status: 409,
400
+ data: { reason: "PACKAGE_INSTALLED_FROM_LOCATION" },
401
+ },
402
+ });
403
+ },
404
+ },
405
+ }),
406
+ ).rejects.toThrow("installed from a location");
407
+ });
408
+
287
409
  it("on the package route, any other failure is thrown, not retried", async () => {
288
410
  let writes = 0;
289
411
  await expect(
@@ -400,7 +522,7 @@ describe("createDocument at a path", () => {
400
522
  expect(writes).toEqual([]);
401
523
  });
402
524
 
403
- it("refuses a path the server answers 409 for, once", async () => {
525
+ it("refuses a path the server answers 409 FILE_EXISTS for, once", async () => {
404
526
  const tried: string[] = [];
405
527
  await expect(
406
528
  createDocument({
@@ -412,7 +534,7 @@ describe("createDocument at a path", () => {
412
534
  write: async (path) => {
413
535
  tried.push(path);
414
536
  throw Object.assign(new Error("exists"), {
415
- response: { status: 409 },
537
+ response: { status: 409, data: { reason: "FILE_EXISTS" } },
416
538
  });
417
539
  },
418
540
  },
@@ -181,8 +181,10 @@ async function writeNewReport(
181
181
  path = candidate;
182
182
  break;
183
183
  } catch (error) {
184
- // A create-only write refused as a conflict means the listing was stale; the next name is free to try.
185
- if (!isConflict(error)) throw error;
184
+ // A file already at the path means the listing was stale, and the
185
+ // next name is free to try. Any other refusal (a package that takes
186
+ // no write in place) fails every name alike, so it is thrown as is.
187
+ if (!isFileExists(error)) throw error;
186
188
  }
187
189
  }
188
190
  if (path === undefined) throw noFreeName(document.title, options.path);
@@ -228,8 +230,40 @@ async function writeNewReport(
228
230
  return found;
229
231
  }
230
232
 
231
- const isConflict = (error: unknown) =>
232
- (error as { response?: { status?: number } })?.response?.status === 409;
233
+ /**
234
+ * What a server from before `reason` FILE_EXISTS said when a create found a
235
+ * file at its path: "`<path>` already exists in the package. Send the …" in
236
+ * the first release that had the write, then "`<path>` already exists in the
237
+ * package, so nothing was written. …". It answers other 409s on the same
238
+ * route with no `reason` too (a package loading or unloading, a
239
+ * materialization conflict), and those are not a taken name.
240
+ */
241
+ const OLD_SERVER_FILE_EXISTS = /^`[^`]+` already exists in the package\b/;
242
+
243
+ /**
244
+ * Whether a create-only write was refused because a file is already at the
245
+ * path: 409 with `reason` FILE_EXISTS, or, from a server that predates the
246
+ * reason, a reasonless 409 whose message is that server's for a file at the
247
+ * path (OLD_SERVER_FILE_EXISTS). Any other 409, with another reason
248
+ * (PACKAGE_IS_VERSIONED, PACKAGE_INSTALLED_FROM_LOCATION) or none, is not:
249
+ * it would refuse every name alike, so it is shown at once.
250
+ */
251
+ function isFileExists(error: unknown): boolean {
252
+ const response = (
253
+ error as {
254
+ response?: {
255
+ status?: number;
256
+ data?: { reason?: unknown; message?: unknown };
257
+ };
258
+ }
259
+ )?.response;
260
+ if (response?.status !== 409) return false;
261
+ const reason = response.data?.reason;
262
+ if (reason === "FILE_EXISTS") return true;
263
+ if (reason !== undefined && reason !== null) return false;
264
+ const message = response.data?.message;
265
+ return typeof message === "string" && OLD_SERVER_FILE_EXISTS.test(message);
266
+ }
233
267
 
234
268
  const noFreeName = (title: string, path?: string) =>
235
269
  new Error(
@@ -61,8 +61,8 @@ async function listVersions(
61
61
  /**
62
62
  * A package's published versions.
63
63
  *
64
- * A package with none — versioning off, a package loaded from configuration —
65
- * and a server that predates versions read as no versions, so the page draws
64
+ * A package with none — one in a watched environment, or any with versioning
65
+ * off — and a server that predates versions read as no versions, so the page draws
66
66
  * exactly as it did before versions existed. A listing that failed reads as
67
67
  * no versions too, but says so with `isError`: until it answers, nothing may
68
68
  * assume the package can be edited.
@@ -121,6 +121,29 @@ interface RenderedResultProps {
121
121
 
122
122
  const FILL_ATTR = "data-publisher-fill";
123
123
 
124
+ /**
125
+ * Whether this page may compile code from strings. Vega compiles each chart's
126
+ * expressions with `new Function`, which a Content-Security-Policy without
127
+ * `'unsafe-eval'` refuses: an MCP App panel's host is one such page. There the
128
+ * renderer is told to use Vega's interpreter instead, which evaluates the same
129
+ * expressions without compiling them. Asked once; elsewhere nothing changes.
130
+ *
131
+ * The probe is itself an eval. Under a CSP that refuses it, the browser fires
132
+ * one `securitypolicyviolation` per page load, and a policy with `report-uri`
133
+ * or `report-to` sends one violation report for it. That report is expected.
134
+ */
135
+ let evalAllowed: boolean | undefined;
136
+ export function pageAllowsEval(): boolean {
137
+ if (evalAllowed === undefined) {
138
+ try {
139
+ evalAllowed = new Function("return true")() === true;
140
+ } catch {
141
+ evalAllowed = false;
142
+ }
143
+ }
144
+ return evalAllowed;
145
+ }
146
+
124
147
  const createRenderer = async (
125
148
  theme: ResolvedTheme,
126
149
  onClick?: DrillBinding["onClick"],
@@ -137,6 +160,8 @@ const createRenderer = async (
137
160
  // which it reports only with `enableDrill` set; see `drillClickRelay`.
138
161
  ...(onDrill ? { onDrill, tableConfig: { enableDrill: true } } : {}),
139
162
  vegaConfigOverride: buildVegaThemeOverride(theme),
163
+ // Charts under a CSP that refuses eval; see `pageAllowsEval`.
164
+ ...(pageAllowsEval() ? {} : { useVegaInterpreter: true }),
140
165
  // Pass the explicit theme so table chrome and dashboard tiles
141
166
  // pick up the operator's colours directly. Without this the
142
167
  // renderer's own inline style writes `--malloy-render--*` values
@@ -0,0 +1,95 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ // The two props a host that is not a browser tab on the server needs: an
5
+ // `adapter` that carries the API calls some other way (an MCP App panel sends
6
+ // them through its host), and a `mode` the host decides.
7
+ //
8
+ // Isolated (see test/README.md): it renders the real ServerProvider, which a
9
+ // spec that ran mockServerProvider earlier in the same `bun test` replaces.
10
+
11
+ import { afterEach, expect, it } from "bun:test";
12
+ import { cleanup, render, waitFor } from "@testing-library/react";
13
+ import type { AxiosAdapter } from "axios";
14
+ import { usePublisherTheme } from "../theme/ThemeContext";
15
+ import { ServerProvider, useServer } from "./ServerProvider";
16
+
17
+ afterEach(cleanup);
18
+
19
+ function Probe({ onReady }: { onReady: (v: unknown) => void }) {
20
+ const { apiClients } = useServer();
21
+ const { mode } = usePublisherTheme();
22
+ return (
23
+ <button
24
+ data-mode={mode}
25
+ onClick={async () =>
26
+ onReady(
27
+ (await apiClients.reports.getReport("e", "p", "a/b.malloy"))
28
+ .data,
29
+ )
30
+ }
31
+ >
32
+ go
33
+ </button>
34
+ );
35
+ }
36
+
37
+ it("sends every API call through the adapter instead of HTTP", async () => {
38
+ const seen: { method?: string; url?: string }[] = [];
39
+ const adapter: AxiosAdapter = async (config) => {
40
+ seen.push({ method: config.method, url: config.url });
41
+ return {
42
+ data: config.url?.endsWith("/status")
43
+ ? { theme: {} }
44
+ : { title: "From the adapter" },
45
+ status: 200,
46
+ statusText: "OK",
47
+ headers: {},
48
+ config,
49
+ };
50
+ };
51
+ let answer: unknown;
52
+ const { getByText } = render(
53
+ <ServerProvider baseURL="http://host.invalid/api/v0" adapter={adapter}>
54
+ <Probe onReady={(v) => (answer = v)} />
55
+ </ServerProvider>,
56
+ );
57
+ getByText("go").click();
58
+ await waitFor(() => expect(answer).toEqual({ title: "From the adapter" }));
59
+ expect(seen).toContainEqual({
60
+ method: "get",
61
+ url: "/environments/e/packages/p/reports/a%2Fb.malloy",
62
+ });
63
+ });
64
+
65
+ it("a host's mode wins over the viewer's stored choice and the OS", async () => {
66
+ try {
67
+ window.localStorage.setItem("publisher:themeMode", "light");
68
+ } catch {
69
+ // A DOM without storage: the prop alone is under test then.
70
+ }
71
+ const adapter: AxiosAdapter = async (config) => ({
72
+ data: { theme: { defaultMode: "light" } },
73
+ status: 200,
74
+ statusText: "OK",
75
+ headers: {},
76
+ config,
77
+ });
78
+ const { getByText } = render(
79
+ <ServerProvider
80
+ baseURL="http://mode.invalid/api/v0"
81
+ adapter={adapter}
82
+ mode="dark"
83
+ >
84
+ <Probe onReady={() => undefined} />
85
+ </ServerProvider>,
86
+ );
87
+ await waitFor(() =>
88
+ expect(getByText("go").getAttribute("data-mode")).toBe("dark"),
89
+ );
90
+ try {
91
+ window.localStorage.removeItem("publisher:themeMode");
92
+ } catch {
93
+ // see above
94
+ }
95
+ });
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { QueryClientProvider, useQuery } from "@tanstack/react-query";
5
- import axios from "axios";
5
+ import axios, { type AxiosAdapter } from "axios";
6
6
  import React, {
7
7
  createContext,
8
8
  ReactNode,
@@ -143,11 +143,27 @@ export interface ServerProviderProps {
143
143
  * what tokens do not reach.
144
144
  */
145
145
  ui?: ReportUiOverrides;
146
+ /**
147
+ * Carry the SDK's API calls some other way than HTTP to `baseURL`: an
148
+ * axios adapter that receives each request (method, URL under `baseURL`,
149
+ * body) and answers it. For a host whose page cannot reach the server
150
+ * directly, such as an MCP App panel, which sends each call through the
151
+ * MCP host as a tool call. Omit for plain HTTP.
152
+ */
153
+ adapter?: AxiosAdapter;
154
+ /**
155
+ * Light or dark, decided by the host. When set, the viewer's own choice
156
+ * and the operating system's preference are not consulted, and nothing is
157
+ * stored. For a host with its own theme switch, such as an MCP host that
158
+ * tells its panels which theme it is in. Omit to let the viewer choose.
159
+ */
160
+ mode?: ThemeMode;
146
161
  }
147
162
 
148
163
  const getApiClients = (
149
164
  baseURL?: string,
150
165
  accessToken?: () => Promise<string>,
166
+ adapter?: AxiosAdapter,
151
167
  ) => {
152
168
  const basePath = `${window.location.protocol}//${window.location.host}/api/v0`;
153
169
 
@@ -156,6 +172,7 @@ const getApiClients = (
156
172
  baseURL: baseURL || basePath,
157
173
  withCredentials: true,
158
174
  timeout: 600000,
175
+ ...(adapter ? { adapter } : {}),
159
176
  });
160
177
 
161
178
  axiosInstance.interceptors.request.use(async (config) => {
@@ -210,10 +227,12 @@ const ServerProviderInner: React.FC<ServerProviderProps> = ({
210
227
  mutable: mutableProp,
211
228
  theme: themeProp,
212
229
  ui,
230
+ adapter,
231
+ mode: modeProp,
213
232
  }) => {
214
233
  const apiClients = useMemo(
215
- () => getApiClients(baseURL, getAccessToken),
216
- [baseURL, getAccessToken],
234
+ () => getApiClients(baseURL, getAccessToken, adapter),
235
+ [baseURL, getAccessToken, adapter],
217
236
  );
218
237
 
219
238
  const server =
@@ -300,12 +319,13 @@ const ServerProviderInner: React.FC<ServerProviderProps> = ({
300
319
  const effectiveUserChoice = allowUserToggle ? userChoice : undefined;
301
320
  const mode: ThemeMode = useMemo(
302
321
  () =>
322
+ modeProp ??
303
323
  resolveMode(
304
324
  instanceTheme?.defaultMode,
305
325
  effectiveUserChoice,
306
326
  prefersDark,
307
327
  ),
308
- [instanceTheme?.defaultMode, effectiveUserChoice, prefersDark],
328
+ [modeProp, instanceTheme?.defaultMode, effectiveUserChoice, prefersDark],
309
329
  );
310
330
 
311
331
  const value: ServerContextValue = {
@@ -325,7 +345,7 @@ const ServerProviderInner: React.FC<ServerProviderProps> = ({
325
345
  mode={mode}
326
346
  userChoice={effectiveUserChoice}
327
347
  setMode={setMode}
328
- allowUserToggle={allowUserToggle}
348
+ allowUserToggle={allowUserToggle && modeProp === undefined}
329
349
  {...(ui ? { ui } : {})}
330
350
  >
331
351
  {children}
package/test/README.md CHANGED
@@ -149,9 +149,11 @@ later spec sees, in file order. Nothing in Bun scopes it to a file. That is
149
149
  survivable only while every spec registers the same shape, which is why the
150
150
  stub lives in one place rather than being hand-rolled per file: a spec that
151
151
  inherits someone else's stub still gets `{ server, apiClients }`, and fails on
152
- a missing client rather than on a missing property of `undefined`. If you ever
153
- need a spec to see the REAL `ServerProvider`, it cannot share a process with
154
- these — that would need its own `bun test` invocation.
152
+ a missing client rather than on a missing property of `undefined`. A spec that
153
+ needs the REAL `ServerProvider` cannot share a process with these, so name it
154
+ `*.isolated.spec.tsx` and add its `./` path to the `test:isolated` script. The
155
+ `test` script leaves every `*.isolated.spec.*` out of the main run, so one that
156
+ is not listed in `test:isolated` does not run at all.
155
157
 
156
158
  `serverWrapper` provides `globalQueryClient`, the same instance `ServerProvider`
157
159
  provides in production. It is not decoration: `useQueryWithApiError` passes that