@makoai/app-sdk 2.2.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 +53 -0
- package/credentials.d.ts +39 -0
- package/credentials.js +118 -0
- package/index.d.ts +46 -0
- package/index.js +283 -0
- package/package.json +54 -0
- package/vite.d.ts +41 -0
- package/vite.js +211 -0
package/README.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# @makoai/app-sdk
|
|
2
|
+
|
|
3
|
+
The runtime SDK for [Mako](https://mako.ai) data apps — React hooks over an
|
|
4
|
+
app's data bindings, plus a Vite plugin that serves those bindings during a
|
|
5
|
+
local `vite dev`.
|
|
6
|
+
|
|
7
|
+
Every Mako workspace repository carries this package at `packages/app-sdk`;
|
|
8
|
+
apps depend on it with `"@makoai/app-sdk": "file:../../packages/app-sdk"`. Mako
|
|
9
|
+
keeps the vendored copy current — do not edit it in a workspace repo.
|
|
10
|
+
|
|
11
|
+
## In the app
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { useQuery, useDuckDB, useSearchParams, useTheme } from "@makoai/app-sdk";
|
|
15
|
+
|
|
16
|
+
// Rows of bindings/<name>.sql, materialized to parquet by Mako.
|
|
17
|
+
const { data, loading, error } = useQuery("latest_sales");
|
|
18
|
+
|
|
19
|
+
// Analytical SQL over every binding (DuckDB-WASM in the browser; table
|
|
20
|
+
// names are binding names).
|
|
21
|
+
const totals = useDuckDB("select country, sum(revenue) r from latest_sales group by 1");
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`useLocation` / `useSearchParams` / `navigate` keep filter state in the URL;
|
|
25
|
+
`useTheme` follows the OS preference. Theme tokens (`--background`,
|
|
26
|
+
`--chart-1`, …) match the ones the scaffold's `styles.css` declares.
|
|
27
|
+
|
|
28
|
+
Data arrives from `__data/<name>.parquet`, relative to the page — the same
|
|
29
|
+
path in Mako's sandbox, in a published app, and on a laptop.
|
|
30
|
+
|
|
31
|
+
## In `vite.config.ts`
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { makoData } from "@makoai/app-sdk/vite";
|
|
35
|
+
|
|
36
|
+
export default defineConfig({ plugins: [react(), makoData()] });
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`makoData()` answers `__data/index.json` (the app's `bindings/*.sql`) and
|
|
40
|
+
`__data/<name>.parquet` during `vite dev` by streaming each binding's
|
|
41
|
+
materialized artifact from the Mako API — a binding that was never
|
|
42
|
+
materialized is built on first request. Results are cached under
|
|
43
|
+
`node_modules/.mako-data/` for five minutes (`?refresh` bypasses; a stale
|
|
44
|
+
copy is served if the API is unreachable). It is `apply: "serve"` only —
|
|
45
|
+
production builds never load it.
|
|
46
|
+
|
|
47
|
+
Credentials, in order: `MAKO_API_URL` / `MAKO_API_KEY` in the environment,
|
|
48
|
+
then in the repo-root `.env`. The workspace id comes from
|
|
49
|
+
`.mako/workspace.json` (or `MAKO_WORKSPACE_ID`). Without a key the app runs
|
|
50
|
+
and every binding answers `503` with a hint.
|
|
51
|
+
|
|
52
|
+
Dependency-free: the DuckDB engine loads from jsDelivr at runtime; the plugin
|
|
53
|
+
uses only Node built-ins.
|
package/credentials.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export const CREDENTIALS_PATH: string;
|
|
2
|
+
|
|
3
|
+
export interface StoredCredential {
|
|
4
|
+
apiUrl: string;
|
|
5
|
+
workspaceId: string | null;
|
|
6
|
+
clientId: string;
|
|
7
|
+
accessToken: string;
|
|
8
|
+
refreshToken?: string;
|
|
9
|
+
/** ISO timestamp. */
|
|
10
|
+
expiresAt?: string;
|
|
11
|
+
scopes?: string[];
|
|
12
|
+
savedAt?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function normalizeApiUrl(url: string): string;
|
|
16
|
+
export function credentialKey(apiUrl: string, workspaceId?: string | null): string;
|
|
17
|
+
export function readCredentialStore(file?: string): Record<string, StoredCredential>;
|
|
18
|
+
export function writeCredentialStore(store: Record<string, StoredCredential>, file?: string): void;
|
|
19
|
+
export function findCredential(
|
|
20
|
+
apiUrl: string,
|
|
21
|
+
workspaceId?: string | null,
|
|
22
|
+
store?: Record<string, StoredCredential>,
|
|
23
|
+
): StoredCredential | null;
|
|
24
|
+
export function saveCredential(
|
|
25
|
+
apiUrl: string,
|
|
26
|
+
workspaceId: string | null,
|
|
27
|
+
entry: Omit<StoredCredential, "apiUrl" | "workspaceId" | "savedAt">,
|
|
28
|
+
file?: string,
|
|
29
|
+
): void;
|
|
30
|
+
export function removeCredential(apiUrl: string, workspaceId?: string | null, file?: string): boolean;
|
|
31
|
+
export function refreshCredential(
|
|
32
|
+
entry: StoredCredential,
|
|
33
|
+
fetchImpl?: typeof fetch,
|
|
34
|
+
): Promise<StoredCredential>;
|
|
35
|
+
export function getAccessToken(
|
|
36
|
+
apiUrl: string,
|
|
37
|
+
workspaceId?: string | null,
|
|
38
|
+
options?: { file?: string; fetch?: typeof fetch },
|
|
39
|
+
): Promise<string | null>;
|
package/credentials.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// @makoai/app-sdk/credentials — the laptop credential store shared by the
|
|
2
|
+
// `mako` CLI (which writes it) and the Vite plugin (which reads it).
|
|
3
|
+
//
|
|
4
|
+
// `mako login` runs the same OAuth 2.1 sign-in Claude Code uses against the
|
|
5
|
+
// Mako MCP server (PKCE, loopback redirect, rotating refresh tokens) and keeps
|
|
6
|
+
// the result here. Tokens are always workspace-bound and read-only — exactly
|
|
7
|
+
// what a local dev server needs and nothing more.
|
|
8
|
+
//
|
|
9
|
+
// Plain ESM, Node built-ins only.
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
|
|
14
|
+
export const CREDENTIALS_PATH =
|
|
15
|
+
process.env.MAKO_CREDENTIALS_FILE ||
|
|
16
|
+
path.join(os.homedir(), ".mako", "credentials.json");
|
|
17
|
+
|
|
18
|
+
const REFRESH_SKEW_MS = 60 * 1000;
|
|
19
|
+
|
|
20
|
+
export function normalizeApiUrl(url) {
|
|
21
|
+
return String(url || "").replace(/\/+$/, "");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Storage key: one entry per (host, workspace). "*" = workspace unknown. */
|
|
25
|
+
export function credentialKey(apiUrl, workspaceId) {
|
|
26
|
+
return `${normalizeApiUrl(apiUrl)}#${workspaceId || "*"}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function readCredentialStore(file = CREDENTIALS_PATH) {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
32
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
33
|
+
} catch {
|
|
34
|
+
return {};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function writeCredentialStore(store, file = CREDENTIALS_PATH) {
|
|
39
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
40
|
+
fs.writeFileSync(file, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The stored entry for a host + workspace: the exact match first, then the
|
|
45
|
+
* host's wildcard entry (a login done outside any workspace checkout).
|
|
46
|
+
*/
|
|
47
|
+
export function findCredential(apiUrl, workspaceId, store = readCredentialStore()) {
|
|
48
|
+
return (
|
|
49
|
+
store[credentialKey(apiUrl, workspaceId)] ??
|
|
50
|
+
store[credentialKey(apiUrl, null)] ??
|
|
51
|
+
null
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function saveCredential(apiUrl, workspaceId, entry, file = CREDENTIALS_PATH) {
|
|
56
|
+
const store = readCredentialStore(file);
|
|
57
|
+
store[credentialKey(apiUrl, workspaceId)] = {
|
|
58
|
+
...entry,
|
|
59
|
+
apiUrl: normalizeApiUrl(apiUrl),
|
|
60
|
+
workspaceId: workspaceId || null,
|
|
61
|
+
savedAt: new Date().toISOString(),
|
|
62
|
+
};
|
|
63
|
+
writeCredentialStore(store, file);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function removeCredential(apiUrl, workspaceId, file = CREDENTIALS_PATH) {
|
|
67
|
+
const store = readCredentialStore(file);
|
|
68
|
+
const key = credentialKey(apiUrl, workspaceId);
|
|
69
|
+
const had = key in store;
|
|
70
|
+
delete store[key];
|
|
71
|
+
writeCredentialStore(store, file);
|
|
72
|
+
return had;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Refresh an entry's access token through the MCP OAuth token endpoint. */
|
|
76
|
+
export async function refreshCredential(entry, fetchImpl = globalThis.fetch) {
|
|
77
|
+
if (!entry?.refreshToken || !entry?.clientId) {
|
|
78
|
+
throw new Error("stored credential has no refresh token; run `mako login` again");
|
|
79
|
+
}
|
|
80
|
+
const res = await fetchImpl(`${normalizeApiUrl(entry.apiUrl)}/api/oauth/mcp/token`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
83
|
+
body: new URLSearchParams({
|
|
84
|
+
grant_type: "refresh_token",
|
|
85
|
+
refresh_token: entry.refreshToken,
|
|
86
|
+
client_id: entry.clientId,
|
|
87
|
+
}),
|
|
88
|
+
});
|
|
89
|
+
if (!res.ok) {
|
|
90
|
+
const text = await res.text().catch(() => "");
|
|
91
|
+
throw new Error(`token refresh failed: HTTP ${res.status} ${text.slice(0, 200)} — run \`mako login\` again`);
|
|
92
|
+
}
|
|
93
|
+
const body = await res.json();
|
|
94
|
+
return {
|
|
95
|
+
...entry,
|
|
96
|
+
accessToken: body.access_token,
|
|
97
|
+
refreshToken: body.refresh_token ?? entry.refreshToken,
|
|
98
|
+
expiresAt: new Date(Date.now() + Number(body.expires_in || 3600) * 1000).toISOString(),
|
|
99
|
+
scopes: typeof body.scope === "string" ? body.scope.split(" ") : entry.scopes,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A usable bearer token for (apiUrl, workspaceId), refreshing and persisting
|
|
105
|
+
* when the stored one is about to expire. Null when nobody logged in.
|
|
106
|
+
*/
|
|
107
|
+
export async function getAccessToken(apiUrl, workspaceId, options = {}) {
|
|
108
|
+
const file = options.file ?? CREDENTIALS_PATH;
|
|
109
|
+
const entry = findCredential(apiUrl, workspaceId, readCredentialStore(file));
|
|
110
|
+
if (!entry) return null;
|
|
111
|
+
const expiresAt = entry.expiresAt ? Date.parse(entry.expiresAt) : 0;
|
|
112
|
+
if (entry.accessToken && expiresAt - REFRESH_SKEW_MS > Date.now()) {
|
|
113
|
+
return entry.accessToken;
|
|
114
|
+
}
|
|
115
|
+
const refreshed = await refreshCredential(entry, options.fetch);
|
|
116
|
+
saveCredential(refreshed.apiUrl, entry.workspaceId, refreshed, file);
|
|
117
|
+
return refreshed.accessToken;
|
|
118
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type * as React from "react";
|
|
2
|
+
|
|
3
|
+
export interface QueryState<Row = Record<string, unknown>> {
|
|
4
|
+
data: Row[] | null;
|
|
5
|
+
error: string | null;
|
|
6
|
+
loading: boolean;
|
|
7
|
+
truncated: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface DuckDBState<Row = Record<string, unknown>>
|
|
10
|
+
extends QueryState<Row> {
|
|
11
|
+
fields: string[] | null;
|
|
12
|
+
rowCount: number | null;
|
|
13
|
+
}
|
|
14
|
+
export interface QueryOptions {
|
|
15
|
+
rowLimit?: number | null;
|
|
16
|
+
}
|
|
17
|
+
export interface MakoLocation {
|
|
18
|
+
pathname: string;
|
|
19
|
+
search: string;
|
|
20
|
+
hash: string;
|
|
21
|
+
href: string;
|
|
22
|
+
searchParams: URLSearchParams;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Rows of a named data binding (bindings/<name>.sql, materialized). */
|
|
26
|
+
export function useQuery<Row = Record<string, unknown>>(
|
|
27
|
+
name: string,
|
|
28
|
+
opts?: QueryOptions,
|
|
29
|
+
): QueryState<Row>;
|
|
30
|
+
|
|
31
|
+
/** Analytical SQL over the app's bindings; table names are binding names. */
|
|
32
|
+
export function useDuckDB<Row = Record<string, unknown>>(
|
|
33
|
+
sql: string,
|
|
34
|
+
opts?: QueryOptions,
|
|
35
|
+
): DuckDBState<Row>;
|
|
36
|
+
|
|
37
|
+
export function useTheme(): { theme: "light" | "dark" };
|
|
38
|
+
export function useLocation(): MakoLocation;
|
|
39
|
+
export function useSearchParams(): [
|
|
40
|
+
URLSearchParams,
|
|
41
|
+
(
|
|
42
|
+
next: URLSearchParams | Record<string, string> | string,
|
|
43
|
+
opts?: { replace?: boolean },
|
|
44
|
+
) => void,
|
|
45
|
+
];
|
|
46
|
+
export function navigate(to: string, opts?: { replace?: boolean }): void;
|
package/index.js
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// @makoai/app-sdk — see package.json. Plain ESM on purpose: no build step.
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_ROW_LIMIT = 500000;
|
|
5
|
+
const DUCKDB_ESM =
|
|
6
|
+
"https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@1.29.0/+esm";
|
|
7
|
+
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// DuckDB: one lazy instance per page, bindings registered on first use. The
|
|
10
|
+
// engine arrives from the CDN at runtime, so this package needs no install
|
|
11
|
+
// step and no dependencies of its own.
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
let dbPromise = null;
|
|
14
|
+
function getDb() {
|
|
15
|
+
dbPromise ??= (async () => {
|
|
16
|
+
const duckdb = await import(/* @vite-ignore */ DUCKDB_ESM);
|
|
17
|
+
const bundle = await duckdb.selectBundle(duckdb.getJsDelivrBundles());
|
|
18
|
+
const worker = await duckdb.createWorker(bundle.mainWorker);
|
|
19
|
+
const db = new duckdb.AsyncDuckDB(new duckdb.VoidLogger(), worker);
|
|
20
|
+
await db.instantiate(bundle.mainModule, bundle.pthreadWorker);
|
|
21
|
+
return db;
|
|
22
|
+
})();
|
|
23
|
+
return dbPromise;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const registered = new Map(); // name -> Promise<void>
|
|
27
|
+
function registerBinding(name) {
|
|
28
|
+
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
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return registered.get(name);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Names of every staged binding — written by the dev server next to the
|
|
59
|
+
* parquet files. Absent (older servers, published builds): empty list. */
|
|
60
|
+
let indexPromise = null;
|
|
61
|
+
function bindingIndex() {
|
|
62
|
+
indexPromise ??= fetch("__data/index.json")
|
|
63
|
+
.then(r => (r.ok ? r.json() : []))
|
|
64
|
+
.then(list => (Array.isArray(list) ? list : []))
|
|
65
|
+
.catch(() => []);
|
|
66
|
+
return indexPromise;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Arrow → plain JS, with the types apps actually want. DuckDB hands DATE and
|
|
70
|
+
// TIMESTAMP columns to JS as epoch milliseconds; v1 apps (JSON over the wire)
|
|
71
|
+
// always saw strings, and a migrated formatDate() that did
|
|
72
|
+
// new Date(`${d}T00:00:00`) on a number threw and unmounted the whole app
|
|
73
|
+
// (apps.md §15.4). So: DATE → "YYYY-MM-DD", TIMESTAMP → ISO 8601, BigInt →
|
|
74
|
+
// Number when it fits. Everything else passes through untouched.
|
|
75
|
+
function columnDecoder(field) {
|
|
76
|
+
const type = String(field.type);
|
|
77
|
+
if (type.startsWith("Date")) {
|
|
78
|
+
return v => (v == null ? v : new Date(Number(v)).toISOString().slice(0, 10));
|
|
79
|
+
}
|
|
80
|
+
if (type.startsWith("Timestamp")) {
|
|
81
|
+
return v => (v == null ? v : new Date(Number(v)).toISOString());
|
|
82
|
+
}
|
|
83
|
+
return v =>
|
|
84
|
+
typeof v === "bigint" && v >= Number.MIN_SAFE_INTEGER && v <= Number.MAX_SAFE_INTEGER
|
|
85
|
+
? Number(v)
|
|
86
|
+
: v;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function toPlainRows(table, cap) {
|
|
90
|
+
const rows = [];
|
|
91
|
+
const fields = table.schema.fields.map(f => f.name);
|
|
92
|
+
const decoders = table.schema.fields.map(columnDecoder);
|
|
93
|
+
const limit = cap == null ? Infinity : cap;
|
|
94
|
+
for (const row of table) {
|
|
95
|
+
if (rows.length >= limit) break;
|
|
96
|
+
const out = {};
|
|
97
|
+
for (let i = 0; i < fields.length; i++) {
|
|
98
|
+
out[fields[i]] = decoders[i](row[fields[i]]);
|
|
99
|
+
}
|
|
100
|
+
rows.push(out);
|
|
101
|
+
}
|
|
102
|
+
return { rows, fields };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function runSql(sql, rowLimit) {
|
|
106
|
+
const cap = rowLimit === null ? Infinity : (rowLimit ?? DEFAULT_ROW_LIMIT);
|
|
107
|
+
const db = await getDb();
|
|
108
|
+
const conn = await db.connect();
|
|
109
|
+
try {
|
|
110
|
+
const table = await conn.query(sql);
|
|
111
|
+
const rowCount = table.numRows;
|
|
112
|
+
const { rows, fields } = toPlainRows(table, cap);
|
|
113
|
+
return { rows, fields, rowCount, truncated: rowCount > rows.length };
|
|
114
|
+
} finally {
|
|
115
|
+
await conn.close();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
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
|
+
});
|
|
128
|
+
React.useEffect(() => {
|
|
129
|
+
let active = true;
|
|
130
|
+
setState({
|
|
131
|
+
data: null,
|
|
132
|
+
fields: null,
|
|
133
|
+
error: null,
|
|
134
|
+
loading: true,
|
|
135
|
+
truncated: false,
|
|
136
|
+
rowCount: null,
|
|
137
|
+
});
|
|
138
|
+
run().then(
|
|
139
|
+
result => {
|
|
140
|
+
if (active) setState({ ...result, error: null, loading: false });
|
|
141
|
+
},
|
|
142
|
+
error => {
|
|
143
|
+
if (active)
|
|
144
|
+
setState({
|
|
145
|
+
data: null,
|
|
146
|
+
fields: null,
|
|
147
|
+
error: error instanceof Error ? error.message : String(error),
|
|
148
|
+
loading: false,
|
|
149
|
+
truncated: false,
|
|
150
|
+
rowCount: null,
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
);
|
|
154
|
+
return () => {
|
|
155
|
+
active = false;
|
|
156
|
+
};
|
|
157
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
158
|
+
}, deps);
|
|
159
|
+
return state;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function useQuery(name, opts) {
|
|
163
|
+
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,
|
|
169
|
+
);
|
|
170
|
+
return { data: r.rows, fields: r.fields, truncated: r.truncated, rowCount: r.rowCount };
|
|
171
|
+
}, [name, rowLimit]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function useDuckDB(sql, opts) {
|
|
175
|
+
const rowLimit = opts ? opts.rowLimit : undefined;
|
|
176
|
+
return useAsyncQuery(async () => {
|
|
177
|
+
// Register everything the server staged, so SQL can join across
|
|
178
|
+
// bindings by name without declaring them first.
|
|
179
|
+
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]);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
// URL state — the real History API; v1 bridged this to the host URL, a v2
|
|
188
|
+
// app owns its own document.
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
const locationListeners = new Set();
|
|
191
|
+
function emitLocation() {
|
|
192
|
+
for (const l of [...locationListeners]) l();
|
|
193
|
+
}
|
|
194
|
+
if (typeof window !== "undefined") {
|
|
195
|
+
window.addEventListener("popstate", emitLocation);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function readLocation() {
|
|
199
|
+
const { pathname, search, hash, href } = window.location;
|
|
200
|
+
return {
|
|
201
|
+
pathname,
|
|
202
|
+
search,
|
|
203
|
+
hash,
|
|
204
|
+
href,
|
|
205
|
+
searchParams: new URLSearchParams(search),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function navigate(to, opts) {
|
|
210
|
+
const url = new URL(to, window.location.href);
|
|
211
|
+
if (opts && opts.replace) {
|
|
212
|
+
window.history.replaceState(null, "", url);
|
|
213
|
+
} else {
|
|
214
|
+
window.history.pushState(null, "", url);
|
|
215
|
+
}
|
|
216
|
+
emitLocation();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function useLocation() {
|
|
220
|
+
const [loc, setLoc] = React.useState(readLocation);
|
|
221
|
+
React.useEffect(() => {
|
|
222
|
+
const listener = () => setLoc(readLocation());
|
|
223
|
+
locationListeners.add(listener);
|
|
224
|
+
listener();
|
|
225
|
+
return () => {
|
|
226
|
+
locationListeners.delete(listener);
|
|
227
|
+
};
|
|
228
|
+
}, []);
|
|
229
|
+
return loc;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function useSearchParams() {
|
|
233
|
+
const loc = useLocation();
|
|
234
|
+
const setSearchParams = (next, opts) => {
|
|
235
|
+
const sp = next instanceof URLSearchParams ? next : new URLSearchParams(next);
|
|
236
|
+
const qs = sp.toString();
|
|
237
|
+
navigate(window.location.pathname + (qs ? "?" + qs : ""), opts);
|
|
238
|
+
};
|
|
239
|
+
return [loc.searchParams, setSearchParams];
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------------------------------------------------------------------------
|
|
243
|
+
// Theme tokens — the same shadcn-style palette the v1 runtime injected around
|
|
244
|
+
// every app (app/src/app-runtime/preview.ts THEME_TOKENS_CSS). The v1 skill
|
|
245
|
+
// taught agents to write var(--background) / var(--border) / var(--chart-N)
|
|
246
|
+
// directly, so migrated apps DEPEND on these names existing; without them a
|
|
247
|
+
// v2 build renders with no backgrounds or borders at all. The SDK restores
|
|
248
|
+
// the contract wherever it loads: prepended to <head> so any app stylesheet
|
|
249
|
+
// overrides it, keyed by id so double-imports no-op, dark on :root.dark (the
|
|
250
|
+
// v1 toggle) plus the system preference for standalone.
|
|
251
|
+
// ---------------------------------------------------------------------------
|
|
252
|
+
const MAKO_THEME_TOKENS_CSS = ":root {\n color-scheme: light;\n --background: hsl(0 0% 100%);\n --foreground: hsl(240 10% 3.9%);\n --card: hsl(0 0% 100%);\n --card-foreground: hsl(240 10% 3.9%);\n --popover: hsl(0 0% 100%);\n --popover-foreground: hsl(240 10% 3.9%);\n --primary: hsl(240 5.9% 10%);\n --primary-foreground: hsl(0 0% 98%);\n --secondary: hsl(240 4.8% 95.9%);\n --secondary-foreground: hsl(240 5.9% 10%);\n --muted: hsl(240 4.8% 95.9%);\n --muted-foreground: hsl(240 3.8% 46.1%);\n --accent: hsl(240 4.8% 95.9%);\n --accent-foreground: hsl(240 5.9% 10%);\n --destructive: hsl(0 84.2% 60.2%);\n --destructive-foreground: hsl(0 0% 98%);\n --border: hsl(240 5.9% 90%);\n --input: hsl(240 5.9% 90%);\n --ring: hsl(240 5.9% 10%);\n --chart-1: hsl(12 76% 61%);\n --chart-2: hsl(173 58% 39%);\n --chart-3: hsl(197 37% 24%);\n --chart-4: hsl(43 74% 66%);\n --chart-5: hsl(27 87% 67%);\n --radius: 0.5rem;\n}\n:root.dark {\n color-scheme: dark;\n --background: hsl(240 10% 3.9%);\n --foreground: hsl(0 0% 98%);\n --card: hsl(240 10% 3.9%);\n --card-foreground: hsl(0 0% 98%);\n --popover: hsl(240 10% 3.9%);\n --popover-foreground: hsl(0 0% 98%);\n --primary: hsl(0 0% 98%);\n --primary-foreground: hsl(240 5.9% 10%);\n --secondary: hsl(240 3.7% 15.9%);\n --secondary-foreground: hsl(0 0% 98%);\n --muted: hsl(240 3.7% 15.9%);\n --muted-foreground: hsl(240 5% 64.9%);\n --accent: hsl(240 3.7% 15.9%);\n --accent-foreground: hsl(0 0% 98%);\n --destructive: hsl(0 62.8% 30.6%);\n --destructive-foreground: hsl(0 0% 98%);\n --border: hsl(240 3.7% 15.9%);\n --input: hsl(240 3.7% 15.9%);\n --ring: hsl(240 4.9% 83.9%);\n --chart-1: hsl(220 70% 50%);\n --chart-2: hsl(160 60% 45%);\n --chart-3: hsl(30 80% 55%);\n --chart-4: hsl(280 65% 60%);\n --chart-5: hsl(340 75% 55%);\n}\n@media (prefers-color-scheme: dark) {\n :root:not(.light) {\n color-scheme: dark;\n --background: hsl(240 10% 3.9%);\n --foreground: hsl(0 0% 98%);\n --card: hsl(240 10% 3.9%);\n --card-foreground: hsl(0 0% 98%);\n --popover: hsl(240 10% 3.9%);\n --popover-foreground: hsl(0 0% 98%);\n --primary: hsl(0 0% 98%);\n --primary-foreground: hsl(240 5.9% 10%);\n --secondary: hsl(240 3.7% 15.9%);\n --secondary-foreground: hsl(0 0% 98%);\n --muted: hsl(240 3.7% 15.9%);\n --muted-foreground: hsl(240 5% 64.9%);\n --accent: hsl(240 3.7% 15.9%);\n --accent-foreground: hsl(0 0% 98%);\n --destructive: hsl(0 62.8% 30.6%);\n --destructive-foreground: hsl(0 0% 98%);\n --border: hsl(240 3.7% 15.9%);\n --input: hsl(240 3.7% 15.9%);\n --ring: hsl(240 4.9% 83.9%);\n --chart-1: hsl(220 70% 50%);\n --chart-2: hsl(160 60% 45%);\n --chart-3: hsl(30 80% 55%);\n --chart-4: hsl(280 65% 60%);\n --chart-5: hsl(340 75% 55%);\n }\n}\nbody { background: var(--background); color: var(--foreground); }";
|
|
253
|
+
if (
|
|
254
|
+
typeof document !== "undefined" &&
|
|
255
|
+
!document.getElementById("mako-theme-tokens")
|
|
256
|
+
) {
|
|
257
|
+
const el = document.createElement("style");
|
|
258
|
+
el.id = "mako-theme-tokens";
|
|
259
|
+
el.textContent = MAKO_THEME_TOKENS_CSS;
|
|
260
|
+
if (document.head.firstChild) {
|
|
261
|
+
document.head.insertBefore(el, document.head.firstChild);
|
|
262
|
+
} else {
|
|
263
|
+
document.head.appendChild(el);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// Theme — the OS preference; v1 mirrored the host's toggle, a standalone app
|
|
269
|
+
// follows the system.
|
|
270
|
+
// ---------------------------------------------------------------------------
|
|
271
|
+
export function useTheme() {
|
|
272
|
+
const query = "(prefers-color-scheme: dark)";
|
|
273
|
+
const [dark, setDark] = React.useState(
|
|
274
|
+
() => typeof window !== "undefined" && window.matchMedia(query).matches,
|
|
275
|
+
);
|
|
276
|
+
React.useEffect(() => {
|
|
277
|
+
const mq = window.matchMedia(query);
|
|
278
|
+
const listener = e => setDark(e.matches);
|
|
279
|
+
mq.addEventListener("change", listener);
|
|
280
|
+
return () => mq.removeEventListener("change", listener);
|
|
281
|
+
}, []);
|
|
282
|
+
return { theme: dark ? "dark" : "light" };
|
|
283
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@makoai/app-sdk",
|
|
3
|
+
"version": "2.2.0",
|
|
4
|
+
"description": "Mako app SDK: data bindings (useQuery/useDuckDB), URL state, theme.",
|
|
5
|
+
"license": "ISC",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/mako-ai/mako.git",
|
|
9
|
+
"directory": "packages/app-sdk"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://docs.mako.ai/mcp-server/",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"mako",
|
|
14
|
+
"data-apps",
|
|
15
|
+
"duckdb",
|
|
16
|
+
"parquet",
|
|
17
|
+
"vite-plugin"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"main": "./index.js",
|
|
21
|
+
"types": "./index.d.ts",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./index.d.ts",
|
|
25
|
+
"default": "./index.js"
|
|
26
|
+
},
|
|
27
|
+
"./vite": {
|
|
28
|
+
"types": "./vite.d.ts",
|
|
29
|
+
"default": "./vite.js"
|
|
30
|
+
},
|
|
31
|
+
"./credentials": {
|
|
32
|
+
"types": "./credentials.d.ts",
|
|
33
|
+
"default": "./credentials.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"index.js",
|
|
38
|
+
"index.d.ts",
|
|
39
|
+
"vite.js",
|
|
40
|
+
"vite.d.ts",
|
|
41
|
+
"credentials.js",
|
|
42
|
+
"credentials.d.ts",
|
|
43
|
+
"README.md"
|
|
44
|
+
],
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"react": ">=18"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"test": "node --test"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/vite.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Plugin } from "vite";
|
|
2
|
+
|
|
3
|
+
export interface MakoDataOptions {
|
|
4
|
+
/** Mako API origin. Default: MAKO_API_URL (process.env, then the repo's .env). */
|
|
5
|
+
apiUrl?: string;
|
|
6
|
+
/** Workspace API key with the query:read scope. Default: MAKO_API_KEY. */
|
|
7
|
+
apiKey?: string;
|
|
8
|
+
/** Default: MAKO_WORKSPACE_ID, then .mako/workspace.json at the repo root. */
|
|
9
|
+
workspaceId?: string;
|
|
10
|
+
/** App slug. Default: the app directory's basename. */
|
|
11
|
+
slug?: string;
|
|
12
|
+
/** Repo root. Default: the nearest ancestor holding .mako/ or .git. */
|
|
13
|
+
repoRoot?: string;
|
|
14
|
+
/** Re-fetch a cached parquet after this long (ms). Default: 5 minutes. */
|
|
15
|
+
revalidateMs?: number;
|
|
16
|
+
/** Build a never-materialized binding on first request. Default: true. */
|
|
17
|
+
materialize?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface MakoContext {
|
|
21
|
+
repoRoot: string;
|
|
22
|
+
apiUrl: string;
|
|
23
|
+
apiKey: string;
|
|
24
|
+
workspaceId: string;
|
|
25
|
+
slug: string;
|
|
26
|
+
bindingsDir: string;
|
|
27
|
+
cacheDir: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Resolve credentials and identity the way `makoData` does. */
|
|
31
|
+
export function resolveMakoContext(
|
|
32
|
+
appDir: string,
|
|
33
|
+
options?: MakoDataOptions,
|
|
34
|
+
): MakoContext;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Serve the app's data bindings (`__data/index.json`, `__data/<name>.parquet`)
|
|
38
|
+
* during a local `vite dev` by streaming materialized artifacts from Mako.
|
|
39
|
+
*/
|
|
40
|
+
export function makoData(options?: MakoDataOptions): Plugin;
|
|
41
|
+
export default makoData;
|
package/vite.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// @makoai/app-sdk/vite — data bindings for a LOCAL `vite dev`.
|
|
2
|
+
//
|
|
3
|
+
// Inside Mako's sandbox the dev server is launched by Mako, which answers
|
|
4
|
+
// `__data/<name>.parquet` itself. On a laptop nothing does, so Vite's SPA
|
|
5
|
+
// fallback returns index.html and DuckDB fails with "footer != PAR1". This
|
|
6
|
+
// plugin is the laptop's answer: it lists the app's bindings/*.sql as
|
|
7
|
+
// __data/index.json and streams each binding's materialized parquet from the
|
|
8
|
+
// Mako API, authenticated with the workspace API key in the repo's .env.
|
|
9
|
+
//
|
|
10
|
+
// Plain ESM, Node built-ins only — like the rest of this package.
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { findCredential, getAccessToken } from "./credentials.js";
|
|
14
|
+
|
|
15
|
+
const BINDING_NAME = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
|
|
16
|
+
const DEFAULT_REVALIDATE_MS = 5 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
function findRepoRoot(start) {
|
|
19
|
+
let dir = path.resolve(start);
|
|
20
|
+
for (;;) {
|
|
21
|
+
if (
|
|
22
|
+
fs.existsSync(path.join(dir, ".mako", "workspace.json")) ||
|
|
23
|
+
fs.existsSync(path.join(dir, ".git"))
|
|
24
|
+
) {
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
const parent = path.dirname(dir);
|
|
28
|
+
if (parent === dir) return path.resolve(start, "..", "..");
|
|
29
|
+
dir = parent;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Minimal .env reader: KEY=VALUE lines, # comments, optional quotes. */
|
|
34
|
+
function readDotenv(file) {
|
|
35
|
+
const out = {};
|
|
36
|
+
let text;
|
|
37
|
+
try {
|
|
38
|
+
text = fs.readFileSync(file, "utf8");
|
|
39
|
+
} catch {
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
for (const raw of text.split("\n")) {
|
|
43
|
+
const line = raw.trim();
|
|
44
|
+
if (!line || line.startsWith("#")) continue;
|
|
45
|
+
const eq = line.indexOf("=");
|
|
46
|
+
if (eq <= 0) continue;
|
|
47
|
+
const key = line.slice(0, eq).trim().replace(/^export\s+/, "");
|
|
48
|
+
let value = line.slice(eq + 1).trim();
|
|
49
|
+
if (
|
|
50
|
+
(value.startsWith('"') && value.endsWith('"')) ||
|
|
51
|
+
(value.startsWith("'") && value.endsWith("'"))
|
|
52
|
+
) {
|
|
53
|
+
value = value.slice(1, -1);
|
|
54
|
+
}
|
|
55
|
+
out[key] = value;
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function readWorkspaceJson(repoRoot) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(
|
|
63
|
+
fs.readFileSync(path.join(repoRoot, ".mako", "workspace.json"), "utf8"),
|
|
64
|
+
);
|
|
65
|
+
} catch {
|
|
66
|
+
return {};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function resolveMakoContext(appDir, options = {}) {
|
|
71
|
+
const repoRoot = options.repoRoot ?? findRepoRoot(appDir);
|
|
72
|
+
const dotenv = readDotenv(path.join(repoRoot, ".env"));
|
|
73
|
+
const ws = readWorkspaceJson(repoRoot);
|
|
74
|
+
const env = (name) => process.env[name] ?? dotenv[name];
|
|
75
|
+
const apiUrl = (
|
|
76
|
+
options.apiUrl ??
|
|
77
|
+
env("MAKO_API_URL") ??
|
|
78
|
+
ws.apiUrl ??
|
|
79
|
+
""
|
|
80
|
+
).replace(/\/+$/, "");
|
|
81
|
+
return {
|
|
82
|
+
repoRoot,
|
|
83
|
+
apiUrl,
|
|
84
|
+
apiKey: options.apiKey ?? env("MAKO_API_KEY") ?? "",
|
|
85
|
+
workspaceId: options.workspaceId ?? env("MAKO_WORKSPACE_ID") ?? ws.workspaceId ?? "",
|
|
86
|
+
slug: options.slug ?? path.basename(path.resolve(appDir)),
|
|
87
|
+
bindingsDir: path.join(appDir, "bindings"),
|
|
88
|
+
cacheDir: path.join(appDir, "node_modules", ".mako-data"),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function listBindings(bindingsDir) {
|
|
93
|
+
try {
|
|
94
|
+
return fs
|
|
95
|
+
.readdirSync(bindingsDir)
|
|
96
|
+
.filter((f) => f.endsWith(".sql"))
|
|
97
|
+
.map((f) => f.slice(0, -4))
|
|
98
|
+
.filter((n) => BINDING_NAME.test(n))
|
|
99
|
+
.sort();
|
|
100
|
+
} catch {
|
|
101
|
+
return [];
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function json(res, status, body) {
|
|
106
|
+
res.statusCode = status;
|
|
107
|
+
res.setHeader("content-type", "application/json");
|
|
108
|
+
res.end(JSON.stringify(body));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function makoData(options = {}) {
|
|
112
|
+
return {
|
|
113
|
+
name: "mako-data",
|
|
114
|
+
apply: "serve",
|
|
115
|
+
configureServer(server) {
|
|
116
|
+
const appDir = server.config.root;
|
|
117
|
+
const ctx = resolveMakoContext(appDir, options);
|
|
118
|
+
const revalidateMs = options.revalidateMs ?? DEFAULT_REVALIDATE_MS;
|
|
119
|
+
const bindings = listBindings(ctx.bindingsDir);
|
|
120
|
+
// Credentials: an API key (env or .env) wins; otherwise the token
|
|
121
|
+
// `mako login` stored — refreshed on demand, so a laptop that signed in
|
|
122
|
+
// once keeps working without ever pasting a key.
|
|
123
|
+
const loggedIn = !ctx.apiKey && !!findCredential(ctx.apiUrl, ctx.workspaceId);
|
|
124
|
+
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)");
|
|
127
|
+
if (!ctx.workspaceId) problems.push("workspace id unknown (.mako/workspace.json or MAKO_WORKSPACE_ID)");
|
|
128
|
+
const appBase = () =>
|
|
129
|
+
`${ctx.apiUrl}/api/workspaces/${encodeURIComponent(ctx.workspaceId)}/apps/${encodeURIComponent(ctx.slug)}`;
|
|
130
|
+
const headers = async () => ({
|
|
131
|
+
authorization: `Bearer ${ctx.apiKey || (await getAccessToken(ctx.apiUrl, ctx.workspaceId))}`,
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
server.config.logger.info(
|
|
135
|
+
` mako-data: ${bindings.length} binding(s) for apps/${ctx.slug}` +
|
|
136
|
+
(problems.length
|
|
137
|
+
? ` — NOT CONNECTED: ${problems.join("; ")} (see CLAUDE.md → Credentials)`
|
|
138
|
+
: ` via ${ctx.apiUrl} (${ctx.apiKey ? "API key" : "mako login"})`),
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
async function fetchArtifact(name) {
|
|
142
|
+
const url = `${appBase()}/bindings/${encodeURIComponent(name)}/artifact`;
|
|
143
|
+
let res = await fetch(url, { headers: await headers() });
|
|
144
|
+
if (res.status === 404 && options.materialize !== false) {
|
|
145
|
+
// Never materialized (or a live binding): build it now, then read.
|
|
146
|
+
const built = await fetch(
|
|
147
|
+
`${appBase()}/bindings/${encodeURIComponent(name)}/materialize`,
|
|
148
|
+
{ method: "POST", headers: await headers() },
|
|
149
|
+
);
|
|
150
|
+
if (!built.ok) {
|
|
151
|
+
const text = await built.text().catch(() => "");
|
|
152
|
+
throw new Error(`materialize ${name}: HTTP ${built.status} ${text.slice(0, 300)}`);
|
|
153
|
+
}
|
|
154
|
+
res = await fetch(url, { headers: await headers() });
|
|
155
|
+
}
|
|
156
|
+
if (!res.ok) {
|
|
157
|
+
const text = await res.text().catch(() => "");
|
|
158
|
+
throw new Error(`artifact ${name}: HTTP ${res.status} ${text.slice(0, 300)}`);
|
|
159
|
+
}
|
|
160
|
+
return Buffer.from(await res.arrayBuffer());
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
server.middlewares.use(async (req, res, next) => {
|
|
164
|
+
const [pathname, query = ""] = (req.url || "").split("?");
|
|
165
|
+
if (pathname === "/__data/index.json") {
|
|
166
|
+
return json(res, 200, listBindings(ctx.bindingsDir));
|
|
167
|
+
}
|
|
168
|
+
const match = /^\/__data\/([^/]+)\.parquet$/.exec(pathname);
|
|
169
|
+
if (!match) return next();
|
|
170
|
+
const name = decodeURIComponent(match[1]);
|
|
171
|
+
if (!BINDING_NAME.test(name)) return json(res, 400, { error: "invalid binding name" });
|
|
172
|
+
if (problems.length) {
|
|
173
|
+
return json(res, 503, {
|
|
174
|
+
error: `mako-data is not connected: ${problems.join("; ")}`,
|
|
175
|
+
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
|
+
});
|
|
177
|
+
}
|
|
178
|
+
const cached = path.join(ctx.cacheDir, `${name}.parquet`);
|
|
179
|
+
const refresh = /(^|&)refresh(=|&|$)/.test(query);
|
|
180
|
+
try {
|
|
181
|
+
const stat = fs.statSync(cached, { throwIfNoEntry: false });
|
|
182
|
+
const fresh = stat && Date.now() - stat.mtimeMs < revalidateMs;
|
|
183
|
+
if (!refresh && fresh) {
|
|
184
|
+
res.setHeader("content-type", "application/vnd.apache.parquet");
|
|
185
|
+
res.setHeader("x-mako-data", "cache");
|
|
186
|
+
return fs.createReadStream(cached).pipe(res);
|
|
187
|
+
}
|
|
188
|
+
const buf = await fetchArtifact(name);
|
|
189
|
+
fs.mkdirSync(ctx.cacheDir, { recursive: true });
|
|
190
|
+
fs.writeFileSync(cached, buf);
|
|
191
|
+
res.setHeader("content-type", "application/vnd.apache.parquet");
|
|
192
|
+
res.setHeader("content-length", String(buf.length));
|
|
193
|
+
res.setHeader("x-mako-data", "api");
|
|
194
|
+
res.end(buf);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
197
|
+
server.config.logger.error(` mako-data: ${message}`);
|
|
198
|
+
if (fs.existsSync(cached)) {
|
|
199
|
+
// Stale beats nothing while offline.
|
|
200
|
+
res.setHeader("content-type", "application/vnd.apache.parquet");
|
|
201
|
+
res.setHeader("x-mako-data", "stale");
|
|
202
|
+
return fs.createReadStream(cached).pipe(res);
|
|
203
|
+
}
|
|
204
|
+
json(res, 502, { error: message });
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export default makoData;
|