@surfaces-ui/dev-server 0.4.0 → 0.6.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/dist/config.d.ts CHANGED
@@ -77,7 +77,42 @@ export interface TeradataDriverSourceConfig {
77
77
  /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */
78
78
  databases?: string[];
79
79
  }
80
- export type SourceConfig = DuckDbSourceConfig | DataFusionSourceConfig | TeradataSourceConfig | TeradataDriverSourceConfig;
80
+ /**
81
+ * A database reached through its own MCP server (the Teradata MCP server, a
82
+ * Postgres or DuckDB one). The SQL for every sort, filter and page goes
83
+ * through that server's query tool, so its rows never pass through a model.
84
+ * Read-only: no kept results, no pipelines and no time travel.
85
+ *
86
+ * A local server is started from `command`; only the environment variables
87
+ * named in `env` are passed to it, so a connection string stays in the
88
+ * environment (or the git-ignored `.env.local`) and out of this file. A
89
+ * remote one is called at `url`, with the bearer token read from
90
+ * `<SECRET>_TOKEN`.
91
+ */
92
+ export interface McpSourceConfig {
93
+ id: string;
94
+ displayName?: string;
95
+ engine: "mcp";
96
+ /** The database behind the server, which decides the SQL written for it. */
97
+ dialect: "postgres" | "mysql" | "duckdb" | "teradata";
98
+ server: {
99
+ command: string;
100
+ args?: string[];
101
+ env?: string[];
102
+ } | {
103
+ url: string;
104
+ secret?: string;
105
+ };
106
+ /** The server's tool that runs a query, and its SQL argument. Found from the server's tool list when left out. */
107
+ tool?: string;
108
+ argument?: string;
109
+ /** Other arguments sent with every query, such as a project id. Never a credential. */
110
+ arguments?: Record<string, unknown>;
111
+ /** Teradata: the default database, and the databases listings cover when none is named. */
112
+ database?: string;
113
+ databases?: string[];
114
+ }
115
+ export type SourceConfig = DuckDbSourceConfig | DataFusionSourceConfig | TeradataSourceConfig | TeradataDriverSourceConfig | McpSourceConfig;
81
116
  export interface DiscoveryConfig {
82
117
  /**
83
118
  * "local" runs a small embedding model on this machine for semantic search
@@ -169,11 +204,47 @@ export declare function envSecrets(env?: Record<string, string | undefined>): (n
169
204
  /** Identity helper that gives `surfaces.config.ts` type checking. */
170
205
  export declare function defineConfig(config: SurfacesConfig): SurfacesConfig;
171
206
  export declare const CONFIG_FILES: string[];
207
+ /**
208
+ * Where a person keeps a config that belongs to no project: `SURFACES_HOME`,
209
+ * or `.surfaces` in their home directory. A server started by a desktop app
210
+ * has no project folder, so it looks here after its working directory. The
211
+ * git-ignored `.env.local` beside the config holds its secrets, as anywhere.
212
+ */
213
+ export declare function configHome(env?: Record<string, string | undefined>): string;
214
+ /** The config file to use: in the working directory, else in `configHome()`. */
215
+ export declare function findConfig(cwd?: string, env?: Record<string, string | undefined>): string | undefined;
172
216
  /** Loads a config file and resolves its relative paths. */
173
217
  export declare function loadConfig(file: string): Promise<{
174
218
  config: SurfacesConfig;
175
219
  dir: string;
176
220
  }>;
221
+ /**
222
+ * The full path of a program named without one (`uvx`), looked for on PATH and
223
+ * then where such programs are usually installed. A desktop app does not hand
224
+ * its children a shell's PATH, so `uvx` alone is often not found there though
225
+ * it is installed. Nothing when it is in none of those places.
226
+ */
227
+ export declare function findProgram(command: string, env?: Record<string, string | undefined>): string | undefined;
228
+ /**
229
+ * A config made from the environment, for where there is no project folder
230
+ * to keep a config file in (a plugin in a desktop app, whose settings screen
231
+ * fills these in). One source, a database reached through its own MCP server:
232
+ *
233
+ * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`.
234
+ * - `SURFACES_SOURCE_SERVER`: the command that starts the database's MCP
235
+ * server (`uvx teradata-mcp-server`), or the address of one (`https://…`).
236
+ * A program named without its folder is looked for on PATH and where such
237
+ * programs are usually installed (`findProgram`).
238
+ * - `SURFACES_SOURCE_SECRET`: the connection string a local server reads, or
239
+ * the token a remote one takes. It is handed to a local server under the
240
+ * name in `SURFACES_SOURCE_SECRET_NAME` (`DATABASE_URI` unless said), and is
241
+ * never written anywhere or shown.
242
+ * - `SURFACES_SOURCE_NAME`, `SURFACES_SOURCE_DATABASE`: a display name, and
243
+ * Teradata's default database.
244
+ *
245
+ * Nothing set gives `undefined`; a dialect or a server without the other is an error that says which is missing.
246
+ */
247
+ export declare function configFromEnv(env?: Record<string, string | undefined>): SurfacesConfig | undefined;
177
248
  /** Opens the engines a config describes. */
178
249
  export declare function openSources(config: SurfacesConfig, dir: string, resolveSecret?: (name: string) => DuckDbSecretValues | undefined | Promise<DuckDbSecretValues | undefined>): Promise<ServerSource[]>;
179
250
  /** The seeds package and the sources, pipelines and forms it adds. */
package/dist/config.js CHANGED
@@ -1,8 +1,12 @@
1
1
  import { createRequire } from "node:module";
2
+ import { existsSync } from "node:fs";
3
+ import os from "node:os";
2
4
  import path from "node:path";
3
5
  import { pathToFileURL } from "node:url";
4
6
  import { createDuckDbEngine, isRemotePath } from "@surfaces-ui/engine-duckdb";
5
7
  import { createDataFusionEngine } from "@surfaces-ui/engine-datafusion";
8
+ import { createMcpEngine, httpServer } from "@surfaces-ui/engine-mcp";
9
+ import { stdioServer } from "@surfaces-ui/engine-mcp/node";
6
10
  import { createTeradataEngine, driverClient } from "@surfaces-ui/engine-teradata";
7
11
  import { dbtPipelines as dbtPipelinesOf, defaultRelation, readArtifacts, semanticModelsFromDbt } from "@surfaces-ui/pipelines-dbt";
8
12
  import { dbtCommand, targetDir } from "@surfaces-ui/pipelines-dbt/node";
@@ -35,6 +39,24 @@ export function defineConfig(config) {
35
39
  return config;
36
40
  }
37
41
  export const CONFIG_FILES = ["surfaces.config.ts", "surfaces.config.mjs", "surfaces.config.js"];
42
+ /**
43
+ * Where a person keeps a config that belongs to no project: `SURFACES_HOME`,
44
+ * or `.surfaces` in their home directory. A server started by a desktop app
45
+ * has no project folder, so it looks here after its working directory. The
46
+ * git-ignored `.env.local` beside the config holds its secrets, as anywhere.
47
+ */
48
+ export function configHome(env = process.env) {
49
+ return env.SURFACES_HOME?.trim() || path.join(os.homedir(), ".surfaces");
50
+ }
51
+ /** The config file to use: in the working directory, else in `configHome()`. */
52
+ export function findConfig(cwd = process.cwd(), env = process.env) {
53
+ for (const dir of [cwd, configHome(env)]) {
54
+ const name = CONFIG_FILES.find((file) => existsSync(path.join(dir, file)));
55
+ if (name)
56
+ return path.join(dir, name);
57
+ }
58
+ return undefined;
59
+ }
38
60
  /** Loads a config file and resolves its relative paths. */
39
61
  export async function loadConfig(file) {
40
62
  const absolute = path.resolve(file);
@@ -45,6 +67,101 @@ export async function loadConfig(file) {
45
67
  }
46
68
  return { config, dir: path.dirname(absolute) };
47
69
  }
70
+ /** An address up to its query or fragment, which can hold a key. Cut by position, since a pattern that can backtrack over a long address is a way to stall the server. */
71
+ function withoutQuery(url) {
72
+ const cut = [url.indexOf("?"), url.indexOf("#")].filter((at) => at !== -1);
73
+ return cut.length === 0 ? url : url.slice(0, Math.min(...cut));
74
+ }
75
+ /** Splits a command line into the program and its arguments, keeping what is inside quotes together. */
76
+ function words(line) {
77
+ return [...line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((match) => match[1] ?? match[2] ?? match[3]);
78
+ }
79
+ /** Where the programs that start MCP servers are usually installed, for a host that starts this process without a shell's PATH (a desktop app). */
80
+ function usualProgramFolders(env) {
81
+ const home = env.HOME ?? env.USERPROFILE ?? "";
82
+ return ["/opt/homebrew/bin", "/usr/local/bin", ...(home ? [path.join(home, ".local", "bin"), path.join(home, ".cargo", "bin")] : []), path.dirname(process.execPath)];
83
+ }
84
+ /**
85
+ * The full path of a program named without one (`uvx`), looked for on PATH and
86
+ * then where such programs are usually installed. A desktop app does not hand
87
+ * its children a shell's PATH, so `uvx` alone is often not found there though
88
+ * it is installed. Nothing when it is in none of those places.
89
+ */
90
+ export function findProgram(command, env = process.env) {
91
+ if (command.includes("/") || command.includes("\\"))
92
+ return existsSync(command) ? command : undefined;
93
+ const folders = [...(env.PATH ?? "").split(path.delimiter).filter(Boolean), ...usualProgramFolders(env)];
94
+ const names = process.platform === "win32" ? [command, `${command}.exe`, `${command}.cmd`] : [command];
95
+ for (const folder of folders) {
96
+ for (const name of names) {
97
+ const full = path.join(folder, name);
98
+ if (existsSync(full))
99
+ return full;
100
+ }
101
+ }
102
+ return undefined;
103
+ }
104
+ /** What to tell a person whose database's MCP server cannot be started because the program that starts it is missing. */
105
+ function missingProgram(command) {
106
+ if (command === "uvx" || command === "uv")
107
+ return "This database's MCP server is started with uv, which is not installed on this computer. Install it (on a Mac: brew install uv; otherwise see https://docs.astral.sh/uv), then start a new session.";
108
+ if (command === "npx" || command === "node")
109
+ return "This database's MCP server is started with Node.js, which was not found on this computer. Install Node.js 22 or later (https://nodejs.org), then start a new session.";
110
+ return `The program that starts this database's MCP server, ${command}, was not found on this computer. Install it, or enter its full path in the plugin's settings.`;
111
+ }
112
+ /**
113
+ * A config made from the environment, for where there is no project folder
114
+ * to keep a config file in (a plugin in a desktop app, whose settings screen
115
+ * fills these in). One source, a database reached through its own MCP server:
116
+ *
117
+ * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`.
118
+ * - `SURFACES_SOURCE_SERVER`: the command that starts the database's MCP
119
+ * server (`uvx teradata-mcp-server`), or the address of one (`https://…`).
120
+ * A program named without its folder is looked for on PATH and where such
121
+ * programs are usually installed (`findProgram`).
122
+ * - `SURFACES_SOURCE_SECRET`: the connection string a local server reads, or
123
+ * the token a remote one takes. It is handed to a local server under the
124
+ * name in `SURFACES_SOURCE_SECRET_NAME` (`DATABASE_URI` unless said), and is
125
+ * never written anywhere or shown.
126
+ * - `SURFACES_SOURCE_NAME`, `SURFACES_SOURCE_DATABASE`: a display name, and
127
+ * Teradata's default database.
128
+ *
129
+ * Nothing set gives `undefined`; a dialect or a server without the other is an error that says which is missing.
130
+ */
131
+ export function configFromEnv(env = process.env) {
132
+ // A host that fills these in from a settings screen can leave one as an empty value, a "none" choice, or its own unfilled placeholder.
133
+ const set = (value) => {
134
+ const text = value?.trim() ?? "";
135
+ return text === "" || text.startsWith("${") || /^(none|sample data)$/i.test(text) ? undefined : text;
136
+ };
137
+ const dialect = set(env.SURFACES_SOURCE_DIALECT)?.toLowerCase();
138
+ const server = set(env.SURFACES_SOURCE_SERVER);
139
+ if (!dialect && !server)
140
+ return undefined;
141
+ if (!dialect || !server)
142
+ throw new Error(`A data source needs both its database type and its MCP server; ${dialect ? "the server" : "the database type"} is missing.`);
143
+ if (dialect !== "postgres" && dialect !== "mysql" && dialect !== "duckdb" && dialect !== "teradata")
144
+ throw new Error(`The database type must be postgres, mysql, duckdb or teradata, not "${dialect}".`);
145
+ const common = { id: "data", displayName: set(env.SURFACES_SOURCE_NAME), engine: "mcp", dialect: dialect, database: set(env.SURFACES_SOURCE_DATABASE) };
146
+ if (/^https?:\/\//i.test(server))
147
+ return { sources: [{ ...common, server: { url: server, secret: set(env.SURFACES_SOURCE_SECRET) ? "SURFACES_SOURCE_SECRET" : undefined } }] };
148
+ const [program, ...args] = words(server);
149
+ if (!program)
150
+ throw new Error("The MCP server's command is empty.");
151
+ // A desktop app starts this process without a shell's PATH, so the program is found here, and the folders it
152
+ // was looked for in are put on the PATH its own children get (uvx starts Python, npx starts Node).
153
+ const command = findProgram(program, env);
154
+ if (!command)
155
+ throw new Error(missingProgram(program));
156
+ env.PATH = [...new Set([...(env.PATH ?? "").split(path.delimiter).filter(Boolean), path.dirname(command), ...usualProgramFolders(env)])].join(path.delimiter);
157
+ const name = set(env.SURFACES_SOURCE_SECRET_NAME) ?? "DATABASE_URI";
158
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
159
+ throw new Error("The name the connection string is handed over under must be a plain environment variable name.");
160
+ const secret = set(env.SURFACES_SOURCE_SECRET);
161
+ if (secret)
162
+ env[name] = secret;
163
+ return { sources: [{ ...common, server: { command, args, env: [name] } }] };
164
+ }
48
165
  /** Opens the engines a config describes. */
49
166
  export async function openSources(config, dir, resolveSecret = envSecrets()) {
50
167
  const ids = new Set();
@@ -58,6 +175,26 @@ export async function openSources(config, dir, resolveSecret = envSecrets()) {
58
175
  sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.FILES, engine: await createDataFusionEngine({ baseUrl: source.baseUrl }) });
59
176
  continue;
60
177
  }
178
+ if (source.engine === "mcp") {
179
+ const server = source.server;
180
+ const secret = "url" in server ? server.secret : undefined;
181
+ // A source made from the environment (`configFromEnv`) keeps its token under this one name.
182
+ const token = secret === "SURFACES_SOURCE_SECRET" ? process.env.SURFACES_SOURCE_SECRET : secret ? (await resolveSecret(secret))?.token : undefined;
183
+ const engine = await createMcpEngine({
184
+ dialect: source.dialect,
185
+ transport: "url" in server ? httpServer(server.url, { token: () => token }) : stdioServer(server.command, server.args, { env: server.env }),
186
+ // A command line can hold a connection string, so only the program is shown; an address is shown without its query.
187
+ address: "url" in server ? withoutQuery(server.url) : server.command,
188
+ tool: source.tool,
189
+ argument: source.argument,
190
+ arguments: source.arguments,
191
+ database: source.database,
192
+ databases: source.databases,
193
+ });
194
+ const kind = source.dialect === "teradata" ? SourceKind.TERADATA : source.dialect === "postgres" ? SourceKind.POSTGRES : source.dialect === "mysql" ? SourceKind.MYSQL : SourceKind.DUCKDB;
195
+ sources.push({ id: source.id, displayName: source.displayName, kind, engine });
196
+ continue;
197
+ }
61
198
  if (source.engine === "teradata" && source.transport === "driver") {
62
199
  const engine = await createTeradataEngine({ client: driverClient(source.connect, { database: source.database }), database: source.database, databases: source.databases, address: source.address });
63
200
  sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });
@@ -133,7 +270,7 @@ export async function serverOptions(config, sources, dir = process.cwd()) {
133
270
  embedder = (await import(name)).localEmbedder();
134
271
  }
135
272
  catch {
136
- console.warn("[surfaces] @surfaces-ui/embedder-local is not installed; search will be keyword only.");
273
+ console.warn("[surfaces] Search by meaning needs @surfaces-ui/embedder-local, which is not installed (npm install @surfaces-ui/embedder-local); search will be by keyword only.");
137
274
  }
138
275
  }
139
276
  const seeded = config.seeds ? await loadSeeds() : undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"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,EAAE,CAAC;QACZ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { AgentBackend } from \"@surfaces-ui/agent\";\nimport type { DataSource, ModelSettings } from \"@surfaces-ui/data\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Embedder } from \"@surfaces-ui/discovery\";\nimport { type DuckDbCatalog, type DuckDbConnection, type DuckDbSecretValues, type DuckDbTable, createDuckDbEngine, isRemotePath } from \"@surfaces-ui/engine-duckdb\";\nimport { createDataFusionEngine } from \"@surfaces-ui/engine-datafusion\";\nimport { type DriverConnection, createTeradataEngine, driverClient } from \"@surfaces-ui/engine-teradata\";\nimport type { PipelineDefinition } from \"@surfaces-ui/pipelines\";\nimport { type DbtNode, type DbtPipelinesOptions, dbtPipelines as dbtPipelinesOf, defaultRelation, readArtifacts, semanticModelsFromDbt } from \"@surfaces-ui/pipelines-dbt\";\nimport { dbtCommand, targetDir } from \"@surfaces-ui/pipelines-dbt/node\";\nimport { type SemanticModel, SemanticModelSchema, SourceKind } from \"@surfaces-ui/proto\";\nimport { type JsonValue, create } from \"@bufbuild/protobuf\";\nimport { semanticModelFromJson } from \"@surfaces-ui/data\";\nimport type { StoredResultsOptions } from \"@surfaces-ui/engine-service\";\nimport type { AgentServices, ServerSource, SurfacesServerOptions } from \"./server.js\";\nimport { fileDiscoveryStore } from \"./store.js\";\nimport { type FormConfig, fileForms, filePipelineStore, fileRunStore, fileSemantics, fileSurfaceLibrary } from \"./stores.js\";\n\n/** A DuckDB-backed source: files and lake tables exposed as named tables. */\nexport interface DuckDbSourceConfig {\n id: string;\n displayName?: string;\n engine: \"duckdb\";\n /** Local paths are relative to the config file; remote ones (`s3://`, `gs://`, `az://`, `https://`) need a connection that covers them. */\n tables: DuckDbTable[];\n /**\n * Object stores and web locations the tables read from. Each names a\n * secret; the values come from the server's environment (see `envSecrets`),\n * never from this file.\n */\n connections?: DuckDbConnection[];\n /** Catalogs to attach read-only: an Iceberg REST catalog, or a DuckDB database file. */\n catalogs?: DuckDbCatalog[];\n}\n\n/** A DataFusion server reached over its HTTP SQL endpoint. Read-only: no kept results and no pipelines. */\nexport interface DataFusionSourceConfig {\n id: string;\n displayName?: string;\n engine: \"datafusion\";\n /** Address of the server, e.g. http://localhost:8080. */\n baseUrl: string;\n}\n\n/**\n * A Teradata system reached through Teradata Query Service (its REST API).\n * Read-only: no kept results, no pipelines and no time travel. The password\n * or JWT is never written here: `secret` names it, and the server reads\n * `<NAME>_PASSWORD` or `<NAME>_TOKEN` from its environment (see `envSecrets`).\n */\nexport interface TeradataSourceConfig {\n id: string;\n displayName?: string;\n engine: \"teradata\";\n /** Address of Query Service up to `/systems`, e.g. https://vantage.example.com:1443. */\n baseUrl: string;\n /** The system name configured in Query Service. */\n system: string;\n /** Database user. Needed with a password; not with a JWT. The user should hold SELECT rights only. */\n user?: string;\n /** Name of the secret holding the password or JWT. */\n secret: string;\n /** Default database: unqualified names resolve here. */\n database?: string;\n /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */\n databases?: string[];\n transport?: \"query-service\";\n /** `explicit` (default) keeps one session set to UTC; `implicit` lets requests run side by side. See `QueryServiceOptions.session`. */\n session?: \"explicit\" | \"implicit\";\n}\n\n/**\n * A Teradata system reached through a driver connection the config opens\n * itself, for example with the `teradatasql` package installed outside this\n * repo. The server never imports a driver: `connect` is the config's own\n * code, and it reads the password from the environment, never from here.\n */\nexport interface TeradataDriverSourceConfig {\n id: string;\n displayName?: string;\n engine: \"teradata\";\n transport: \"driver\";\n /** Opens the connection, on first use. Its errors are not passed on, since a driver's message can repeat its settings. */\n connect(): DriverConnection | Promise<DriverConnection>;\n /** Shown as where this source connects, such as the host name. Never a credential. */\n address?: string;\n /** Default database: unqualified names resolve here. */\n database?: string;\n /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */\n databases?: string[];\n}\n\nexport type SourceConfig = DuckDbSourceConfig | DataFusionSourceConfig | TeradataSourceConfig | TeradataDriverSourceConfig;\n\nexport interface DiscoveryConfig {\n /**\n * \"local\" runs a small embedding model on this machine for semantic search\n * (needs `@surfaces-ui/embedder-local`; the model downloads once to a cache\n * outside the repo). Omit for keyword search only.\n */\n embedder?: \"local\";\n /** Source IDs whose data values may be profiled, shown and put in agent context. Default: none. */\n allowSampleValues?: string[];\n /** Folder for context packs and accepted descriptions, relative to the config file. Defaults to `.surfaces`. */\n storeDir?: string;\n}\n\nexport interface SurfacesConfig {\n /** May be left out when `seeds` is on. */\n sources?: SourceConfig[];\n /**\n * Serve the six synthetic industry models from `@surfaces-ui/seeds` as the\n * sources `retail`, `healthcare`, `fraud`, `telco`, `transportation` and\n * `manufacturing`, with their pipelines and forms. Their data is invented,\n * so their values may be shown (they are added to `allowSampleValues`).\n */\n seeds?: boolean;\n /**\n * Semantic models: the dimensions, measures and metrics of a project's\n * queries, which explorers and reports take their fields from. They are\n * kept as one JSON file each in `dir` (default `<storeDir>/semantic`), so\n * point it at a folder in your repo to review and commit them. `models`\n * (in the contract's JSON form) are added when the folder has none of\n * that name; with `seeds` on, each seed's starter models are too.\n */\n semantic?: { dir?: string; models?: JsonValue[] };\n /**\n * Forms people can submit. Fields and checks are set here; a client sends\n * only a form id and values. Submissions are appended to\n * `<storeDir>/forms/<form id>.jsonl`.\n */\n forms?: FormConfig[];\n discovery?: DiscoveryConfig;\n /** Port for `surfaces-dev`. Defaults to 5220. */\n port?: number;\n maxResultRows?: number;\n /**\n * Pipelines the server can run: datasets built from one another by SQL,\n * with data quality rules. The SQL lives here, never in the browser.\n */\n pipelines?: PipelineDefinition[];\n /**\n * Lets people save pipelines they approved (`SavePipeline`), typically ones\n * an agent proposed. Each is checked by the server before it is kept, as\n * one JSON file with its versions in `<storeDir>/pipelines/` (or `dir`).\n * Pipelines in `pipelines` stay as written here. Off by default.\n */\n savedPipelines?: boolean | { dir?: string };\n /**\n * dbt projects, served as pipelines read from their artifacts: models,\n * seeds, snapshots and sources as datasets, dbt's tests as checks, and its\n * runs and source freshness. dbt stays what builds them.\n */\n dbt?: DbtProjectConfig[];\n /** Keeping query results so views do not re-run the query. `false` turns it off. */\n storedResults?: StoredResultsOptions | false;\n /**\n * An agent to serve as `AgentService`, such as\n * `anthropicAgent({ client: new Anthropic(), system: catalogPrompt(analyticsCatalog) })`.\n * Its model key is read from this server's environment, never from config.\n * A function gets the server's data source, for tools that list tables or\n * run queries.\n */\n agent?: AgentBackend | ((dataSource: DataSource, services: AgentServices) => AgentBackend);\n /**\n * Which model each agent backend uses, shown and changed from a page\n * (`ModelService`). Build it with `modelSettings` from `@surfaces-ui/data`.\n * Keys stay in the environment; nothing here carries one.\n */\n models?: ModelSettings;\n}\n\n/**\n * Reads a named secret from environment variables, so credentials stay out\n * of config files and the repository. For the name `LAKE` it reads\n * `LAKE_KEY_ID`, `LAKE_SECRET`, `LAKE_SESSION_TOKEN`, `LAKE_CONNECTION_STRING`\n * `LAKE_TOKEN` and `LAKE_PASSWORD`, whichever are set.\n */\nexport function envSecrets(env: Record<string, string | undefined> = process.env): (name: string) => DuckDbSecretValues | undefined {\n return (name) => {\n const values: DuckDbSecretValues = {\n keyId: env[`${name}_KEY_ID`],\n secret: env[`${name}_SECRET`],\n sessionToken: env[`${name}_SESSION_TOKEN`],\n connectionString: env[`${name}_CONNECTION_STRING`],\n token: env[`${name}_TOKEN`],\n password: env[`${name}_PASSWORD`],\n };\n return Object.values(values).some((v) => v) ? values : undefined;\n };\n}\n\n/** Identity helper that gives `surfaces.config.ts` type checking. */\nexport function defineConfig(config: SurfacesConfig): SurfacesConfig {\n return config;\n}\n\nexport const CONFIG_FILES = [\"surfaces.config.ts\", \"surfaces.config.mjs\", \"surfaces.config.js\"];\n\n/** Loads a config file and resolves its relative paths. */\nexport async function loadConfig(file: string): Promise<{ config: SurfacesConfig; dir: string }> {\n const absolute = path.resolve(file);\n const module = (await import(pathToFileURL(absolute).href)) as { default?: SurfacesConfig };\n const config = module.default;\n if (!config || (!Array.isArray(config.sources) && !config.seeds)) {\n throw new Error(`${file} must default-export defineConfig({ sources: [...] }) or defineConfig({ seeds: true })`);\n }\n return { config, dir: path.dirname(absolute) };\n}\n\n/** Opens the engines a config describes. */\nexport async function openSources(\n config: SurfacesConfig,\n dir: string,\n resolveSecret: (name: string) => DuckDbSecretValues | undefined | Promise<DuckDbSecretValues | undefined> = envSecrets(),\n): Promise<ServerSource[]> {\n const ids = new Set<string>();\n const sources: ServerSource[] = [];\n const all = [...(config.sources ?? []), ...(config.seeds ? (await loadSeeds()).sources : [])];\n for (const source of all) {\n if (ids.has(source.id)) throw new Error(`Duplicate source id: ${source.id}`);\n ids.add(source.id);\n if (source.engine === \"datafusion\") {\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.FILES, engine: await createDataFusionEngine({ baseUrl: source.baseUrl }) });\n continue;\n }\n if (source.engine === \"teradata\" && source.transport === \"driver\") {\n const engine = await createTeradataEngine({ client: driverClient(source.connect, { database: source.database }), database: source.database, databases: source.databases, address: source.address });\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });\n continue;\n }\n if (source.engine === \"teradata\") {\n const engine = await createTeradataEngine({\n baseUrl: source.baseUrl,\n system: source.system,\n user: source.user,\n secret: source.secret,\n database: source.database,\n databases: source.databases,\n session: source.session,\n resolveSecret,\n });\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });\n continue;\n }\n const engine = await createDuckDbEngine({\n tables: source.tables.map((t) => ({ ...t, path: isRemotePath(t.path) ? t.path : path.resolve(dir, t.path) })),\n connections: source.connections,\n catalogs: source.catalogs?.map((c) => (c.kind === \"duckdb\" ? { ...c, uri: path.resolve(dir, c.uri) } : c)),\n resolveSecret,\n });\n sources.push({ id: source.id, displayName: source.displayName, engine });\n }\n return sources;\n}\n\ntype SeedsModule = typeof import(\"@surfaces-ui/seeds\");\n\n/** The seeds package and the sources, pipelines and forms it adds. */\nexport async function loadSeeds() {\n const module: SeedsModule = await import(\"@surfaces-ui/seeds\");\n const dataDir = path.join(path.dirname(createRequire(import.meta.url).resolve(\"@surfaces-ui/seeds/package.json\")), \"data\");\n const sources: DuckDbSourceConfig[] = module.seedSources(dataDir);\n const pipelines: PipelineDefinition[] = module.seeds.flatMap((seed) => seed.pipelines.map((p) => ({ ...p, sourceId: seed.id })));\n const forms: FormConfig[] = module.seeds.flatMap((seed) =>\n seed.forms.map((f) => ({ id: f.id, title: f.title, description: f.description, target: `${seed.id}.${f.table}`, fields: f.fields })),\n );\n const semanticModels: JsonValue[] = module.seeds.flatMap((seed) => module.seedSemanticModels(seed) as unknown as JsonValue[]);\n return { sources, pipelines, forms, semanticModels, ids: module.seeds.map((s) => s.id) };\n}\n\n/** A dbt project the server reads. Paths are relative to the config file. */\nexport interface DbtProjectConfig {\n /** The pipeline's id. Defaults to the project's name. */\n id?: string;\n name?: string;\n /** The source whose engine reads the warehouse dbt builds into. */\n sourceId: string;\n /** Where dbt writes its artifacts: the project's `target` directory. */\n targetDir: string;\n /**\n * Lets a person, or an agent they approve, start `dbt build` (or\n * `dbt compile` to check) from here. Needs `projectDir`. Credentials stay\n * in dbt's profile and this server's environment. Off by default: runs\n * made by dbt itself are reported either way.\n */\n build?: { projectDir: string; profilesDir?: string; target?: string; command?: string };\n /** Starter semantic models from dbt's semantic layer (semantic_manifest.json). On by default. */\n semanticModels?: boolean;\n /**\n * Put before each table's `schema.alias` when the source reads dbt's\n * database under a name of its own: the name a DuckDB source attaches the\n * database file as, for one.\n */\n relationPrefix?: string;\n}\n\n/** Each dbt project's backend options and its starter semantic models. A project whose artifacts cannot be read is reported and left out. */\nasync function dbtProjects(projects: DbtProjectConfig[], dir: string) {\n if (projects.length === 0) return [];\n const out: { options: Omit<DbtPipelinesOptions, \"onFinished\">; models: SemanticModel[] }[] = [];\n for (const project of projects) {\n const read = targetDir(path.resolve(dir, project.targetDir));\n try {\n const artifacts = await readArtifacts(read);\n const options = {\n ...(project.id ? { id: project.id } : {}),\n ...(project.name ? { name: project.name } : {}),\n sourceId: project.sourceId,\n read,\n ...(project.relationPrefix ? { relationOf: (node: DbtNode) => `${project.relationPrefix}.${defaultRelation(node)}` } : {}),\n ...(project.build ? { invoke: dbtCommand({ ...project.build, projectDir: path.resolve(dir, project.build.projectDir), ...(project.build.profilesDir ? { profilesDir: path.resolve(dir, project.build.profilesDir) } : {}) }) } : {}),\n };\n const semantic = project.semanticModels === false ? { models: [], skipped: [] } : semanticModelsFromDbt(artifacts, options);\n if (semantic.skipped.length > 0) console.warn(`[surfaces] dbt ${artifacts.manifest.metadata?.project_name}: ${semantic.skipped.length} semantic fields left out. ${semantic.skipped.join(\" \")}`);\n out.push({ options, models: semantic.models.map((m) => create(SemanticModelSchema, m)) });\n } catch (error) {\n console.warn(`[surfaces] The dbt project at ${project.targetDir} was left out: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return out;\n}\n\nexport async function serverOptions(config: SurfacesConfig, sources: ServerSource[], dir = process.cwd()): Promise<SurfacesServerOptions> {\n let embedder: Embedder | undefined;\n if (config.discovery?.embedder === \"local\") {\n try {\n const name = \"@surfaces-ui/embedder-local\";\n embedder = ((await import(name)) as { localEmbedder(): Embedder }).localEmbedder();\n } catch {\n console.warn(\"[surfaces] @surfaces-ui/embedder-local is not installed; search will be keyword only.\");\n }\n }\n const seeded = config.seeds ? await loadSeeds() : undefined;\n const storeDir = path.resolve(dir, config.discovery?.storeDir ?? \".surfaces\");\n const forms = [...(config.forms ?? []), ...(seeded?.forms ?? [])];\n const dbt = await dbtProjects(config.dbt ?? [], dir);\n return {\n sources,\n maxResultRows: config.maxResultRows,\n storedResults: config.storedResults,\n ...(config.agent ? { agent: config.agent } : {}),\n ...(config.models ? { models: config.models } : {}),\n pipelines: [...(config.pipelines ?? []), ...(seeded?.pipelines ?? [])],\n ...(dbt.length > 0 ? { externalPipelines: ({ onFinished }) => dbt.map((project) => dbtPipelinesOf({ ...project.options, onFinished })) } : {}),\n // Run history outlives a restart.\n pipelineRuns: fileRunStore(path.join(storeDir, \"pipeline-runs\")),\n ...(config.savedPipelines\n ? { savedPipelines: filePipelineStore(path.resolve(dir, (typeof config.savedPipelines === \"object\" && config.savedPipelines.dir) || path.join(storeDir, \"pipelines\"))) }\n : {}),\n forms: forms.length > 0 ? fileForms(path.join(storeDir, \"forms\"), forms) : undefined,\n library: fileSurfaceLibrary(path.join(storeDir, \"surfaces\")),\n semantics: fileSemantics(path.resolve(dir, config.semantic?.dir ?? path.join(storeDir, \"semantic\")), {\n models: withDbtModels(starterModels([...(config.semantic?.models ?? []), ...(seeded?.semanticModels ?? [])]), dbt.flatMap((p) => p.models)),\n }),\n discovery: {\n embedder,\n allowSampleValues: [...(config.discovery?.allowSampleValues ?? []), ...(seeded?.ids ?? [])],\n store: fileDiscoveryStore(storeDir),\n },\n };\n}\n\n/**\n * dbt's semantic models beside the others. Names are shared by every source,\n * so one whose name is taken is renamed after its project (orders becomes\n * shop_orders) and the rename is reported.\n */\nfunction withDbtModels(starters: SemanticModel[], fromDbt: SemanticModel[]): SemanticModel[] {\n const taken = new Set(starters.map((m) => m.name));\n const out = [...starters];\n for (const model of fromDbt) {\n let name = model.name;\n if (taken.has(name)) {\n name = `${model.dataset?.pipelineId ?? \"dbt\"}_${model.name}`.toLowerCase().replace(/[^a-z0-9_]+/g, \"_\").slice(0, 64);\n if (taken.has(name)) {\n console.warn(`[surfaces] dbt's semantic model ${model.name} was left out: the names ${model.name} and ${name} are taken.`);\n continue;\n }\n console.warn(`[surfaces] dbt's semantic model ${model.name} is named ${name} here, since another model is named ${model.name}.`);\n }\n taken.add(name);\n out.push(name === model.name ? model : { ...model, name });\n }\n return out;\n}\n\n/** Starter models from config, in the contract's JSON form; one that does not parse is reported and left out. */\nfunction starterModels(json: JsonValue[]): SemanticModel[] {\n return json.flatMap((item) => {\n try {\n return [semanticModelFromJson(item)];\n } catch (error) {\n console.warn(`[surfaces] A semantic model in the config was left out: ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n });\n}\n"]}
1
+ {"version":3,"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AAC,CAAC;QACvC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,CAAC,2DAA2D,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClI,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { AgentBackend } from \"@surfaces-ui/agent\";\nimport type { DataSource, ModelSettings } from \"@surfaces-ui/data\";\nimport { createRequire } from \"node:module\";\nimport { existsSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Embedder } from \"@surfaces-ui/discovery\";\nimport { type DuckDbCatalog, type DuckDbConnection, type DuckDbSecretValues, type DuckDbTable, createDuckDbEngine, isRemotePath } from \"@surfaces-ui/engine-duckdb\";\nimport { createDataFusionEngine } from \"@surfaces-ui/engine-datafusion\";\nimport { createMcpEngine, httpServer } from \"@surfaces-ui/engine-mcp\";\nimport { stdioServer } from \"@surfaces-ui/engine-mcp/node\";\nimport { type DriverConnection, createTeradataEngine, driverClient } from \"@surfaces-ui/engine-teradata\";\nimport type { PipelineDefinition } from \"@surfaces-ui/pipelines\";\nimport { type DbtNode, type DbtPipelinesOptions, dbtPipelines as dbtPipelinesOf, defaultRelation, readArtifacts, semanticModelsFromDbt } from \"@surfaces-ui/pipelines-dbt\";\nimport { dbtCommand, targetDir } from \"@surfaces-ui/pipelines-dbt/node\";\nimport { type SemanticModel, SemanticModelSchema, SourceKind } from \"@surfaces-ui/proto\";\nimport { type JsonValue, create } from \"@bufbuild/protobuf\";\nimport { semanticModelFromJson } from \"@surfaces-ui/data\";\nimport type { StoredResultsOptions } from \"@surfaces-ui/engine-service\";\nimport type { AgentServices, ServerSource, SurfacesServerOptions } from \"./server.js\";\nimport { fileDiscoveryStore } from \"./store.js\";\nimport { type FormConfig, fileForms, filePipelineStore, fileRunStore, fileSemantics, fileSurfaceLibrary } from \"./stores.js\";\n\n/** A DuckDB-backed source: files and lake tables exposed as named tables. */\nexport interface DuckDbSourceConfig {\n id: string;\n displayName?: string;\n engine: \"duckdb\";\n /** Local paths are relative to the config file; remote ones (`s3://`, `gs://`, `az://`, `https://`) need a connection that covers them. */\n tables: DuckDbTable[];\n /**\n * Object stores and web locations the tables read from. Each names a\n * secret; the values come from the server's environment (see `envSecrets`),\n * never from this file.\n */\n connections?: DuckDbConnection[];\n /** Catalogs to attach read-only: an Iceberg REST catalog, or a DuckDB database file. */\n catalogs?: DuckDbCatalog[];\n}\n\n/** A DataFusion server reached over its HTTP SQL endpoint. Read-only: no kept results and no pipelines. */\nexport interface DataFusionSourceConfig {\n id: string;\n displayName?: string;\n engine: \"datafusion\";\n /** Address of the server, e.g. http://localhost:8080. */\n baseUrl: string;\n}\n\n/**\n * A Teradata system reached through Teradata Query Service (its REST API).\n * Read-only: no kept results, no pipelines and no time travel. The password\n * or JWT is never written here: `secret` names it, and the server reads\n * `<NAME>_PASSWORD` or `<NAME>_TOKEN` from its environment (see `envSecrets`).\n */\nexport interface TeradataSourceConfig {\n id: string;\n displayName?: string;\n engine: \"teradata\";\n /** Address of Query Service up to `/systems`, e.g. https://vantage.example.com:1443. */\n baseUrl: string;\n /** The system name configured in Query Service. */\n system: string;\n /** Database user. Needed with a password; not with a JWT. The user should hold SELECT rights only. */\n user?: string;\n /** Name of the secret holding the password or JWT. */\n secret: string;\n /** Default database: unqualified names resolve here. */\n database?: string;\n /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */\n databases?: string[];\n transport?: \"query-service\";\n /** `explicit` (default) keeps one session set to UTC; `implicit` lets requests run side by side. See `QueryServiceOptions.session`. */\n session?: \"explicit\" | \"implicit\";\n}\n\n/**\n * A Teradata system reached through a driver connection the config opens\n * itself, for example with the `teradatasql` package installed outside this\n * repo. The server never imports a driver: `connect` is the config's own\n * code, and it reads the password from the environment, never from here.\n */\nexport interface TeradataDriverSourceConfig {\n id: string;\n displayName?: string;\n engine: \"teradata\";\n transport: \"driver\";\n /** Opens the connection, on first use. Its errors are not passed on, since a driver's message can repeat its settings. */\n connect(): DriverConnection | Promise<DriverConnection>;\n /** Shown as where this source connects, such as the host name. Never a credential. */\n address?: string;\n /** Default database: unqualified names resolve here. */\n database?: string;\n /** The databases listings, search and agent context cover when no database is named. Defaults to the default database. */\n databases?: string[];\n}\n\n/**\n * A database reached through its own MCP server (the Teradata MCP server, a\n * Postgres or DuckDB one). The SQL for every sort, filter and page goes\n * through that server's query tool, so its rows never pass through a model.\n * Read-only: no kept results, no pipelines and no time travel.\n *\n * A local server is started from `command`; only the environment variables\n * named in `env` are passed to it, so a connection string stays in the\n * environment (or the git-ignored `.env.local`) and out of this file. A\n * remote one is called at `url`, with the bearer token read from\n * `<SECRET>_TOKEN`.\n */\nexport interface McpSourceConfig {\n id: string;\n displayName?: string;\n engine: \"mcp\";\n /** The database behind the server, which decides the SQL written for it. */\n dialect: \"postgres\" | \"mysql\" | \"duckdb\" | \"teradata\";\n server: { command: string; args?: string[]; env?: string[] } | { url: string; secret?: string };\n /** The server's tool that runs a query, and its SQL argument. Found from the server's tool list when left out. */\n tool?: string;\n argument?: string;\n /** Other arguments sent with every query, such as a project id. Never a credential. */\n arguments?: Record<string, unknown>;\n /** Teradata: the default database, and the databases listings cover when none is named. */\n database?: string;\n databases?: string[];\n}\n\nexport type SourceConfig = DuckDbSourceConfig | DataFusionSourceConfig | TeradataSourceConfig | TeradataDriverSourceConfig | McpSourceConfig;\n\nexport interface DiscoveryConfig {\n /**\n * \"local\" runs a small embedding model on this machine for semantic search\n * (needs `@surfaces-ui/embedder-local`; the model downloads once to a cache\n * outside the repo). Omit for keyword search only.\n */\n embedder?: \"local\";\n /** Source IDs whose data values may be profiled, shown and put in agent context. Default: none. */\n allowSampleValues?: string[];\n /** Folder for context packs and accepted descriptions, relative to the config file. Defaults to `.surfaces`. */\n storeDir?: string;\n}\n\nexport interface SurfacesConfig {\n /** May be left out when `seeds` is on. */\n sources?: SourceConfig[];\n /**\n * Serve the six synthetic industry models from `@surfaces-ui/seeds` as the\n * sources `retail`, `healthcare`, `fraud`, `telco`, `transportation` and\n * `manufacturing`, with their pipelines and forms. Their data is invented,\n * so their values may be shown (they are added to `allowSampleValues`).\n */\n seeds?: boolean;\n /**\n * Semantic models: the dimensions, measures and metrics of a project's\n * queries, which explorers and reports take their fields from. They are\n * kept as one JSON file each in `dir` (default `<storeDir>/semantic`), so\n * point it at a folder in your repo to review and commit them. `models`\n * (in the contract's JSON form) are added when the folder has none of\n * that name; with `seeds` on, each seed's starter models are too.\n */\n semantic?: { dir?: string; models?: JsonValue[] };\n /**\n * Forms people can submit. Fields and checks are set here; a client sends\n * only a form id and values. Submissions are appended to\n * `<storeDir>/forms/<form id>.jsonl`.\n */\n forms?: FormConfig[];\n discovery?: DiscoveryConfig;\n /** Port for `surfaces-dev`. Defaults to 5220. */\n port?: number;\n maxResultRows?: number;\n /**\n * Pipelines the server can run: datasets built from one another by SQL,\n * with data quality rules. The SQL lives here, never in the browser.\n */\n pipelines?: PipelineDefinition[];\n /**\n * Lets people save pipelines they approved (`SavePipeline`), typically ones\n * an agent proposed. Each is checked by the server before it is kept, as\n * one JSON file with its versions in `<storeDir>/pipelines/` (or `dir`).\n * Pipelines in `pipelines` stay as written here. Off by default.\n */\n savedPipelines?: boolean | { dir?: string };\n /**\n * dbt projects, served as pipelines read from their artifacts: models,\n * seeds, snapshots and sources as datasets, dbt's tests as checks, and its\n * runs and source freshness. dbt stays what builds them.\n */\n dbt?: DbtProjectConfig[];\n /** Keeping query results so views do not re-run the query. `false` turns it off. */\n storedResults?: StoredResultsOptions | false;\n /**\n * An agent to serve as `AgentService`, such as\n * `anthropicAgent({ client: new Anthropic(), system: catalogPrompt(analyticsCatalog) })`.\n * Its model key is read from this server's environment, never from config.\n * A function gets the server's data source, for tools that list tables or\n * run queries.\n */\n agent?: AgentBackend | ((dataSource: DataSource, services: AgentServices) => AgentBackend);\n /**\n * Which model each agent backend uses, shown and changed from a page\n * (`ModelService`). Build it with `modelSettings` from `@surfaces-ui/data`.\n * Keys stay in the environment; nothing here carries one.\n */\n models?: ModelSettings;\n}\n\n/**\n * Reads a named secret from environment variables, so credentials stay out\n * of config files and the repository. For the name `LAKE` it reads\n * `LAKE_KEY_ID`, `LAKE_SECRET`, `LAKE_SESSION_TOKEN`, `LAKE_CONNECTION_STRING`\n * `LAKE_TOKEN` and `LAKE_PASSWORD`, whichever are set.\n */\nexport function envSecrets(env: Record<string, string | undefined> = process.env): (name: string) => DuckDbSecretValues | undefined {\n return (name) => {\n const values: DuckDbSecretValues = {\n keyId: env[`${name}_KEY_ID`],\n secret: env[`${name}_SECRET`],\n sessionToken: env[`${name}_SESSION_TOKEN`],\n connectionString: env[`${name}_CONNECTION_STRING`],\n token: env[`${name}_TOKEN`],\n password: env[`${name}_PASSWORD`],\n };\n return Object.values(values).some((v) => v) ? values : undefined;\n };\n}\n\n/** Identity helper that gives `surfaces.config.ts` type checking. */\nexport function defineConfig(config: SurfacesConfig): SurfacesConfig {\n return config;\n}\n\nexport const CONFIG_FILES = [\"surfaces.config.ts\", \"surfaces.config.mjs\", \"surfaces.config.js\"];\n\n/**\n * Where a person keeps a config that belongs to no project: `SURFACES_HOME`,\n * or `.surfaces` in their home directory. A server started by a desktop app\n * has no project folder, so it looks here after its working directory. The\n * git-ignored `.env.local` beside the config holds its secrets, as anywhere.\n */\nexport function configHome(env: Record<string, string | undefined> = process.env): string {\n return env.SURFACES_HOME?.trim() || path.join(os.homedir(), \".surfaces\");\n}\n\n/** The config file to use: in the working directory, else in `configHome()`. */\nexport function findConfig(cwd: string = process.cwd(), env: Record<string, string | undefined> = process.env): string | undefined {\n for (const dir of [cwd, configHome(env)]) {\n const name = CONFIG_FILES.find((file) => existsSync(path.join(dir, file)));\n if (name) return path.join(dir, name);\n }\n return undefined;\n}\n\n/** Loads a config file and resolves its relative paths. */\nexport async function loadConfig(file: string): Promise<{ config: SurfacesConfig; dir: string }> {\n const absolute = path.resolve(file);\n const module = (await import(pathToFileURL(absolute).href)) as { default?: SurfacesConfig };\n const config = module.default;\n if (!config || (!Array.isArray(config.sources) && !config.seeds)) {\n throw new Error(`${file} must default-export defineConfig({ sources: [...] }) or defineConfig({ seeds: true })`);\n }\n return { config, dir: path.dirname(absolute) };\n}\n\n/** An address up to its query or fragment, which can hold a key. Cut by position, since a pattern that can backtrack over a long address is a way to stall the server. */\nfunction withoutQuery(url: string): string {\n const cut = [url.indexOf(\"?\"), url.indexOf(\"#\")].filter((at) => at !== -1);\n return cut.length === 0 ? url : url.slice(0, Math.min(...cut));\n}\n\n/** Splits a command line into the program and its arguments, keeping what is inside quotes together. */\nfunction words(line: string): string[] {\n return [...line.matchAll(/\"([^\"]*)\"|'([^']*)'|(\\S+)/g)].map((match) => match[1] ?? match[2] ?? match[3]!);\n}\n\n/** Where the programs that start MCP servers are usually installed, for a host that starts this process without a shell's PATH (a desktop app). */\nfunction usualProgramFolders(env: Record<string, string | undefined>): string[] {\n const home = env.HOME ?? env.USERPROFILE ?? \"\";\n return [\"/opt/homebrew/bin\", \"/usr/local/bin\", ...(home ? [path.join(home, \".local\", \"bin\"), path.join(home, \".cargo\", \"bin\")] : []), path.dirname(process.execPath)];\n}\n\n/**\n * The full path of a program named without one (`uvx`), looked for on PATH and\n * then where such programs are usually installed. A desktop app does not hand\n * its children a shell's PATH, so `uvx` alone is often not found there though\n * it is installed. Nothing when it is in none of those places.\n */\nexport function findProgram(command: string, env: Record<string, string | undefined> = process.env): string | undefined {\n if (command.includes(\"/\") || command.includes(\"\\\\\")) return existsSync(command) ? command : undefined;\n const folders = [...(env.PATH ?? \"\").split(path.delimiter).filter(Boolean), ...usualProgramFolders(env)];\n const names = process.platform === \"win32\" ? [command, `${command}.exe`, `${command}.cmd`] : [command];\n for (const folder of folders) {\n for (const name of names) {\n const full = path.join(folder, name);\n if (existsSync(full)) return full;\n }\n }\n return undefined;\n}\n\n/** What to tell a person whose database's MCP server cannot be started because the program that starts it is missing. */\nfunction missingProgram(command: string): string {\n if (command === \"uvx\" || command === \"uv\") return \"This database's MCP server is started with uv, which is not installed on this computer. Install it (on a Mac: brew install uv; otherwise see https://docs.astral.sh/uv), then start a new session.\";\n if (command === \"npx\" || command === \"node\") return \"This database's MCP server is started with Node.js, which was not found on this computer. Install Node.js 22 or later (https://nodejs.org), then start a new session.\";\n return `The program that starts this database's MCP server, ${command}, was not found on this computer. Install it, or enter its full path in the plugin's settings.`;\n}\n\n/**\n * A config made from the environment, for where there is no project folder\n * to keep a config file in (a plugin in a desktop app, whose settings screen\n * fills these in). One source, a database reached through its own MCP server:\n *\n * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`.\n * - `SURFACES_SOURCE_SERVER`: the command that starts the database's MCP\n * server (`uvx teradata-mcp-server`), or the address of one (`https://…`).\n * A program named without its folder is looked for on PATH and where such\n * programs are usually installed (`findProgram`).\n * - `SURFACES_SOURCE_SECRET`: the connection string a local server reads, or\n * the token a remote one takes. It is handed to a local server under the\n * name in `SURFACES_SOURCE_SECRET_NAME` (`DATABASE_URI` unless said), and is\n * never written anywhere or shown.\n * - `SURFACES_SOURCE_NAME`, `SURFACES_SOURCE_DATABASE`: a display name, and\n * Teradata's default database.\n *\n * Nothing set gives `undefined`; a dialect or a server without the other is an error that says which is missing.\n */\nexport function configFromEnv(env: Record<string, string | undefined> = process.env): SurfacesConfig | undefined {\n // A host that fills these in from a settings screen can leave one as an empty value, a \"none\" choice, or its own unfilled placeholder.\n const set = (value: string | undefined) => {\n const text = value?.trim() ?? \"\";\n return text === \"\" || text.startsWith(\"${\") || /^(none|sample data)$/i.test(text) ? undefined : text;\n };\n const dialect = set(env.SURFACES_SOURCE_DIALECT)?.toLowerCase();\n const server = set(env.SURFACES_SOURCE_SERVER);\n if (!dialect && !server) return undefined;\n if (!dialect || !server) throw new Error(`A data source needs both its database type and its MCP server; ${dialect ? \"the server\" : \"the database type\"} is missing.`);\n if (dialect !== \"postgres\" && dialect !== \"mysql\" && dialect !== \"duckdb\" && dialect !== \"teradata\") throw new Error(`The database type must be postgres, mysql, duckdb or teradata, not \"${dialect}\".`);\n const common = { id: \"data\", displayName: set(env.SURFACES_SOURCE_NAME), engine: \"mcp\" as const, dialect: dialect as McpSourceConfig[\"dialect\"], database: set(env.SURFACES_SOURCE_DATABASE) };\n if (/^https?:\\/\\//i.test(server)) return { sources: [{ ...common, server: { url: server, secret: set(env.SURFACES_SOURCE_SECRET) ? \"SURFACES_SOURCE_SECRET\" : undefined } }] };\n const [program, ...args] = words(server);\n if (!program) throw new Error(\"The MCP server's command is empty.\");\n // A desktop app starts this process without a shell's PATH, so the program is found here, and the folders it\n // was looked for in are put on the PATH its own children get (uvx starts Python, npx starts Node).\n const command = findProgram(program, env);\n if (!command) throw new Error(missingProgram(program));\n env.PATH = [...new Set([...(env.PATH ?? \"\").split(path.delimiter).filter(Boolean), path.dirname(command), ...usualProgramFolders(env)])].join(path.delimiter);\n const name = set(env.SURFACES_SOURCE_SECRET_NAME) ?? \"DATABASE_URI\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(\"The name the connection string is handed over under must be a plain environment variable name.\");\n const secret = set(env.SURFACES_SOURCE_SECRET);\n if (secret) env[name] = secret;\n return { sources: [{ ...common, server: { command, args, env: [name] } }] };\n}\n\n/** Opens the engines a config describes. */\nexport async function openSources(\n config: SurfacesConfig,\n dir: string,\n resolveSecret: (name: string) => DuckDbSecretValues | undefined | Promise<DuckDbSecretValues | undefined> = envSecrets(),\n): Promise<ServerSource[]> {\n const ids = new Set<string>();\n const sources: ServerSource[] = [];\n const all = [...(config.sources ?? []), ...(config.seeds ? (await loadSeeds()).sources : [])];\n for (const source of all) {\n if (ids.has(source.id)) throw new Error(`Duplicate source id: ${source.id}`);\n ids.add(source.id);\n if (source.engine === \"datafusion\") {\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.FILES, engine: await createDataFusionEngine({ baseUrl: source.baseUrl }) });\n continue;\n }\n if (source.engine === \"mcp\") {\n const server = source.server;\n const secret = \"url\" in server ? server.secret : undefined;\n // A source made from the environment (`configFromEnv`) keeps its token under this one name.\n const token = secret === \"SURFACES_SOURCE_SECRET\" ? process.env.SURFACES_SOURCE_SECRET : secret ? (await resolveSecret(secret))?.token : undefined;\n const engine = await createMcpEngine({\n dialect: source.dialect,\n transport: \"url\" in server ? httpServer(server.url, { token: () => token }) : stdioServer(server.command, server.args, { env: server.env }),\n // A command line can hold a connection string, so only the program is shown; an address is shown without its query.\n address: \"url\" in server ? withoutQuery(server.url) : server.command,\n tool: source.tool,\n argument: source.argument,\n arguments: source.arguments,\n database: source.database,\n databases: source.databases,\n });\n const kind = source.dialect === \"teradata\" ? SourceKind.TERADATA : source.dialect === \"postgres\" ? SourceKind.POSTGRES : source.dialect === \"mysql\" ? SourceKind.MYSQL : SourceKind.DUCKDB;\n sources.push({ id: source.id, displayName: source.displayName, kind, engine });\n continue;\n }\n if (source.engine === \"teradata\" && source.transport === \"driver\") {\n const engine = await createTeradataEngine({ client: driverClient(source.connect, { database: source.database }), database: source.database, databases: source.databases, address: source.address });\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });\n continue;\n }\n if (source.engine === \"teradata\") {\n const engine = await createTeradataEngine({\n baseUrl: source.baseUrl,\n system: source.system,\n user: source.user,\n secret: source.secret,\n database: source.database,\n databases: source.databases,\n session: source.session,\n resolveSecret,\n });\n sources.push({ id: source.id, displayName: source.displayName, kind: SourceKind.TERADATA, engine });\n continue;\n }\n const engine = await createDuckDbEngine({\n tables: source.tables.map((t) => ({ ...t, path: isRemotePath(t.path) ? t.path : path.resolve(dir, t.path) })),\n connections: source.connections,\n catalogs: source.catalogs?.map((c) => (c.kind === \"duckdb\" ? { ...c, uri: path.resolve(dir, c.uri) } : c)),\n resolveSecret,\n });\n sources.push({ id: source.id, displayName: source.displayName, engine });\n }\n return sources;\n}\n\ntype SeedsModule = typeof import(\"@surfaces-ui/seeds\");\n\n/** The seeds package and the sources, pipelines and forms it adds. */\nexport async function loadSeeds() {\n const module: SeedsModule = await import(\"@surfaces-ui/seeds\");\n const dataDir = path.join(path.dirname(createRequire(import.meta.url).resolve(\"@surfaces-ui/seeds/package.json\")), \"data\");\n const sources: DuckDbSourceConfig[] = module.seedSources(dataDir);\n const pipelines: PipelineDefinition[] = module.seeds.flatMap((seed) => seed.pipelines.map((p) => ({ ...p, sourceId: seed.id })));\n const forms: FormConfig[] = module.seeds.flatMap((seed) =>\n seed.forms.map((f) => ({ id: f.id, title: f.title, description: f.description, target: `${seed.id}.${f.table}`, fields: f.fields })),\n );\n const semanticModels: JsonValue[] = module.seeds.flatMap((seed) => module.seedSemanticModels(seed) as unknown as JsonValue[]);\n return { sources, pipelines, forms, semanticModels, ids: module.seeds.map((s) => s.id) };\n}\n\n/** A dbt project the server reads. Paths are relative to the config file. */\nexport interface DbtProjectConfig {\n /** The pipeline's id. Defaults to the project's name. */\n id?: string;\n name?: string;\n /** The source whose engine reads the warehouse dbt builds into. */\n sourceId: string;\n /** Where dbt writes its artifacts: the project's `target` directory. */\n targetDir: string;\n /**\n * Lets a person, or an agent they approve, start `dbt build` (or\n * `dbt compile` to check) from here. Needs `projectDir`. Credentials stay\n * in dbt's profile and this server's environment. Off by default: runs\n * made by dbt itself are reported either way.\n */\n build?: { projectDir: string; profilesDir?: string; target?: string; command?: string };\n /** Starter semantic models from dbt's semantic layer (semantic_manifest.json). On by default. */\n semanticModels?: boolean;\n /**\n * Put before each table's `schema.alias` when the source reads dbt's\n * database under a name of its own: the name a DuckDB source attaches the\n * database file as, for one.\n */\n relationPrefix?: string;\n}\n\n/** Each dbt project's backend options and its starter semantic models. A project whose artifacts cannot be read is reported and left out. */\nasync function dbtProjects(projects: DbtProjectConfig[], dir: string) {\n if (projects.length === 0) return [];\n const out: { options: Omit<DbtPipelinesOptions, \"onFinished\">; models: SemanticModel[] }[] = [];\n for (const project of projects) {\n const read = targetDir(path.resolve(dir, project.targetDir));\n try {\n const artifacts = await readArtifacts(read);\n const options = {\n ...(project.id ? { id: project.id } : {}),\n ...(project.name ? { name: project.name } : {}),\n sourceId: project.sourceId,\n read,\n ...(project.relationPrefix ? { relationOf: (node: DbtNode) => `${project.relationPrefix}.${defaultRelation(node)}` } : {}),\n ...(project.build ? { invoke: dbtCommand({ ...project.build, projectDir: path.resolve(dir, project.build.projectDir), ...(project.build.profilesDir ? { profilesDir: path.resolve(dir, project.build.profilesDir) } : {}) }) } : {}),\n };\n const semantic = project.semanticModels === false ? { models: [], skipped: [] } : semanticModelsFromDbt(artifacts, options);\n if (semantic.skipped.length > 0) console.warn(`[surfaces] dbt ${artifacts.manifest.metadata?.project_name}: ${semantic.skipped.length} semantic fields left out. ${semantic.skipped.join(\" \")}`);\n out.push({ options, models: semantic.models.map((m) => create(SemanticModelSchema, m)) });\n } catch (error) {\n console.warn(`[surfaces] The dbt project at ${project.targetDir} was left out: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return out;\n}\n\nexport async function serverOptions(config: SurfacesConfig, sources: ServerSource[], dir = process.cwd()): Promise<SurfacesServerOptions> {\n let embedder: Embedder | undefined;\n if (config.discovery?.embedder === \"local\") {\n try {\n const name = \"@surfaces-ui/embedder-local\";\n embedder = ((await import(name)) as { localEmbedder(): Embedder }).localEmbedder();\n } catch {\n console.warn(\"[surfaces] Search by meaning needs @surfaces-ui/embedder-local, which is not installed (npm install @surfaces-ui/embedder-local); search will be by keyword only.\");\n }\n }\n const seeded = config.seeds ? await loadSeeds() : undefined;\n const storeDir = path.resolve(dir, config.discovery?.storeDir ?? \".surfaces\");\n const forms = [...(config.forms ?? []), ...(seeded?.forms ?? [])];\n const dbt = await dbtProjects(config.dbt ?? [], dir);\n return {\n sources,\n maxResultRows: config.maxResultRows,\n storedResults: config.storedResults,\n ...(config.agent ? { agent: config.agent } : {}),\n ...(config.models ? { models: config.models } : {}),\n pipelines: [...(config.pipelines ?? []), ...(seeded?.pipelines ?? [])],\n ...(dbt.length > 0 ? { externalPipelines: ({ onFinished }) => dbt.map((project) => dbtPipelinesOf({ ...project.options, onFinished })) } : {}),\n // Run history outlives a restart.\n pipelineRuns: fileRunStore(path.join(storeDir, \"pipeline-runs\")),\n ...(config.savedPipelines\n ? { savedPipelines: filePipelineStore(path.resolve(dir, (typeof config.savedPipelines === \"object\" && config.savedPipelines.dir) || path.join(storeDir, \"pipelines\"))) }\n : {}),\n forms: forms.length > 0 ? fileForms(path.join(storeDir, \"forms\"), forms) : undefined,\n library: fileSurfaceLibrary(path.join(storeDir, \"surfaces\")),\n semantics: fileSemantics(path.resolve(dir, config.semantic?.dir ?? path.join(storeDir, \"semantic\")), {\n models: withDbtModels(starterModels([...(config.semantic?.models ?? []), ...(seeded?.semanticModels ?? [])]), dbt.flatMap((p) => p.models)),\n }),\n discovery: {\n embedder,\n allowSampleValues: [...(config.discovery?.allowSampleValues ?? []), ...(seeded?.ids ?? [])],\n store: fileDiscoveryStore(storeDir),\n },\n };\n}\n\n/**\n * dbt's semantic models beside the others. Names are shared by every source,\n * so one whose name is taken is renamed after its project (orders becomes\n * shop_orders) and the rename is reported.\n */\nfunction withDbtModels(starters: SemanticModel[], fromDbt: SemanticModel[]): SemanticModel[] {\n const taken = new Set(starters.map((m) => m.name));\n const out = [...starters];\n for (const model of fromDbt) {\n let name = model.name;\n if (taken.has(name)) {\n name = `${model.dataset?.pipelineId ?? \"dbt\"}_${model.name}`.toLowerCase().replace(/[^a-z0-9_]+/g, \"_\").slice(0, 64);\n if (taken.has(name)) {\n console.warn(`[surfaces] dbt's semantic model ${model.name} was left out: the names ${model.name} and ${name} are taken.`);\n continue;\n }\n console.warn(`[surfaces] dbt's semantic model ${model.name} is named ${name} here, since another model is named ${model.name}.`);\n }\n taken.add(name);\n out.push(name === model.name ? model : { ...model, name });\n }\n return out;\n}\n\n/** Starter models from config, in the contract's JSON form; one that does not parse is reported and left out. */\nfunction starterModels(json: JsonValue[]): SemanticModel[] {\n return json.flatMap((item) => {\n try {\n return [semanticModelFromJson(item)];\n } catch (error) {\n console.warn(`[surfaces] A semantic model in the config was left out: ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surfaces-ui/dev-server",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Local Connect server for Surfaces UI data sources",
5
5
  "keywords": [
6
6
  "surfaces-ui",
@@ -39,31 +39,30 @@
39
39
  "@connectrpc/connect": "^2.3.0",
40
40
  "@connectrpc/connect-node": "^2.3.0",
41
41
  "apache-arrow": "^21.2.0",
42
- "@surfaces-ui/agent": "0.4.0",
43
- "@surfaces-ui/data": "0.4.0",
44
- "@surfaces-ui/engine": "0.4.0",
45
- "@surfaces-ui/discovery": "0.4.0",
46
- "@surfaces-ui/engine-datafusion": "0.4.0",
47
- "@surfaces-ui/engine-duckdb": "0.4.0",
48
- "@surfaces-ui/engine-service": "0.4.0",
49
- "@surfaces-ui/engine-teradata": "0.4.0",
50
- "@surfaces-ui/pipelines": "0.4.0",
51
- "@surfaces-ui/proto": "0.4.0",
52
- "@surfaces-ui/pipelines-dbt": "0.4.0",
53
- "@surfaces-ui/seeds": "0.4.0",
54
- "@surfaces-ui/sql": "0.4.0"
42
+ "@surfaces-ui/agent": "0.6.0",
43
+ "@surfaces-ui/data": "0.6.0",
44
+ "@surfaces-ui/discovery": "0.6.0",
45
+ "@surfaces-ui/engine-datafusion": "0.6.0",
46
+ "@surfaces-ui/engine": "0.6.0",
47
+ "@surfaces-ui/engine-mcp": "0.6.0",
48
+ "@surfaces-ui/engine-service": "0.6.0",
49
+ "@surfaces-ui/engine-duckdb": "0.6.0",
50
+ "@surfaces-ui/engine-teradata": "0.6.0",
51
+ "@surfaces-ui/pipelines": "0.6.0",
52
+ "@surfaces-ui/proto": "0.6.0",
53
+ "@surfaces-ui/pipelines-dbt": "0.6.0",
54
+ "@surfaces-ui/seeds": "0.6.0",
55
+ "@surfaces-ui/sql": "0.6.0"
55
56
  },
56
57
  "devDependencies": {
57
58
  "@types/node": "^26.6.6",
58
- "@surfaces-ui/client-connect": "0.4.0"
59
+ "@surfaces-ui/client-connect": "0.6.0",
60
+ "@surfaces-ui/embedder-local": "0.6.0"
59
61
  },
60
62
  "bin": {
61
63
  "surfaces-dev": "./dist/cli.js",
62
64
  "surfaces-pipelines": "./dist/pipelines-cli.js"
63
65
  },
64
- "optionalDependencies": {
65
- "@surfaces-ui/embedder-local": "0.4.0"
66
- },
67
66
  "publishConfig": {
68
67
  "access": "public",
69
68
  "provenance": true