@surfaces-ui/dev-server 0.5.0 → 0.7.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/NOTICE CHANGED
@@ -2,3 +2,53 @@ Surfaces UI
2
2
  Copyright 2026 Josh Schoen
3
3
 
4
4
  This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ --------------------------------------------------------------------------------
7
+
8
+ @surfaces-ui/icons includes drawings from Lucide (https://lucide.dev), taken
9
+ from lucide-static 1.84.0. Other packages include some of them by depending on
10
+ it or by bundling it. They are used under this license:
11
+
12
+ ISC License
13
+
14
+ Copyright (c) 2026 Lucide Icons and Contributors
15
+
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted, provided that the above
18
+ copyright notice and this permission notice appear in all copies.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
21
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
22
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
23
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
25
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
26
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27
+
28
+ ---
29
+
30
+ The following Lucide icons are derived from the Feather project:
31
+
32
+ airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
33
+
34
+ The MIT License (MIT) (for the icons listed above)
35
+
36
+ Copyright (c) 2013-present Cole Bemis
37
+
38
+ Permission is hereby granted, free of charge, to any person obtaining a copy
39
+ of this software and associated documentation files (the "Software"), to deal
40
+ in the Software without restriction, including without limitation the rights
41
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
42
+ copies of the Software, and to permit persons to whom the Software is
43
+ furnished to do so, subject to the following conditions:
44
+
45
+ The above copyright notice and this permission notice shall be included in all
46
+ copies or substantial portions of the Software.
47
+
48
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
51
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
53
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
54
+ SOFTWARE.
package/dist/config.d.ts CHANGED
@@ -218,14 +218,26 @@ export declare function loadConfig(file: string): Promise<{
218
218
  config: SurfacesConfig;
219
219
  dir: string;
220
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;
221
228
  /**
222
229
  * A config made from the environment, for where there is no project folder
223
230
  * to keep a config file in (a plugin in a desktop app, whose settings screen
224
231
  * fills these in). One source, a database reached through its own MCP server:
225
232
  *
226
- * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`.
233
+ * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`,
234
+ * read loosely ("PostgreSQL"). Left empty, it is told from the server's
235
+ * command or the connection string's scheme, and asked for only when
236
+ * neither names a database.
227
237
  * - `SURFACES_SOURCE_SERVER`: the command that starts the database's MCP
228
238
  * server (`uvx teradata-mcp-server`), or the address of one (`https://…`).
239
+ * A program named without its folder is looked for on PATH and where such
240
+ * programs are usually installed (`findProgram`).
229
241
  * - `SURFACES_SOURCE_SECRET`: the connection string a local server reads, or
230
242
  * the token a remote one takes. It is handed to a local server under the
231
243
  * name in `SURFACES_SOURCE_SECRET_NAME` (`DATABASE_URI` unless said), and is
package/dist/config.js CHANGED
@@ -76,14 +76,73 @@ function withoutQuery(url) {
76
76
  function words(line) {
77
77
  return [...line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((match) => match[1] ?? match[2] ?? match[3]);
78
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
+ /** The part of a connection string before `://`, which names the database and holds nothing secret. */
113
+ function schemeOf(uri) {
114
+ const at = uri?.indexOf("://") ?? -1;
115
+ return at > 0 ? uri.slice(0, at) : undefined;
116
+ }
117
+ /** The database type a piece of text names (a typed setting, a server's command, a URI's scheme), or nothing. Read by plain words, never a pattern that could backtrack over someone else's text. */
118
+ function dialectFrom(text) {
119
+ const lower = text?.toLowerCase() ?? "";
120
+ if (lower === "")
121
+ return undefined;
122
+ const has = (...words) => words.some((word) => lower.includes(word));
123
+ if (has("teradata", "vantage"))
124
+ return "teradata";
125
+ if (has("postgres", "pgsql", "supabase") || lower === "pg")
126
+ return "postgres";
127
+ if (has("mysql", "mariadb"))
128
+ return "mysql";
129
+ if (has("duckdb", "motherduck"))
130
+ return "duckdb";
131
+ return undefined;
132
+ }
79
133
  /**
80
134
  * A config made from the environment, for where there is no project folder
81
135
  * to keep a config file in (a plugin in a desktop app, whose settings screen
82
136
  * fills these in). One source, a database reached through its own MCP server:
83
137
  *
84
- * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`.
138
+ * - `SURFACES_SOURCE_DIALECT`: `postgres`, `mysql`, `duckdb` or `teradata`,
139
+ * read loosely ("PostgreSQL"). Left empty, it is told from the server's
140
+ * command or the connection string's scheme, and asked for only when
141
+ * neither names a database.
85
142
  * - `SURFACES_SOURCE_SERVER`: the command that starts the database's MCP
86
143
  * server (`uvx teradata-mcp-server`), or the address of one (`https://…`).
144
+ * A program named without its folder is looked for on PATH and where such
145
+ * programs are usually installed (`findProgram`).
87
146
  * - `SURFACES_SOURCE_SECRET`: the connection string a local server reads, or
88
147
  * the token a remote one takes. It is handed to a local server under the
89
148
  * name in `SURFACES_SOURCE_SECRET_NAME` (`DATABASE_URI` unless said), and is
@@ -99,20 +158,32 @@ export function configFromEnv(env = process.env) {
99
158
  const text = value?.trim() ?? "";
100
159
  return text === "" || text.startsWith("${") || /^(none|sample data)$/i.test(text) ? undefined : text;
101
160
  };
102
- const dialect = set(env.SURFACES_SOURCE_DIALECT)?.toLowerCase();
161
+ const typed = set(env.SURFACES_SOURCE_DIALECT);
103
162
  const server = set(env.SURFACES_SOURCE_SERVER);
104
- if (!dialect && !server)
163
+ if (!typed && !server)
105
164
  return undefined;
106
- if (!dialect || !server)
107
- throw new Error(`A data source needs both its database type and its MCP server; ${dialect ? "the server" : "the database type"} is missing.`);
108
- if (dialect !== "postgres" && dialect !== "mysql" && dialect !== "duckdb" && dialect !== "teradata")
109
- throw new Error(`The database type must be postgres, mysql, duckdb or teradata, not "${dialect}".`);
110
- const common = { id: "data", displayName: set(env.SURFACES_SOURCE_NAME), engine: "mcp", dialect: dialect, database: set(env.SURFACES_SOURCE_DATABASE) };
165
+ if (!server)
166
+ throw new Error("A data source needs its database's MCP server; only the database type is filled in.");
167
+ // The type is typed by hand on some settings screens, so it is read loosely ("PostgreSQL", "Teradata Vantage"),
168
+ // and left empty it is told from the server's command and the scheme of the connection string.
169
+ const dialect = dialectFrom(typed) ?? (typed ? undefined : dialectFrom(server) ?? dialectFrom(schemeOf(set(env.SURFACES_SOURCE_SECRET))));
170
+ if (!dialect) {
171
+ throw new Error(typed
172
+ ? `The database type must be teradata, postgres, mysql or duckdb, not "${typed}".`
173
+ : "The database type could not be told from the server's command. Fill it in: teradata, postgres, mysql or duckdb.");
174
+ }
175
+ const common = { id: "data", displayName: set(env.SURFACES_SOURCE_NAME), engine: "mcp", dialect, database: set(env.SURFACES_SOURCE_DATABASE) };
111
176
  if (/^https?:\/\//i.test(server))
112
177
  return { sources: [{ ...common, server: { url: server, secret: set(env.SURFACES_SOURCE_SECRET) ? "SURFACES_SOURCE_SECRET" : undefined } }] };
113
- const [command, ...args] = words(server);
114
- if (!command)
178
+ const [program, ...args] = words(server);
179
+ if (!program)
115
180
  throw new Error("The MCP server's command is empty.");
181
+ // A desktop app starts this process without a shell's PATH, so the program is found here, and the folders it
182
+ // was looked for in are put on the PATH its own children get (uvx starts Python, npx starts Node).
183
+ const command = findProgram(program, env);
184
+ if (!command)
185
+ throw new Error(missingProgram(program));
186
+ env.PATH = [...new Set([...(env.PATH ?? "").split(path.delimiter).filter(Boolean), path.dirname(command), ...usualProgramFolders(env)])].join(path.delimiter);
116
187
  const name = set(env.SURFACES_SOURCE_SECRET_NAME) ?? "DATABASE_URI";
117
188
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
118
189
  throw new Error("The name the connection string is handed over under must be a plain environment variable name.");
@@ -229,7 +300,7 @@ export async function serverOptions(config, sources, dir = process.cwd()) {
229
300
  embedder = (await import(name)).localEmbedder();
230
301
  }
231
302
  catch {
232
- console.warn("[surfaces] @surfaces-ui/embedder-local is not installed; search will be keyword only.");
303
+ 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.");
233
304
  }
234
305
  }
235
306
  const seeded = config.seeds ? await loadSeeds() : undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAwF,kBAAkB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACpK,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAyB,oBAAoB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAEzG,OAAO,EAA0C,YAAY,IAAI,cAAc,EAAE,eAAe,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAC3K,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAsB,mBAAmB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAkB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAG1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAmB,SAAS,EAAE,iBAAiB,EAAE,YAAY,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AA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C,CAAC;QACnI,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAChB,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,iHAAiH;AACjH,SAAS,aAAa,CAAC,IAAiB;IACtC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC3B,IAAI,CAAC;YACH,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,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/**\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 * - `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 [command, ...args] = words(server);\n if (!command) throw new Error(\"The MCP server's command is empty.\");\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] @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,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAwF,kBAAkB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACpK,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EAAyB,oBAAoB,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAEzG,OAAO,EAA0C,YAAY,IAAI,cAAc,EAAE,eAAe,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAC3K,OAAO,EAAE,UAAU,EA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AK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAChB,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,iHAAiH;AACjH,SAAS,aAAa,CAAC,IAAiB;IACtC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC3B,IAAI,CAAC;YACH,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,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/** The part of a connection string before `://`, which names the database and holds nothing secret. */\nfunction schemeOf(uri: string | undefined): string | undefined {\n const at = uri?.indexOf(\"://\") ?? -1;\n return at > 0 ? uri!.slice(0, at) : undefined;\n}\n\n/** The database type a piece of text names (a typed setting, a server's command, a URI's scheme), or nothing. Read by plain words, never a pattern that could backtrack over someone else's text. */\nfunction dialectFrom(text: string | undefined): McpSourceConfig[\"dialect\"] | undefined {\n const lower = text?.toLowerCase() ?? \"\";\n if (lower === \"\") return undefined;\n const has = (...words: string[]) => words.some((word) => lower.includes(word));\n if (has(\"teradata\", \"vantage\")) return \"teradata\";\n if (has(\"postgres\", \"pgsql\", \"supabase\") || lower === \"pg\") return \"postgres\";\n if (has(\"mysql\", \"mariadb\")) return \"mysql\";\n if (has(\"duckdb\", \"motherduck\")) return \"duckdb\";\n return undefined;\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 * read loosely (\"PostgreSQL\"). Left empty, it is told from the server's\n * command or the connection string's scheme, and asked for only when\n * neither names a database.\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 typed = set(env.SURFACES_SOURCE_DIALECT);\n const server = set(env.SURFACES_SOURCE_SERVER);\n if (!typed && !server) return undefined;\n if (!server) throw new Error(\"A data source needs its database's MCP server; only the database type is filled in.\");\n // The type is typed by hand on some settings screens, so it is read loosely (\"PostgreSQL\", \"Teradata Vantage\"),\n // and left empty it is told from the server's command and the scheme of the connection string.\n const dialect = dialectFrom(typed) ?? (typed ? undefined : dialectFrom(server) ?? dialectFrom(schemeOf(set(env.SURFACES_SOURCE_SECRET))));\n if (!dialect) {\n throw new Error(\n typed\n ? `The database type must be teradata, postgres, mysql or duckdb, not \"${typed}\".`\n : \"The database type could not be told from the server's command. Fill it in: teradata, postgres, mysql or duckdb.\",\n );\n }\n const common = { id: \"data\", displayName: set(env.SURFACES_SOURCE_NAME), engine: \"mcp\" as const, 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.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Local Connect server for Surfaces UI data sources",
5
5
  "keywords": [
6
6
  "surfaces-ui",
@@ -39,32 +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.5.0",
43
- "@surfaces-ui/data": "0.5.0",
44
- "@surfaces-ui/discovery": "0.5.0",
45
- "@surfaces-ui/engine": "0.5.0",
46
- "@surfaces-ui/engine-datafusion": "0.5.0",
47
- "@surfaces-ui/engine-mcp": "0.5.0",
48
- "@surfaces-ui/engine-duckdb": "0.5.0",
49
- "@surfaces-ui/engine-service": "0.5.0",
50
- "@surfaces-ui/pipelines": "0.5.0",
51
- "@surfaces-ui/pipelines-dbt": "0.5.0",
52
- "@surfaces-ui/seeds": "0.5.0",
53
- "@surfaces-ui/proto": "0.5.0",
54
- "@surfaces-ui/engine-teradata": "0.5.0",
55
- "@surfaces-ui/sql": "0.5.0"
42
+ "@surfaces-ui/data": "0.7.0",
43
+ "@surfaces-ui/engine": "0.7.0",
44
+ "@surfaces-ui/discovery": "0.7.0",
45
+ "@surfaces-ui/engine-datafusion": "0.7.0",
46
+ "@surfaces-ui/agent": "0.7.0",
47
+ "@surfaces-ui/engine-mcp": "0.7.0",
48
+ "@surfaces-ui/engine-duckdb": "0.7.0",
49
+ "@surfaces-ui/engine-service": "0.7.0",
50
+ "@surfaces-ui/engine-teradata": "0.7.0",
51
+ "@surfaces-ui/seeds": "0.7.0",
52
+ "@surfaces-ui/sql": "0.7.0",
53
+ "@surfaces-ui/proto": "0.7.0",
54
+ "@surfaces-ui/pipelines-dbt": "0.7.0",
55
+ "@surfaces-ui/pipelines": "0.7.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/node": "^26.6.6",
59
- "@surfaces-ui/client-connect": "0.5.0"
59
+ "@surfaces-ui/client-connect": "0.7.0",
60
+ "@surfaces-ui/embedder-local": "0.7.0"
60
61
  },
61
62
  "bin": {
62
63
  "surfaces-dev": "./dist/cli.js",
63
64
  "surfaces-pipelines": "./dist/pipelines-cli.js"
64
65
  },
65
- "optionalDependencies": {
66
- "@surfaces-ui/embedder-local": "0.5.0"
67
- },
68
66
  "publishConfig": {
69
67
  "access": "public",
70
68
  "provenance": true