@makoai/app-sdk 2.2.0 → 2.4.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.
package/README.md CHANGED
@@ -19,8 +19,25 @@ const { data, loading, error } = useQuery("latest_sales");
19
19
  // Analytical SQL over every binding (DuckDB-WASM in the browser; table
20
20
  // names are binding names).
21
21
  const totals = useDuckDB("select country, sum(revenue) r from latest_sales group by 1");
22
+
23
+ // Rematerialize on demand: re-runs the binding's query on the warehouse,
24
+ // then every hook reading it re-renders with the new rows. The old rows
25
+ // stay on screen while `refreshing` is true.
26
+ const { refresh, refreshing } = useQuery("latest_sales");
27
+ <button onClick={() => refresh().catch(e => alert(e.message))} disabled={refreshing}>
28
+ Refresh
29
+ </button>
22
30
  ```
23
31
 
32
+ `useDuckDB(...).refresh()` refreshes every binding; `refreshBinding(name)` /
33
+ `refreshBindings()` do the same outside a component. A refresh POSTs to
34
+ `__data/<name>/refresh`, the data URL's sibling, so whoever serves the app's
35
+ data (Mako, the sandbox dev server, the Vite plugin below) rebuilds it with
36
+ its own authorization: a signed-in member can always refresh; a public share
37
+ only when its owner enabled live queries, and at most once every few minutes
38
+ per binding. A refused refresh rejects with `status` (403, 429 + `retryAfterMs`)
39
+ or 502 with the query's error.
40
+
24
41
  `useLocation` / `useSearchParams` / `navigate` keep filter state in the URL;
25
42
  `useTheme` follows the OS preference. Theme tokens (`--background`,
26
43
  `--chart-1`, …) match the ones the scaffold's `styles.css` declares.
@@ -28,6 +45,48 @@ const totals = useDuckDB("select country, sum(revenue) r from latest_sales group
28
45
  Data arrives from `__data/<name>.parquet`, relative to the page — the same
29
46
  path in Mako's sandbox, in a published app, and on a laptop.
30
47
 
48
+ ### Who is looking: `useViewer()`
49
+
50
+ ```tsx
51
+ import { useViewer } from "@makoai/app-sdk";
52
+
53
+ const { viewer, loading } = useViewer();
54
+ // viewer === null → anonymous share link (or still loading)
55
+ // viewer.email → "sam@acme.com"
56
+ // viewer.workspace.role → "owner" | "admin" | "member" | "viewer" | null
57
+ // viewer.app.role → "owner" | "editor" | "viewer" | null
58
+ ```
59
+
60
+ Mako resolves the viewer server-side from the session or the signed view
61
+ token — the page cannot forge it — and reports only what the platform
62
+ knows: identity, the workspace and the person's **access** role in it, and
63
+ their role on this app. There is no job title, team or country in the
64
+ platform, on purpose: those are your data. Put a roster in a binding and
65
+ join on the email:
66
+
67
+ ```sql
68
+ -- bindings/viewers.sql
69
+ SELECT lower(email) AS email, team, country, is_lead FROM hr.people
70
+ ```
71
+
72
+ ```tsx
73
+ const { viewer } = useViewer();
74
+ const me = useDuckDB(
75
+ viewer ? `select * from viewers where email = '${viewer.email.replace(/'/g, "''")}'` : "select 1 where false",
76
+ );
77
+ const board = useDuckDB(
78
+ me.data?.[0]?.is_lead
79
+ ? "select * from pipeline"
80
+ : `select * from pipeline where team = '${me.data?.[0]?.team ?? ""}'`,
81
+ );
82
+ ```
83
+
84
+ Keep the roster binding to the columns the app needs for its logic: every
85
+ binding the app can read is downloaded whole into the viewer's browser, so
86
+ this shapes the UI rather than enforcing access. Who may *open* the app is
87
+ the app's access setting in Mako; server-side row filtering is a follow-up
88
+ on the same identity (apps.md §28).
89
+
31
90
  ## In `vite.config.ts`
32
91
 
33
92
  ```ts
@@ -39,11 +98,16 @@ export default defineConfig({ plugins: [react(), makoData()] });
39
98
  `makoData()` answers `__data/index.json` (the app's `bindings/*.sql`) and
40
99
  `__data/<name>.parquet` during `vite dev` by streaming each binding's
41
100
  materialized artifact from the Mako API — a binding that was never
42
- materialized is built on first request. Results are cached under
101
+ materialized is built on first request, and `POST __data/<name>/refresh`
102
+ (the SDK's `refresh()`) rebuilds one on demand. Results are cached under
43
103
  `node_modules/.mako-data/` for five minutes (`?refresh` bypasses; a stale
44
104
  copy is served if the API is unreachable). It is `apply: "serve"` only —
45
105
  production builds never load it.
46
106
 
107
+ It also answers `__data/viewer.json` (you, as Mako sees you), and
108
+ `MAKO_VIEWER_AS=<email>` — in the environment or the repo's `.env` —
109
+ previews the app as that member instead (editors of the app only).
110
+
47
111
  Credentials, in order: `MAKO_API_URL` / `MAKO_API_KEY` in the environment,
48
112
  then in the repo-root `.env`. The workspace id comes from
49
113
  `.mako/workspace.json` (or `MAKO_WORKSPACE_ID`). Without a key the app runs
package/credentials.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ /** The hosted Mako API — the default wherever nothing overrides it. */
2
+ export const HOSTED_API_URL: string;
3
+
1
4
  export const CREDENTIALS_PATH: string;
2
5
 
3
6
  export interface StoredCredential {
package/credentials.js CHANGED
@@ -11,6 +11,10 @@ import fs from "node:fs";
11
11
  import os from "node:os";
12
12
  import path from "node:path";
13
13
 
14
+ /** The hosted Mako API — the default wherever nothing overrides it
15
+ * (MAKO_API_URL, .env, .mako/workspace.json apiUrl, or an explicit option). */
16
+ export const HOSTED_API_URL = "https://app.mako.ai";
17
+
14
18
  export const CREDENTIALS_PATH =
15
19
  process.env.MAKO_CREDENTIALS_FILE ||
16
20
  path.join(os.homedir(), ".mako", "credentials.json");
package/index.d.ts CHANGED
@@ -1,10 +1,37 @@
1
1
  import type * as React from "react";
2
2
 
3
+ /** What a refresh built — the server's answer to `POST __data/<name>/refresh`. */
4
+ export interface RefreshResult {
5
+ binding: string;
6
+ /** "live" bindings have no artifact; the refresh just re-fetched them. */
7
+ materialization: "parquet" | "live";
8
+ rowCount?: number;
9
+ byteSize?: number;
10
+ /** ISO 8601; absent for a live binding. */
11
+ materializedAt?: string;
12
+ }
13
+
14
+ /** Why a refresh was refused or failed. */
15
+ export interface RefreshError extends Error {
16
+ /** 403: not allowed here; 404: no such binding; 429: refreshed too recently; 502: the query failed. */
17
+ status?: number;
18
+ /** With 429: how long until the next refresh is accepted. */
19
+ retryAfterMs?: number;
20
+ }
21
+
3
22
  export interface QueryState<Row = Record<string, unknown>> {
4
23
  data: Row[] | null;
5
24
  error: string | null;
25
+ /** First load (or a new query): no rows yet. */
6
26
  loading: boolean;
27
+ /** A refresh is in flight; `data` still holds the previous rows. */
28
+ refreshing: boolean;
7
29
  truncated: boolean;
30
+ /**
31
+ * Rematerialize the data behind this query and re-run it. Rejects with a
32
+ * `RefreshError` — the rows on screen are untouched when it does.
33
+ */
34
+ refresh: () => Promise<RefreshResult | RefreshResult[]>;
8
35
  }
9
36
  export interface DuckDBState<Row = Record<string, unknown>>
10
37
  extends QueryState<Row> {
@@ -26,13 +53,63 @@ export interface MakoLocation {
26
53
  export function useQuery<Row = Record<string, unknown>>(
27
54
  name: string,
28
55
  opts?: QueryOptions,
29
- ): QueryState<Row>;
56
+ ): QueryState<Row> & { refresh: () => Promise<RefreshResult> };
30
57
 
31
58
  /** Analytical SQL over the app's bindings; table names are binding names. */
32
59
  export function useDuckDB<Row = Record<string, unknown>>(
33
60
  sql: string,
34
61
  opts?: QueryOptions,
35
- ): DuckDBState<Row>;
62
+ ): DuckDBState<Row> & { refresh: () => Promise<RefreshResult[]> };
63
+
64
+ /**
65
+ * Rematerialize one binding on demand and reload it everywhere it is used.
66
+ * Concurrent calls for the same binding share one request.
67
+ */
68
+ export function refreshBinding(name: string): Promise<RefreshResult>;
69
+
70
+ /**
71
+ * Refresh several bindings — all of them when `names` is omitted. Every one
72
+ * is attempted; rejects after they settle if any failed (`failures` lists
73
+ * them).
74
+ */
75
+ export function refreshBindings(
76
+ names?: string[],
77
+ ): Promise<RefreshResult[]>;
78
+
79
+ /**
80
+ * The person viewing the app, as Mako resolved them from the session or the
81
+ * signed view token (apps.md §28). Only what the platform knows: identity,
82
+ * the workspace and their ACCESS role in it, their role on this app. Look
83
+ * up anything else (team, territory, …) in the warehouse by `email`.
84
+ */
85
+ export interface Viewer {
86
+ id: string;
87
+ /** Signed-in email, lowercased. */
88
+ email: string;
89
+ workspace: {
90
+ id: string;
91
+ name: string;
92
+ /** Access role in the workspace; null when not a member. */
93
+ role: "owner" | "admin" | "member" | "viewer" | null;
94
+ };
95
+ app: {
96
+ id: string;
97
+ slug: string | null;
98
+ /** What they may do to this app. */
99
+ role: "owner" | "editor" | "viewer" | null;
100
+ };
101
+ }
102
+ export interface ViewerState {
103
+ /** null while loading, on an anonymous share, or on an older server. */
104
+ viewer: Viewer | null;
105
+ loading: boolean;
106
+ error: string | null;
107
+ }
108
+
109
+ /** Who is looking. The app decides what that means for its UI and data. */
110
+ export function useViewer(): ViewerState;
111
+ /** The same, outside a component; resolved once per page. */
112
+ export function getViewer(): Promise<Viewer | null>;
36
113
 
37
114
  export function useTheme(): { theme: "light" | "dark" };
38
115
  export function useLocation(): MakoLocation;
package/index.js CHANGED
@@ -23,38 +23,210 @@ function getDb() {
23
23
  return dbPromise;
24
24
  }
25
25
 
26
+ // The server answers failures with JSON { error, hint, retryAfterMs } —
27
+ // show that, not a bare status code (and never let it reach DuckDB, where it
28
+ // would surface as a baffling Catalog Error).
29
+ async function responseError(res, what) {
30
+ let body = null;
31
+ try {
32
+ body = await res.json();
33
+ } catch {
34
+ /* not JSON (e.g. a published build with no artifact) */
35
+ }
36
+ const detail = body ? [body.error, body.hint].filter(Boolean).join(" — ") : "";
37
+ const error = new Error(what + " (HTTP " + res.status + ")" + (detail ? ": " + detail : ""));
38
+ error.status = res.status;
39
+ if (body && typeof body.retryAfterMs === "number") error.retryAfterMs = body.retryAfterMs;
40
+ return error;
41
+ }
42
+
43
+ async function loadBinding(name, bust) {
44
+ const res = await fetch(
45
+ "__data/" + encodeURIComponent(name) + ".parquet" + (bust ? "?refresh=" + Date.now() : ""),
46
+ );
47
+ if (!res.ok) {
48
+ throw await responseError(res, 'Data for binding "' + name + '" could not be loaded');
49
+ }
50
+ const buf = new Uint8Array(await res.arrayBuffer());
51
+ const db = await getDb();
52
+ if (bust) await db.dropFile(name + ".parquet").catch(() => {});
53
+ await db.registerFileBuffer(name + ".parquet", buf);
54
+ const conn = await db.connect();
55
+ try {
56
+ // A view per binding so SQL can name tables by binding name.
57
+ await conn.query(
58
+ 'CREATE OR REPLACE VIEW "' + name.replace(/"/g, '""') +
59
+ "\" AS SELECT * FROM read_parquet('" + name + ".parquet')",
60
+ );
61
+ } finally {
62
+ await conn.close();
63
+ }
64
+ }
65
+
26
66
  const registered = new Map(); // name -> Promise<void>
27
67
  function registerBinding(name) {
28
68
  if (!registered.has(name)) {
29
- registered.set(
30
- name,
31
- (async () => {
32
- const res = await fetch("__data/" + encodeURIComponent(name) + ".parquet");
33
- if (!res.ok) {
34
- registered.delete(name);
35
- throw new Error(
36
- 'Binding "' + name + '" is not materialized (HTTP ' + res.status + ")",
37
- );
38
- }
39
- const buf = new Uint8Array(await res.arrayBuffer());
40
- const db = await getDb();
41
- await db.registerFileBuffer(name + ".parquet", buf);
42
- const conn = await db.connect();
43
- try {
44
- // A view per binding so SQL can name tables by binding name.
45
- await conn.query(
46
- 'CREATE OR REPLACE VIEW "' + name.replace(/"/g, '""') +
47
- "\" AS SELECT * FROM read_parquet('" + name + ".parquet')",
48
- );
49
- } finally {
50
- await conn.close();
51
- }
52
- })(),
53
- );
69
+ const load = loadBinding(name, false);
70
+ registered.set(name, load);
71
+ load.catch(() => registered.delete(name));
54
72
  }
55
73
  return registered.get(name);
56
74
  }
57
75
 
76
+ /** Replace a binding's loaded bytes with what the server has now. */
77
+ async function reloadBinding(name) {
78
+ // Let a load in flight settle first, or its (older) bytes could land after
79
+ // the fresh ones and win.
80
+ const previous = registered.get(name);
81
+ if (previous) await previous.catch(() => {});
82
+ const load = loadBinding(name, true);
83
+ registered.set(name, load);
84
+ try {
85
+ await load;
86
+ } catch (error) {
87
+ registered.delete(name);
88
+ throw error;
89
+ }
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Refresh — rematerialize a binding on demand. The runtime POSTs to the
94
+ // data URL's sibling, `__data/<name>/refresh`, and every server that answers
95
+ // `__data/<name>.parquet` (Mako's viewer, preview and share routes, the
96
+ // sandbox dev server, the laptop Vite plugin) rebuilds the binding behind
97
+ // it, with its own authorization. The runtime then reloads the bytes and
98
+ // bumps a version every query hook depends on, so the page re-renders with
99
+ // the new rows — and keeps the old ones on screen until they arrive.
100
+ // ---------------------------------------------------------------------------
101
+ const bindingListeners = new Set();
102
+ let bindingState = { version: 0, refreshing: new Set() };
103
+ function setBindingState(next) {
104
+ bindingState = next;
105
+ for (const l of [...bindingListeners]) l();
106
+ }
107
+ function subscribeBindings(l) {
108
+ bindingListeners.add(l);
109
+ return () => bindingListeners.delete(l);
110
+ }
111
+ function getBindingState() {
112
+ return bindingState;
113
+ }
114
+ function useBindingState() {
115
+ return React.useSyncExternalStore(subscribeBindings, getBindingState, getBindingState);
116
+ }
117
+
118
+ const refreshes = new Map(); // name -> Promise<RefreshResult>
119
+
120
+ /**
121
+ * Rebuild one binding's data and reload it. Resolves with what the server
122
+ * built; rejects with an Error carrying `status` (403: not allowed here,
123
+ * 429: refreshed too recently — see `retryAfterMs`, 502: the query failed —
124
+ * the message says why). Concurrent calls for the same binding share one
125
+ * request.
126
+ */
127
+ export function refreshBinding(name) {
128
+ const pending = refreshes.get(name);
129
+ if (pending) return pending;
130
+ const run = (async () => {
131
+ const res = await fetch("__data/" + encodeURIComponent(name) + "/refresh", { method: "POST" });
132
+ if (!res.ok) {
133
+ throw await responseError(res, 'Binding "' + name + '" could not be refreshed');
134
+ }
135
+ const body = await res.json();
136
+ await reloadBinding(name);
137
+ setBindingState({ ...bindingState, version: bindingState.version + 1 });
138
+ return {
139
+ binding: name,
140
+ materialization: body.materialization,
141
+ rowCount: body.rowCount,
142
+ byteSize: body.byteSize,
143
+ materializedAt: body.materializedAt,
144
+ };
145
+ })();
146
+ refreshes.set(name, run);
147
+ setBindingState({ ...bindingState, refreshing: new Set([...bindingState.refreshing, name]) });
148
+ run
149
+ .finally(() => {
150
+ refreshes.delete(name);
151
+ const refreshing = new Set(bindingState.refreshing);
152
+ refreshing.delete(name);
153
+ setBindingState({ ...bindingState, refreshing });
154
+ })
155
+ .catch(() => {
156
+ /* the caller's copy of `run` carries the rejection */
157
+ });
158
+ return run;
159
+ }
160
+
161
+ /**
162
+ * Refresh several bindings at once — every staged binding when no names are
163
+ * given (what `useDuckDB(...).refresh()` does). All of them are attempted;
164
+ * if any failed, rejects after the rest settle with `failures` listing them.
165
+ */
166
+ export async function refreshBindings(names) {
167
+ const list = names ?? (await bindingIndex());
168
+ const settled = await Promise.allSettled(list.map(refreshBinding));
169
+ const failures = settled
170
+ .map((s, i) => (s.status === "rejected" ? { binding: list[i], error: s.reason } : null))
171
+ .filter(Boolean);
172
+ if (failures.length) {
173
+ const error = new Error(
174
+ failures.map(f => (f.error instanceof Error ? f.error.message : String(f.error))).join("; "),
175
+ );
176
+ error.failures = failures;
177
+ throw error;
178
+ }
179
+ return settled.map(s => s.value);
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // Viewer — who is looking. `__data/viewer.json` is answered per request by
184
+ // whoever serves the app (Mako's published/preview routes from the session
185
+ // or the signed token, the Vite plugin from the API), so the app cannot
186
+ // forge it. `null` on an anonymous share link, and on servers that predate
187
+ // it (404). Mako says only what it knows: id, email, the workspace and the
188
+ // person's ACCESS role in it, their role on this app. Anything else about
189
+ // the person is data the app looks up in the warehouse by email.
190
+ // ---------------------------------------------------------------------------
191
+ let viewerPromise = null;
192
+ function normalizeViewer(body) {
193
+ if (!body || typeof body !== "object" || typeof body.email !== "string") return null;
194
+ const ws = body.workspace && typeof body.workspace === "object" ? body.workspace : {};
195
+ const app = body.app && typeof body.app === "object" ? body.app : {};
196
+ return {
197
+ id: typeof body.id === "string" ? body.id : "",
198
+ email: body.email,
199
+ workspace: {
200
+ id: typeof ws.id === "string" ? ws.id : "",
201
+ name: typeof ws.name === "string" ? ws.name : "",
202
+ role: typeof ws.role === "string" ? ws.role : null,
203
+ },
204
+ app: {
205
+ id: typeof app.id === "string" ? app.id : "",
206
+ slug: typeof app.slug === "string" ? app.slug : null,
207
+ role: typeof app.role === "string" ? app.role : null,
208
+ },
209
+ };
210
+ }
211
+
212
+ /** The viewer, once per page. Resolves to null when nobody is known. */
213
+ export function getViewer() {
214
+ viewerPromise ??= fetch("__data/viewer.json").then(async r => {
215
+ if (r.status === 404) return null;
216
+ const body = await r.json().catch(() => null);
217
+ if (!r.ok) {
218
+ throw new Error(
219
+ body && body.error ? String(body.error) : "Viewer lookup failed (HTTP " + r.status + ")",
220
+ );
221
+ }
222
+ return normalizeViewer(body);
223
+ });
224
+ viewerPromise.catch(() => {
225
+ viewerPromise = null;
226
+ });
227
+ return viewerPromise;
228
+ }
229
+
58
230
  /** Names of every staged binding — written by the dev server next to the
59
231
  * parquet files. Absent (older servers, published builds): empty list. */
60
232
  let indexPromise = null;
@@ -116,38 +288,40 @@ async function runSql(sql, rowLimit) {
116
288
  }
117
289
  }
118
290
 
119
- function useAsyncQuery(run, deps) {
120
- const [state, setState] = React.useState({
121
- data: null,
122
- fields: null,
123
- error: null,
124
- loading: true,
125
- truncated: false,
126
- rowCount: null,
127
- });
291
+ const EMPTY = {
292
+ data: null,
293
+ fields: null,
294
+ error: null,
295
+ loading: true,
296
+ truncated: false,
297
+ rowCount: null,
298
+ refreshing: false,
299
+ };
300
+
301
+ // Runs `run` when `deps` change (a fresh query: rows reset, `loading`), and
302
+ // again when a refresh lands (`refreshing`: the rows already on screen stay
303
+ // until the new ones arrive — a dashboard must not blink to empty on every
304
+ // refresh). `isRefreshing` says whether a refresh in flight concerns this
305
+ // query, so `refreshing` is true from the click, not only from the reload.
306
+ function useAsyncQuery(run, deps, isRefreshing) {
307
+ const bindings = useBindingState();
308
+ const [state, setState] = React.useState(EMPTY);
309
+ const seenVersion = React.useRef(bindings.version);
128
310
  React.useEffect(() => {
129
311
  let active = true;
130
- setState({
131
- data: null,
132
- fields: null,
133
- error: null,
134
- loading: true,
135
- truncated: false,
136
- rowCount: null,
137
- });
312
+ const isRefresh = seenVersion.current !== bindings.version;
313
+ seenVersion.current = bindings.version;
314
+ setState(s => (isRefresh && s.data !== null ? { ...s, refreshing: true } : EMPTY));
138
315
  run().then(
139
316
  result => {
140
- if (active) setState({ ...result, error: null, loading: false });
317
+ if (active) setState({ ...result, error: null, loading: false, refreshing: false });
141
318
  },
142
319
  error => {
143
320
  if (active)
144
321
  setState({
145
- data: null,
146
- fields: null,
322
+ ...EMPTY,
147
323
  error: error instanceof Error ? error.message : String(error),
148
324
  loading: false,
149
- truncated: false,
150
- rowCount: null,
151
325
  });
152
326
  },
153
327
  );
@@ -155,32 +329,95 @@ function useAsyncQuery(run, deps) {
155
329
  active = false;
156
330
  };
157
331
  // eslint-disable-next-line react-hooks/exhaustive-deps
158
- }, deps);
159
- return state;
332
+ }, [...deps, bindings.version]);
333
+ return {
334
+ ...state,
335
+ refreshing: state.refreshing || isRefreshing(bindings.refreshing),
336
+ };
160
337
  }
161
338
 
162
339
  export function useQuery(name, opts) {
163
340
  const rowLimit = opts ? opts.rowLimit : undefined;
164
- return useAsyncQuery(async () => {
165
- await registerBinding(name);
166
- const r = await runSql(
167
- 'SELECT * FROM "' + name.replace(/"/g, '""') + '"',
168
- rowLimit,
341
+ const state = useAsyncQuery(
342
+ async () => {
343
+ await registerBinding(name);
344
+ const r = await runSql(
345
+ 'SELECT * FROM "' + name.replace(/"/g, '""') + '"',
346
+ rowLimit,
347
+ );
348
+ return { data: r.rows, fields: r.fields, truncated: r.truncated, rowCount: r.rowCount };
349
+ },
350
+ [name, rowLimit],
351
+ refreshing => refreshing.has(name),
352
+ );
353
+ const refresh = React.useCallback(() => refreshBinding(name), [name]);
354
+ return { ...state, refresh };
355
+ }
356
+
357
+ /**
358
+ * Who is looking at the app: `{ viewer, loading, error }`. `viewer` is null
359
+ * while loading, on an anonymous share link, and when the server does not
360
+ * know. Join `viewer.email` against your own roster binding for anything
361
+ * beyond identity and access role — that is the app's call, not Mako's.
362
+ */
363
+ export function useViewer() {
364
+ const [state, setState] = React.useState({ viewer: null, loading: true, error: null });
365
+ React.useEffect(() => {
366
+ let active = true;
367
+ getViewer().then(
368
+ viewer => {
369
+ if (active) setState({ viewer, loading: false, error: null });
370
+ },
371
+ error => {
372
+ if (active) {
373
+ setState({
374
+ viewer: null,
375
+ loading: false,
376
+ error: error instanceof Error ? error.message : String(error),
377
+ });
378
+ }
379
+ },
169
380
  );
170
- return { data: r.rows, fields: r.fields, truncated: r.truncated, rowCount: r.rowCount };
171
- }, [name, rowLimit]);
381
+ return () => {
382
+ active = false;
383
+ };
384
+ }, []);
385
+ return state;
172
386
  }
173
387
 
174
388
  export function useDuckDB(sql, opts) {
175
389
  const rowLimit = opts ? opts.rowLimit : undefined;
176
- return useAsyncQuery(async () => {
390
+ const state = useAsyncQuery(async () => {
177
391
  // Register everything the server staged, so SQL can join across
178
- // bindings by name without declaring them first.
392
+ // bindings by name without declaring them first. A binding that fails to
393
+ // load must not sink the whole query set silently: remember why, and when
394
+ // the SQL then fails (typically DuckDB's "Table … does not exist"),
395
+ // surface the load failure — it is the actual cause.
179
396
  const names = await bindingIndex();
180
- await Promise.all(names.map(n => registerBinding(n).catch(() => {})));
181
- const r = await runSql(sql, rowLimit);
182
- return { data: r.rows, fields: r.fields, truncated: r.truncated, rowCount: r.rowCount };
183
- }, [sql, rowLimit]);
397
+ const failures = new Map();
398
+ await Promise.all(
399
+ names.map(n => registerBinding(n).catch(e => failures.set(n, e))),
400
+ );
401
+ try {
402
+ const r = await runSql(sql, rowLimit);
403
+ return { data: r.rows, fields: r.fields, truncated: r.truncated, rowCount: r.rowCount };
404
+ } catch (error) {
405
+ const message = error instanceof Error ? error.message : String(error);
406
+ for (const [n, cause] of failures) {
407
+ if (message.includes(n)) throw cause;
408
+ }
409
+ if (failures.size) {
410
+ const details = [...failures.values()]
411
+ .map(e => (e instanceof Error ? e.message : String(e)))
412
+ .join("; ");
413
+ throw new Error(message + " (bindings that failed to load: " + details + ")");
414
+ }
415
+ throw error;
416
+ }
417
+ }, [sql, rowLimit], refreshing => refreshing.size > 0);
418
+ // A query over every binding refreshes every binding.
419
+ const refresh = React.useCallback(() => refreshBindings(), []);
420
+ return { ...state, refresh };
184
421
  }
185
422
 
186
423
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@makoai/app-sdk",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "Mako app SDK: data bindings (useQuery/useDuckDB), URL state, theme.",
5
- "license": "ISC",
5
+ "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/mako-ai/mako.git",
package/vite.d.ts CHANGED
@@ -15,6 +15,11 @@ export interface MakoDataOptions {
15
15
  revalidateMs?: number;
16
16
  /** Build a never-materialized binding on first request. Default: true. */
17
17
  materialize?: boolean;
18
+ /**
19
+ * Preview the app as this member (an email): `__data/viewer.json` answers
20
+ * as Mako would for them. Default: MAKO_VIEWER_AS, else yourself.
21
+ */
22
+ viewAs?: string;
18
23
  }
19
24
 
20
25
  export interface MakoContext {
@@ -25,6 +30,8 @@ export interface MakoContext {
25
30
  slug: string;
26
31
  bindingsDir: string;
27
32
  cacheDir: string;
33
+ /** Email of the member being previewed, or "" for yourself. */
34
+ viewAs: string;
28
35
  }
29
36
 
30
37
  /** Resolve credentials and identity the way `makoData` does. */
package/vite.js CHANGED
@@ -10,7 +10,7 @@
10
10
  // Plain ESM, Node built-ins only — like the rest of this package.
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
- import { findCredential, getAccessToken } from "./credentials.js";
13
+ import { HOSTED_API_URL, findCredential, getAccessToken } from "./credentials.js";
14
14
 
15
15
  const BINDING_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
16
16
  const DEFAULT_REVALIDATE_MS = 5 * 60 * 1000;
@@ -72,11 +72,13 @@ export function resolveMakoContext(appDir, options = {}) {
72
72
  const dotenv = readDotenv(path.join(repoRoot, ".env"));
73
73
  const ws = readWorkspaceJson(repoRoot);
74
74
  const env = (name) => process.env[name] ?? dotenv[name];
75
+ // Hosted Mako is the default: a fresh clone + `mako login` needs no .env.
76
+ // MAKO_API_URL / workspace.json apiUrl exist for self-hosted or local dev.
75
77
  const apiUrl = (
76
78
  options.apiUrl ??
77
79
  env("MAKO_API_URL") ??
78
80
  ws.apiUrl ??
79
- ""
81
+ HOSTED_API_URL
80
82
  ).replace(/\/+$/, "");
81
83
  return {
82
84
  repoRoot,
@@ -86,6 +88,8 @@ export function resolveMakoContext(appDir, options = {}) {
86
88
  slug: options.slug ?? path.basename(path.resolve(appDir)),
87
89
  bindingsDir: path.join(appDir, "bindings"),
88
90
  cacheDir: path.join(appDir, "node_modules", ".mako-data"),
91
+ /** Preview the app as this viewer (email) — see makoData(). */
92
+ viewAs: options.viewAs ?? env("MAKO_VIEWER_AS") ?? "",
89
93
  };
90
94
  }
91
95
 
@@ -122,8 +126,11 @@ export function makoData(options = {}) {
122
126
  // once keeps working without ever pasting a key.
123
127
  const loggedIn = !ctx.apiKey && !!findCredential(ctx.apiUrl, ctx.workspaceId);
124
128
  const problems = [];
125
- if (!ctx.apiUrl) problems.push("MAKO_API_URL is not set");
126
- if (!ctx.apiKey && !loggedIn) problems.push("not signed in: run `mako login` (or set MAKO_API_KEY)");
129
+ if (!ctx.apiUrl) problems.push("MAKO_API_URL is set but empty");
130
+ if (!ctx.apiKey && !loggedIn)
131
+ problems.push(
132
+ `not signed in to ${ctx.apiUrl || "Mako"}: run \`npx @makoai/cli login\` in this repo (or set MAKO_API_KEY in .env)`,
133
+ );
127
134
  if (!ctx.workspaceId) problems.push("workspace id unknown (.mako/workspace.json or MAKO_WORKSPACE_ID)");
128
135
  const appBase = () =>
129
136
  `${ctx.apiUrl}/api/workspaces/${encodeURIComponent(ctx.workspaceId)}/apps/${encodeURIComponent(ctx.slug)}`;
@@ -138,12 +145,28 @@ export function makoData(options = {}) {
138
145
  : ` via ${ctx.apiUrl} (${ctx.apiKey ? "API key" : "mako login"})`),
139
146
  );
140
147
 
148
+ // fetch() with network failures translated into something a person can
149
+ // act on — "fetch failed" alone has sent people debugging the wrong end.
150
+ async function apiFetch(url, init) {
151
+ try {
152
+ return await fetch(url, init);
153
+ } catch (error) {
154
+ const cause = error?.cause?.code ?? error?.cause?.message ?? error?.message ?? String(error);
155
+ throw new Error(
156
+ `cannot reach the Mako API at ${ctx.apiUrl} (${cause})` +
157
+ (ctx.apiUrl === HOSTED_API_URL
158
+ ? " — check your network connection"
159
+ : ` — is that server running? Unset MAKO_API_URL (repo .env or environment) to use ${HOSTED_API_URL}`),
160
+ );
161
+ }
162
+ }
163
+
141
164
  async function fetchArtifact(name) {
142
165
  const url = `${appBase()}/bindings/${encodeURIComponent(name)}/artifact`;
143
- let res = await fetch(url, { headers: await headers() });
166
+ let res = await apiFetch(url, { headers: await headers() });
144
167
  if (res.status === 404 && options.materialize !== false) {
145
168
  // Never materialized (or a live binding): build it now, then read.
146
- const built = await fetch(
169
+ const built = await apiFetch(
147
170
  `${appBase()}/bindings/${encodeURIComponent(name)}/materialize`,
148
171
  { method: "POST", headers: await headers() },
149
172
  );
@@ -151,30 +174,97 @@ export function makoData(options = {}) {
151
174
  const text = await built.text().catch(() => "");
152
175
  throw new Error(`materialize ${name}: HTTP ${built.status} ${text.slice(0, 300)}`);
153
176
  }
154
- res = await fetch(url, { headers: await headers() });
177
+ res = await apiFetch(url, { headers: await headers() });
155
178
  }
156
179
  if (!res.ok) {
157
180
  const text = await res.text().catch(() => "");
181
+ if (res.status === 401 || res.status === 403) {
182
+ throw new Error(
183
+ `the Mako API at ${ctx.apiUrl} refused the credential (HTTP ${res.status}) — ` +
184
+ (ctx.apiKey
185
+ ? "the MAKO_API_KEY in .env is invalid for this host/workspace"
186
+ : "run `npx @makoai/cli login` in this repo again") +
187
+ (text ? ` (${text.slice(0, 200)})` : ""),
188
+ );
189
+ }
158
190
  throw new Error(`artifact ${name}: HTTP ${res.status} ${text.slice(0, 300)}`);
159
191
  }
160
192
  return Buffer.from(await res.arrayBuffer());
161
193
  }
162
194
 
195
+ // POST __data/<name>/refresh — the SDK's refresh(): rebuild the
196
+ // binding through the API (the same call app_materialize makes), then
197
+ // forget the local copy so the next read is the new artifact.
198
+ async function refreshBinding(name, res) {
199
+ const cached = path.join(ctx.cacheDir, `${name}.parquet`);
200
+ try {
201
+ const built = await apiFetch(
202
+ `${appBase()}/bindings/${encodeURIComponent(name)}/materialize`,
203
+ { method: "POST", headers: await headers() },
204
+ );
205
+ const body = await built.json().catch(() => ({}));
206
+ if (!built.ok) {
207
+ return json(res, built.status, {
208
+ success: false,
209
+ error: body.error || `materialize ${name}: HTTP ${built.status}`,
210
+ });
211
+ }
212
+ fs.rmSync(cached, { force: true });
213
+ json(res, 200, {
214
+ success: true,
215
+ binding: name,
216
+ materialization: "parquet",
217
+ rowCount: body.rowCount,
218
+ byteSize: body.byteSize,
219
+ materializedAt: body.materializedAt,
220
+ });
221
+ } catch (error) {
222
+ const message = error instanceof Error ? error.message : String(error);
223
+ server.config.logger.error(` mako-data: ${message}`);
224
+ json(res, 502, { success: false, error: message });
225
+ }
226
+ }
227
+
228
+ // `__data/viewer.json` — the SDK's useViewer(): the developer's own
229
+ // identity, or, with MAKO_VIEWER_AS=<email> (env or .env), another
230
+ // member's, exactly as Mako would answer for them.
231
+ const viewAsQuery = ctx.viewAs ? `?as=${encodeURIComponent(ctx.viewAs)}` : "";
232
+ async function serveViewer(res) {
233
+ if (problems.length) return json(res, 200, null);
234
+ try {
235
+ const r = await apiFetch(`${appBase()}/viewer${viewAsQuery}`, {
236
+ headers: await headers(),
237
+ });
238
+ const body = await r.json().catch(() => ({}));
239
+ if (r.status === 404) return json(res, 200, null);
240
+ if (!r.ok) return json(res, r.status, { error: body.error ?? `viewer: HTTP ${r.status}` });
241
+ return json(res, 200, body.viewer ?? null);
242
+ } catch (error) {
243
+ return json(res, 502, { error: error instanceof Error ? error.message : String(error) });
244
+ }
245
+ }
246
+
163
247
  server.middlewares.use(async (req, res, next) => {
164
248
  const [pathname, query = ""] = (req.url || "").split("?");
165
249
  if (pathname === "/__data/index.json") {
166
250
  return json(res, 200, listBindings(ctx.bindingsDir));
167
251
  }
168
- const match = /^\/__data\/([^/]+)\.parquet$/.exec(pathname);
252
+ if (pathname === "/__data/viewer.json") return serveViewer(res);
253
+ const match = /^\/__data\/([^/]+)(\.parquet|\/refresh)$/.exec(pathname);
169
254
  if (!match) return next();
170
255
  const name = decodeURIComponent(match[1]);
256
+ const isRefresh = match[2] === "/refresh";
171
257
  if (!BINDING_NAME.test(name)) return json(res, 400, { error: "invalid binding name" });
258
+ if (isRefresh && req.method !== "POST") {
259
+ return json(res, 405, { error: "POST to refresh a binding" });
260
+ }
172
261
  if (problems.length) {
173
262
  return json(res, 503, {
174
263
  error: `mako-data is not connected: ${problems.join("; ")}`,
175
264
  hint: "Run `mako login` in this repo, or put MAKO_API_URL and MAKO_API_KEY in the repo's .env (see AGENTS.md).",
176
265
  });
177
266
  }
267
+ if (isRefresh) return refreshBinding(name, res);
178
268
  const cached = path.join(ctx.cacheDir, `${name}.parquet`);
179
269
  const refresh = /(^|&)refresh(=|&|$)/.test(query);
180
270
  try {