@surf-ai/sdk 0.1.6-beta → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/db/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/db/index.ts
@@ -24,32 +34,55 @@ __export(db_exports, {
24
34
  dbQuery: () => dbQuery,
25
35
  dbStatus: () => dbStatus,
26
36
  dbTableSchema: () => dbTableSchema,
27
- dbTables: () => dbTables
37
+ dbTables: () => dbTables,
38
+ syncSchema: () => syncSchema,
39
+ watchSchema: () => watchSchema
28
40
  });
29
41
  module.exports = __toCommonJS(db_exports);
30
42
 
31
- // src/data/client.ts
32
- var DEFAULT_PUBLIC_URL = "https://api.ask.surf/gateway/v1";
33
- function env(surfName, legacyName) {
34
- return process.env[surfName] || process.env[legacyName];
35
- }
36
- function resolveConfig() {
37
- const proxyBase = env("SURF_SANDBOX_PROXY_BASE", "DATA_PROXY_BASE");
38
- if (proxyBase) {
39
- return { baseUrl: proxyBase, headers: {} };
40
- }
41
- const gatewayUrl = env("SURF_DEPLOYED_GATEWAY_URL", "GATEWAY_URL");
42
- const appToken = env("SURF_DEPLOYED_APP_TOKEN", "APP_TOKEN");
43
- if (gatewayUrl && appToken) {
44
- return {
45
- baseUrl: `${gatewayUrl.replace(/\/$/, "")}/gateway/v1`,
46
- headers: { Authorization: `Bearer ${appToken}` }
47
- };
43
+ // src/core/config.ts
44
+ var DEFAULT_API_BASE_URL = "https://api.ask.surf/gateway/v1";
45
+ function trimTrailingSlashes(value) {
46
+ return String(value || "").replace(/\/+$/, "");
47
+ }
48
+ function readSurfApiConfig() {
49
+ return {
50
+ baseUrl: trimTrailingSlashes(process.env.SURF_API_BASE_URL || DEFAULT_API_BASE_URL),
51
+ apiKey: process.env.SURF_API_KEY
52
+ };
53
+ }
54
+ function requireSurfApiConfig() {
55
+ const config = readSurfApiConfig();
56
+ if (!config.apiKey) {
57
+ throw new Error("SURF_API_KEY is required");
48
58
  }
49
- return { baseUrl: DEFAULT_PUBLIC_URL, headers: {} };
59
+ return { baseUrl: config.baseUrl, apiKey: config.apiKey };
60
+ }
61
+
62
+ // src/core/transport.ts
63
+ function sleep(ms) {
64
+ return new Promise((resolve) => setTimeout(resolve, ms));
50
65
  }
51
66
  function normalizePath(path) {
52
- return String(path || "").replace(/^\/+/, "").replace(/^(?:proxy\/)+/, "");
67
+ return String(path || "").replace(/^\/+/, "");
68
+ }
69
+ function buildUrl(path, params) {
70
+ const { baseUrl } = requireSurfApiConfig();
71
+ const url = new URL(`${baseUrl}/${normalizePath(path)}`);
72
+ if (params) {
73
+ for (const [key, value] of Object.entries(params)) {
74
+ if (value != null) {
75
+ url.searchParams.set(key, String(value));
76
+ }
77
+ }
78
+ }
79
+ return url.toString();
80
+ }
81
+ function buildHeaders(extra) {
82
+ const { apiKey } = requireSurfApiConfig();
83
+ const headers = new Headers(extra);
84
+ headers.set("Authorization", `Bearer ${apiKey}`);
85
+ return headers;
53
86
  }
54
87
  async function fetchJson(url, init, retries = 1) {
55
88
  for (let attempt = 0; attempt <= retries; attempt++) {
@@ -59,36 +92,178 @@ async function fetchJson(url, init, retries = 1) {
59
92
  throw new Error(`API error ${res.status}: ${text2.slice(0, 200)}`);
60
93
  }
61
94
  const text = await res.text();
62
- if (text) return JSON.parse(text);
63
- if (attempt < retries) await new Promise((r) => setTimeout(r, 1e3));
95
+ if (text) {
96
+ return JSON.parse(text);
97
+ }
98
+ if (attempt < retries) {
99
+ await sleep(1e3);
100
+ }
64
101
  }
65
102
  throw new Error(`Empty response from ${url}`);
66
103
  }
67
- async function get(path, params) {
68
- const config = resolveConfig();
69
- const cleaned = {};
70
- if (params) {
71
- for (const [k, v] of Object.entries(params)) {
72
- if (v != null) cleaned[k] = String(v);
73
- }
74
- }
75
- const qs = Object.keys(cleaned).length ? "?" + new URLSearchParams(cleaned).toString() : "";
76
- return fetchJson(`${config.baseUrl}/${normalizePath(path)}${qs}`, {
77
- headers: config.headers
104
+ async function getJson(path, params) {
105
+ return fetchJson(buildUrl(path, params), {
106
+ headers: buildHeaders()
78
107
  });
79
108
  }
80
- async function post(path, body) {
81
- const config = resolveConfig();
82
- return fetchJson(`${config.baseUrl}/${normalizePath(path)}`, {
109
+ async function postJson(path, body) {
110
+ return fetchJson(buildUrl(path), {
83
111
  method: "POST",
84
- headers: { ...config.headers, "Content-Type": "application/json" },
112
+ headers: buildHeaders({
113
+ "Content-Type": "application/json"
114
+ }),
85
115
  body: body ? JSON.stringify(body) : void 0
86
116
  });
87
117
  }
88
118
 
119
+ // src/data/client.ts
120
+ async function get(path, params) {
121
+ return getJson(path, params);
122
+ }
123
+ async function post(path, body) {
124
+ return postJson(path, body);
125
+ }
126
+
127
+ // src/db/schema-sync.ts
128
+ var import_fs = __toESM(require("fs"), 1);
129
+ var syncing = false;
130
+ async function syncSchema(options) {
131
+ const { schemaPath, retries = 3, retryDelay = 2e3 } = options;
132
+ for (let i = 0; i < retries; i++) {
133
+ try {
134
+ await doSyncSchema(schemaPath);
135
+ return;
136
+ } catch (err) {
137
+ console.error(`DB schema sync attempt ${i + 1}/${retries} failed: ${err.message}`);
138
+ if (i < retries - 1) await new Promise((r) => setTimeout(r, retryDelay * (i + 1)));
139
+ }
140
+ }
141
+ console.error("DB schema sync failed after all retries");
142
+ }
143
+ async function doSyncSchema(schemaPath) {
144
+ if (syncing) return;
145
+ syncing = true;
146
+ try {
147
+ if (!import_fs.default.existsSync(schemaPath)) return;
148
+ let schema;
149
+ if (schemaPath.endsWith(".ts")) {
150
+ try {
151
+ schema = await import(`${schemaPath}?t=${Date.now()}`);
152
+ } catch (err) {
153
+ if (err instanceof SyntaxError) {
154
+ console.log("DB: schema file has syntax error, waiting for next change...");
155
+ return;
156
+ }
157
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
158
+ return;
159
+ }
160
+ throw err;
161
+ }
162
+ } else {
163
+ try {
164
+ delete require.cache[require.resolve(schemaPath)];
165
+ } catch {
166
+ }
167
+ try {
168
+ schema = require(schemaPath);
169
+ } catch (err) {
170
+ if (err instanceof SyntaxError) {
171
+ console.log("DB: schema file has syntax error, waiting for next change...");
172
+ return;
173
+ }
174
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
175
+ return;
176
+ }
177
+ throw err;
178
+ }
179
+ }
180
+ let getTableConfig;
181
+ try {
182
+ getTableConfig = require("drizzle-orm/pg-core").getTableConfig;
183
+ } catch {
184
+ return;
185
+ }
186
+ const tables = Object.values(schema).filter(
187
+ (t) => t && typeof t === "object" && /* @__PURE__ */ Symbol.for("drizzle:Name") in t
188
+ );
189
+ if (tables.length === 0) return;
190
+ await post("db/provision", {});
191
+ const existing = (await get("db/tables")).map((t) => t.name);
192
+ const missing = tables.filter((t) => !existing.includes(getTableConfig(t).name));
193
+ if (missing.length > 0) {
194
+ const { generateDrizzleJson, generateMigration } = require("drizzle-kit/api");
195
+ const missingSchema = {};
196
+ for (const t of missing) missingSchema[getTableConfig(t).name] = t;
197
+ const sqls = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(missingSchema));
198
+ for (const sql of sqls) {
199
+ for (let attempt = 0; attempt < 2; attempt++) {
200
+ try {
201
+ await post("db/query", { sql, params: [] });
202
+ console.log(`DB: Executed: ${sql.slice(0, 80)}...`);
203
+ break;
204
+ } catch (err) {
205
+ if (attempt === 0) {
206
+ console.warn(`DB: Retrying after: ${err.message}`);
207
+ await new Promise((r) => setTimeout(r, 1500));
208
+ } else {
209
+ console.error(`DB: Failed: ${sql.slice(0, 80)}... \u2014 ${err.message}`);
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+ const existingTables = tables.filter((t) => existing.includes(getTableConfig(t).name));
216
+ for (const t of existingTables) {
217
+ const cfg = getTableConfig(t);
218
+ try {
219
+ const live = await get("db/table-schema", { table: cfg.name });
220
+ const liveCols = new Set((live.columns || []).map((c) => c.name));
221
+ for (const col of cfg.columns) {
222
+ if (!liveCols.has(col.name)) {
223
+ const colType = col.getSQLType();
224
+ const ddl = `ALTER TABLE "${cfg.name}" ADD COLUMN IF NOT EXISTS "${col.name}" ${colType}`;
225
+ try {
226
+ await post("db/query", { sql: ddl, params: [] });
227
+ console.log(`DB: Added column ${col.name} to ${cfg.name}`);
228
+ } catch (err) {
229
+ console.warn(`DB: Failed to add column ${col.name} to ${cfg.name}: ${err.message}`);
230
+ }
231
+ }
232
+ }
233
+ } catch (err) {
234
+ console.warn(`DB: Column check failed for ${cfg.name}: ${err.message}`);
235
+ }
236
+ }
237
+ } finally {
238
+ syncing = false;
239
+ }
240
+ }
241
+ function watchSchema(schemaPath, options) {
242
+ const { debounceMs = 1e3, retries = 2, retryDelay = 1500 } = options || {};
243
+ if (!import_fs.default.existsSync(schemaPath)) return () => {
244
+ };
245
+ let debounce = null;
246
+ import_fs.default.watchFile(schemaPath, { interval: 2e3 }, () => {
247
+ if (debounce) clearTimeout(debounce);
248
+ debounce = setTimeout(async () => {
249
+ console.log("DB: schema file changed, re-syncing tables...");
250
+ try {
251
+ await syncSchema({ schemaPath, retries, retryDelay });
252
+ console.log("DB: schema re-sync complete");
253
+ } catch (err) {
254
+ console.error(`DB: schema re-sync failed: ${err.message}`);
255
+ }
256
+ }, debounceMs);
257
+ });
258
+ return () => {
259
+ import_fs.default.unwatchFile(schemaPath);
260
+ if (debounce) clearTimeout(debounce);
261
+ };
262
+ }
263
+
89
264
  // src/db/index.ts
90
265
  async function dbProvision() {
91
- return post("db/provision");
266
+ return post("db/provision", {});
92
267
  }
93
268
  async function dbQuery(sql, params, options) {
94
269
  return post("db/query", { sql, params, arrayMode: options?.arrayMode ?? false });
@@ -108,5 +283,7 @@ async function dbStatus() {
108
283
  dbQuery,
109
284
  dbStatus,
110
285
  dbTableSchema,
111
- dbTables
286
+ dbTables,
287
+ syncSchema,
288
+ watchSchema
112
289
  });
@@ -1,3 +1,36 @@
1
+ /**
2
+ * Shared schema sync logic — used by both Express runtime (createServer)
3
+ * and Next.js template (instrumentation.ts).
4
+ *
5
+ * Reads a Drizzle schema file, provisions the database, creates missing
6
+ * tables, and adds missing columns to existing tables.
7
+ */
8
+ interface SchemaSyncOptions {
9
+ /** Path to the schema file (e.g., 'db/schema.js' or 'db/schema.ts') */
10
+ schemaPath: string;
11
+ /** Number of retries on failure (default: 3) */
12
+ retries?: number;
13
+ /** Base delay between retries in ms (default: 2000) */
14
+ retryDelay?: number;
15
+ }
16
+ /**
17
+ * Sync a Drizzle schema file to the database.
18
+ *
19
+ * - Provisions the database via the Surf proxy
20
+ * - Creates missing tables using drizzle-kit DDL generation
21
+ * - Adds missing columns to existing tables via ALTER TABLE
22
+ */
23
+ declare function syncSchema(options: SchemaSyncOptions): Promise<void>;
24
+ /**
25
+ * Watch a schema file for changes and re-sync on edit.
26
+ * Returns a cleanup function to stop watching.
27
+ */
28
+ declare function watchSchema(schemaPath: string, options?: {
29
+ debounceMs?: number;
30
+ retries?: number;
31
+ retryDelay?: number;
32
+ }): () => void;
33
+
1
34
  /**
2
35
  * @surf-ai/sdk/db — Drizzle ORM + Neon PostgreSQL database helpers.
3
36
  *
@@ -12,8 +45,9 @@
12
45
  * // Raw SQL:
13
46
  * const result = await dbQuery('SELECT * FROM users WHERE id = $1', [userId])
14
47
  */
48
+
15
49
  /**
16
- * Provision a database for the current user via /proxy/db/provision.
50
+ * Provision a database for the current user via db/provision.
17
51
  * Returns connection metadata. Neon auto-creates the DB if it doesn't exist.
18
52
  */
19
53
  declare function dbProvision(): Promise<{
@@ -23,7 +57,7 @@ declare function dbProvision(): Promise<{
23
57
  password: string;
24
58
  }>;
25
59
  /**
26
- * Execute a SQL query via /proxy/db/query.
60
+ * Execute a SQL query via db/query.
27
61
  * Uses pg-proxy driver under the hood — Drizzle ORM calls this automatically.
28
62
  *
29
63
  * @param options.arrayMode - When true, rows are returned as positional arrays
@@ -48,4 +82,4 @@ declare function dbStatus(): Promise<{
48
82
  database?: string;
49
83
  }>;
50
84
 
51
- export { dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables };
85
+ export { type SchemaSyncOptions, dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables, syncSchema, watchSchema };
@@ -1,3 +1,36 @@
1
+ /**
2
+ * Shared schema sync logic — used by both Express runtime (createServer)
3
+ * and Next.js template (instrumentation.ts).
4
+ *
5
+ * Reads a Drizzle schema file, provisions the database, creates missing
6
+ * tables, and adds missing columns to existing tables.
7
+ */
8
+ interface SchemaSyncOptions {
9
+ /** Path to the schema file (e.g., 'db/schema.js' or 'db/schema.ts') */
10
+ schemaPath: string;
11
+ /** Number of retries on failure (default: 3) */
12
+ retries?: number;
13
+ /** Base delay between retries in ms (default: 2000) */
14
+ retryDelay?: number;
15
+ }
16
+ /**
17
+ * Sync a Drizzle schema file to the database.
18
+ *
19
+ * - Provisions the database via the Surf proxy
20
+ * - Creates missing tables using drizzle-kit DDL generation
21
+ * - Adds missing columns to existing tables via ALTER TABLE
22
+ */
23
+ declare function syncSchema(options: SchemaSyncOptions): Promise<void>;
24
+ /**
25
+ * Watch a schema file for changes and re-sync on edit.
26
+ * Returns a cleanup function to stop watching.
27
+ */
28
+ declare function watchSchema(schemaPath: string, options?: {
29
+ debounceMs?: number;
30
+ retries?: number;
31
+ retryDelay?: number;
32
+ }): () => void;
33
+
1
34
  /**
2
35
  * @surf-ai/sdk/db — Drizzle ORM + Neon PostgreSQL database helpers.
3
36
  *
@@ -12,8 +45,9 @@
12
45
  * // Raw SQL:
13
46
  * const result = await dbQuery('SELECT * FROM users WHERE id = $1', [userId])
14
47
  */
48
+
15
49
  /**
16
- * Provision a database for the current user via /proxy/db/provision.
50
+ * Provision a database for the current user via db/provision.
17
51
  * Returns connection metadata. Neon auto-creates the DB if it doesn't exist.
18
52
  */
19
53
  declare function dbProvision(): Promise<{
@@ -23,7 +57,7 @@ declare function dbProvision(): Promise<{
23
57
  password: string;
24
58
  }>;
25
59
  /**
26
- * Execute a SQL query via /proxy/db/query.
60
+ * Execute a SQL query via db/query.
27
61
  * Uses pg-proxy driver under the hood — Drizzle ORM calls this automatically.
28
62
  *
29
63
  * @param options.arrayMode - When true, rows are returned as positional arrays
@@ -48,4 +82,4 @@ declare function dbStatus(): Promise<{
48
82
  database?: string;
49
83
  }>;
50
84
 
51
- export { dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables };
85
+ export { type SchemaSyncOptions, dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables, syncSchema, watchSchema };