@holistics/anfra-sdk 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,7 +21,10 @@ The package root exports nothing; each entrypoint is for a different side of a D
21
21
  | Entrypoint | For | Holds |
22
22
  |---|---|---|
23
23
  | `@holistics/anfra-sdk/app` | a Data App definition, in its frame | the **app runtime** (`createApp`, queries, controls, cross-filters, results and state), and the **frame bootstrap** that provisions it from its host |
24
- | `@holistics/anfra-sdk/host` | the page hosting a Data App | provisioning its frame, mounting it sandboxed, and answering its calls over the **bridge** |
24
+ | `@holistics/anfra-sdk/host` | the page hosting a Data App | the **host runtime**: the plugins and middleware a page installs, provisioning each frame, mounting it sandboxed, and answering its calls over the **bridge**; `definePlugin` for a plugin of your own |
25
+ | `@holistics/anfra-sdk/plugins` | the page hosting a Data App | anfra's own **plugins**: `core` (queries), `export`, `lineage`, `render`, `inspect` |
26
+ | `@holistics/anfra-sdk/build` | a plugin's build, in Node | `buildFrameHalf`: a plugin's frame half as the script a host provisions |
27
+ | `@holistics/anfra-sdk/testing` | a plugin's tests | `testFrame`: a frame half run on the real kernel against a stand-in host |
25
28
  | `@holistics/anfra-sdk/api` | the host's page, scripts, tests | a client for the core API, generated from anfra's spec, and a **Backend** over it |
26
29
  | `@holistics/anfra-sdk/common` | all of the above | the contract they share: types, error classes, the bridge's messages |
27
30
 
@@ -44,10 +47,19 @@ app.subscribe(() => render(byRegion.result));
44
47
  await app.execute();
45
48
  ```
46
49
 
47
- A reader can download a query's whole result, with the inputs its result on screen was run with:
50
+ Everything beyond queries comes from a **plugin** the host installed, which adds its API under its
51
+ own name (`query.export`, `Anfra.render`, `Anfra.lineage`). Where the host didn't install it, the
52
+ member isn't there: check `Anfra.plugins.has(name)` before using an optional one.
53
+
54
+ Data Apps written before plugins read `Anfra.features.export` (`.render`, `.lineage`). It still
55
+ answers, from the installed plugins, but it is deprecated and warns in the console: replace it with
56
+ `Anfra.plugins.has('export')`. It goes in the next breaking release.
57
+
58
+ A reader can download a query's whole result, with the inputs its result on screen was run with
59
+ (the `export` plugin):
48
60
 
49
61
  ```js
50
- if (Anfra.features.export && Anfra.user.permissions.canExportData) {
62
+ if (Anfra.plugins.has('export') && Anfra.user.permissions.canExportData) {
51
63
  button.onclick = () => byRegion.export().catch((err) => showError(err.message));
52
64
  }
53
65
  ```
@@ -55,22 +67,24 @@ if (Anfra.features.export && Anfra.user.permissions.canExportData) {
55
67
  `export()` resolves once the file is made and the host has started saving it, with its link and
56
68
  `rowCount`. The file is a CSV named after the app and the query unless you pass `filename`.
57
69
 
58
- A reader can download a picture of the app, or of one block or container, as they see it:
70
+ A reader can download a picture of the app, or of one block or container, as they see it (the
71
+ `render` plugin):
59
72
 
60
73
  ```js
61
74
  await Anfra.render({ block: 'trend', format: 'png' }); // or 'pdf'; no node: the whole app
62
75
  ```
63
76
 
64
- It works only where the host turned rendering on (`mountDataApp({ render: true })`; `anfra serve`
65
- does). Check `Anfra.features.render` and `Anfra.user.permissions.canExportData` before offering it, and
77
+ It works only where the host installed `render` (`anfra serve` does). Check
78
+ `Anfra.plugins.has('render')` and `Anfra.user.permissions.canExportData` before offering it, and
66
79
  mark what shouldn't be drawn (the download button itself) `data-anfra-render="skip"`. Serve images
67
80
  and web fonts with CORS: an image without it is left blank (listed in the result's `omitted`), a
68
81
  font without it falls back.
69
82
 
70
83
  `Anfra.datasets` describes what there is to query. For TypeScript, `@holistics/anfra-sdk/ambient` declares the
71
- global.
84
+ global. A plugin's members are typed as optional: check the member itself (`if (Anfra.render)`,
85
+ `query.export?.()`), which narrows it.
72
86
 
73
- `Anfra.lineage({ parent: 'orders', child: 'amount' })` traces fields through the repo's catalog, each named
87
+ `Anfra.lineage({ parent: 'orders', child: 'amount' })` (the `lineage` plugin) traces fields through the repo's catalog, each named
74
88
  by its parent and its name in it: what each is built from, as a diagram to draw (`results[i].diagram`), or
75
89
  why it could not be (`results[i].error`). It reads the catalog the host last ingested (`anfra ingest`).
76
90
 
@@ -97,33 +111,83 @@ inspects, and never thrown over: a wrong name or a block inside a block is repor
97
111
 
98
112
  ```ts
99
113
  import { coreApiBackend, coreClient, loadDatasets } from '@holistics/anfra-sdk/api';
100
- import { mountDataApp } from '@holistics/anfra-sdk/host';
114
+ import { createHost } from '@holistics/anfra-sdk/host';
115
+ import {
116
+ corePlugin, exportPlugin, inspectPlugin, lineagePlugin, renderPlugin,
117
+ } from '@holistics/anfra-sdk/plugins';
101
118
 
102
119
  const client = coreClient('/api'); // the core API, on whichever server serves it
103
120
  const { datasets } = await loadDatasets(client); // every dataset, through core.show
121
+ const backend = coreApiBackend(client, { datasets }); // queries, suggestions, exports and lineage, as core ops
122
+
123
+ const host = createHost({ // one per page
124
+ plugins: [
125
+ corePlugin(backend), // required: runs the queries
126
+ exportPlugin(backend), // query.export()
127
+ lineagePlugin(backend), // Anfra.lineage()
128
+ renderPlugin(), // Anfra.render(): the host saves PNGs and PDFs the frame makes
129
+ inspectPlugin(), // what an inspect panel needs
130
+ ],
131
+ });
104
132
 
105
- const mounted = mountDataApp({
133
+ const mounted = host.mount({
106
134
  container: document.querySelector('#data-app')!,
107
135
  definition: await (await fetch('/appserve/files/sales/overview.html')).text(),
108
136
  baseHref: '/appserve/files/sales/', // where its relative URLs resolve
109
137
  datasets,
110
138
  user,
111
- backend: coreApiBackend(client, { datasets }), // queries, field suggestions and exports, as core ops; lineage as core.lineage
112
- render: true, // let it save PNGs and PDFs of itself (off by default)
113
139
  });
114
- // mounted.setInspecting(true) to receive inspection snapshots; mounted.render({ format: 'pdf' }) to
115
- // save a picture of the app (needs render: true); mounted.unmount() when done.
140
+ await mounted.call('render.draw', { format: 'pdf' }); // save a picture of the app
141
+ mounted.on('inspect.snapshot', ({ apps, structure }) => …);
142
+ await mounted.call('inspect.watch', true); // start the snapshots
143
+ mounted.unmount(); // when done
144
+ ```
145
+
146
+ `host.mount` puts the definition in an iframe with `sandbox="allow-scripts"`, as its `srcdoc`, with
147
+ the frame's kernel, the provisioned data and each plugin's frame setup ahead of it. Every call the
148
+ frame makes, and every call a plugin makes of another, goes through the host's one pipeline to the
149
+ plugin that answers it. An export's file is saved from the host's page, by following its link: the
150
+ frame can't download.
151
+
152
+ ### Middleware
153
+
154
+ Middleware wraps calls by name (`*`, `core.*`, `core.submitQuery`), in order of `stage`, then name:
155
+
156
+ ```ts
157
+ createHost({
158
+ plugins,
159
+ middleware: [{
160
+ name: 'log',
161
+ match: '*',
162
+ handle: async (request, call, next) => {
163
+ const started = Date.now();
164
+ try { return await next(request); } finally { console.log(call.name, call.caller, Date.now() - started); }
165
+ },
166
+ }],
167
+ });
116
168
  ```
117
169
 
118
- `mountDataApp` puts the definition in an iframe with `sandbox="allow-scripts"`, as its `srcdoc`,
119
- with the frame bootstrap and the provisioned data ahead of it. The bootstrap's Backend forwards each call to the host over postMessage; the host answers it with the Backend it was given. An export's file is saved from the host's page, by following its link: the frame can't download. A Backend without `exportQuery` makes a host that can't export, and its frames see `Anfra.features.export` false; likewise a Backend without `lineage`, and `Anfra.features.lineage`.
170
+ It may change the request, answer in the plugin's place (not calling `next`), refuse (throwing), or
171
+ change the answer. `call.caller` says who made the call: the frame, the host, or another plugin;
172
+ `call.origin` who started it, through any plugins between (`call.chain`). Count what the frame
173
+ started by `origin`: a query a plugin runs for the frame's request has the plugin as its `caller`.
174
+ A handler forwarding a call or request the frame chose makes it with `{ asOrigin: true }`, so it
175
+ is refused if the frame couldn't make it itself.
176
+
177
+ ### A plugin of your own
178
+
179
+ A plugin adds a feature to the Data Apps on your host, such as a call from the frame to your
180
+ server. Make one with `definePlugin`, build its frame half with `@holistics/anfra-sdk/build`, and
181
+ test it with `@holistics/anfra-sdk/testing`. The guide, with a worked example, is
182
+ [docs/usage/sdk-plugins.md](../../docs/usage/sdk-plugins.md); the design is
183
+ [docs/designs/sdk-plugins.md](../../docs/designs/sdk-plugins.md).
120
184
 
121
185
  ## The boundary
122
186
 
123
187
  A Data App definition can come from any author, often an agent, which may not think of security while building an analysis. So the SDK guards it for its author, and makes the safe way the easy one:
124
188
 
125
189
  - Its frame has an opaque origin. Its own requests to the API are cross-origin, which `anfra serve` refuses, and carry no credentials on a platform that has them.
126
- - The bridge answers only the Backend's methods, `submitQuery`, `fieldSuggestions`, `exportQuery` and the optional `lineage`, and the two a rendering needs, the renderer's code and saving its file. Nothing else of the API is reachable from a frame.
190
+ - The frame reaches only the calls its host's plugins let it make (`frame: true`); every other call is the host's. Nothing else of the API is reachable from a frame.
127
191
  - `@holistics/anfra-sdk/app` imports only `common`: the script injected into a frame carries no API client. A test on the built frame script holds this.
128
192
 
129
193
  ## Development
@@ -131,7 +195,7 @@ A Data App definition can come from any author, often an agent, which may not th
131
195
  From the repository root, after `pnpm install`:
132
196
 
133
197
  ```sh
134
- pnpm build:sdk # dist/{common,app,host,api}.js, with the frame script built into host
198
+ pnpm build:sdk # dist/{common,app,host,plugins,api,build,testing}.js, with the frame script built into host and the plugins' into plugins
135
199
  pnpm dev:sdk # the same, rebuilt on change
136
200
  pnpm test:sdk # vitest
137
201
  ```
package/dist/api.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Client } from 'openapi-fetch';
2
- import { aj as paths, D as DatasetDescriptor, B as Backend, f as BackendExportRequest, ak as components, i as BackendQueryRequest } from './types-DznT0m7F.js';
2
+ import { ak as paths, D as DatasetDescriptor, B as Backend, f as BackendExportRequest, al as components, i as BackendQueryRequest } from './types-plgahUrN.js';
3
3
  import { D as DataAppError } from './errors-CKvqVaqU.js';
4
4
 
5
5
  /** The core API, typed from anfra core's spec (`api/openapi.yaml`, generated into `schema.d.ts`). */
package/dist/api.js CHANGED
@@ -2,7 +2,8 @@ import {
2
2
  PermissionError,
3
3
  QueryError,
4
4
  TransportError
5
- } from "./chunk-KBXITYQK.js";
5
+ } from "./chunk-KCTLO3CO.js";
6
+ import "./chunk-PKBMQBKP.js";
6
7
 
7
8
  // src/api/client.ts
8
9
  import createClient from "openapi-fetch";
@@ -43,6 +44,42 @@ function toSdkError(status, body) {
43
44
  }
44
45
  }
45
46
 
47
+ // src/api/stream.ts
48
+ async function readEvents(body, onEvent) {
49
+ const reader = body.getReader();
50
+ const decoder = new TextDecoder();
51
+ let buffered = "";
52
+ const line = (text) => {
53
+ if (!text.trim()) return false;
54
+ const event = JSON.parse(text);
55
+ if (event.type === "ping") return false;
56
+ if (event.type === "end") {
57
+ const end = event;
58
+ if (end.status === "failed") throw toSdkError(end.error?.status ?? 500, end.error);
59
+ return true;
60
+ }
61
+ onEvent(event);
62
+ return false;
63
+ };
64
+ try {
65
+ for (; ; ) {
66
+ const { value, done } = await reader.read();
67
+ if (done) break;
68
+ buffered += decoder.decode(value, { stream: true });
69
+ let start = 0;
70
+ for (let newline = buffered.indexOf("\n"); newline >= 0; newline = buffered.indexOf("\n", start)) {
71
+ if (line(buffered.slice(start, newline))) return;
72
+ start = newline + 1;
73
+ }
74
+ buffered = buffered.slice(start);
75
+ }
76
+ if (line(buffered + decoder.decode())) return;
77
+ } finally {
78
+ reader.releaseLock();
79
+ }
80
+ throw new TransportError("The connection to the server was cut before the answer ended.");
81
+ }
82
+
46
83
  // src/api/backend.ts
47
84
  var SUGGESTION_LIMIT = 100;
48
85
  function isAbort(err) {
@@ -93,8 +130,40 @@ async function callCoreAPI(call) {
93
130
  if (!data) throw toSdkError(response.status, error?.error);
94
131
  return data;
95
132
  }
96
- function runQuery(client, body, signal) {
97
- return callCoreAPI(() => client.POST("/core.query", { body, signal }));
133
+ async function runQuery(client, body, signal) {
134
+ const stream = await callCoreAPI(() => client.POST("/core.query", {
135
+ body,
136
+ signal,
137
+ parseAs: "stream",
138
+ headers: { Accept: "application/x-ndjson" }
139
+ }));
140
+ if (!stream) throw new TransportError("The server answered the query with no body.");
141
+ const result = { sql: "", columns: [], result: { fields: [], records: [] }, has_more: false, timings: { steps: [], end_ms: 0 } };
142
+ try {
143
+ await readEvents(stream, (event) => {
144
+ switch (event.type) {
145
+ case "compiled":
146
+ result.sql = event.sql;
147
+ if (event.aql) result.aql = event.aql;
148
+ break;
149
+ case "header":
150
+ result.columns = event.columns;
151
+ result.result.fields = event.fields;
152
+ break;
153
+ case "rows":
154
+ for (const row of event.records) result.result.records.push(row);
155
+ break;
156
+ case "summary":
157
+ result.has_more = event.has_more;
158
+ result.timings = event.timings;
159
+ break;
160
+ }
161
+ });
162
+ } catch (err) {
163
+ if (isAbort(err) || !(err instanceof Error) || err.name !== "TypeError") throw err;
164
+ throw new TransportError(`The connection to the server failed: ${err.message}`);
165
+ }
166
+ return result;
98
167
  }
99
168
  function coreApiBackend(base, options = {}) {
100
169
  const client = typeof base === "string" ? coreClient(base) : base;
@@ -106,13 +175,17 @@ function coreApiBackend(base, options = {}) {
106
175
  columns: toColumns(data.columns),
107
176
  values,
108
177
  meta: {
109
- ...request.pageSize !== void 0 ? { page: request.page ?? 1, pageSize: request.pageSize } : {},
178
+ ...request.pageSize !== void 0 ? { page: request.page ?? 1, pageSize: request.pageSize, hasMore: data.has_more } : {},
110
179
  numRows: values.length
111
180
  },
112
181
  debug: {
113
182
  ...data.aql ? { executedAql: data.aql } : {},
114
183
  executedSql: data.sql,
115
184
  fromCache: false,
185
+ timings: {
186
+ steps: data.timings.steps.map((s) => ({ step: s.step, startMs: s.start_ms })),
187
+ endMs: data.timings.end_ms
188
+ },
116
189
  executedAt: /* @__PURE__ */ new Date()
117
190
  }
118
191
  };