@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.js CHANGED
@@ -1,25 +1,53 @@
1
- // src/data/client.ts
2
- var DEFAULT_PUBLIC_URL = "https://api.ask.surf/gateway/v1";
3
- function env(surfName, legacyName) {
4
- return process.env[surfName] || process.env[legacyName];
5
- }
6
- function resolveConfig() {
7
- const proxyBase = env("SURF_SANDBOX_PROXY_BASE", "DATA_PROXY_BASE");
8
- if (proxyBase) {
9
- return { baseUrl: proxyBase, headers: {} };
10
- }
11
- const gatewayUrl = env("SURF_DEPLOYED_GATEWAY_URL", "GATEWAY_URL");
12
- const appToken = env("SURF_DEPLOYED_APP_TOKEN", "APP_TOKEN");
13
- if (gatewayUrl && appToken) {
14
- return {
15
- baseUrl: `${gatewayUrl.replace(/\/$/, "")}/gateway/v1`,
16
- headers: { Authorization: `Bearer ${appToken}` }
17
- };
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/core/config.ts
9
+ var DEFAULT_API_BASE_URL = "https://api.ask.surf/gateway/v1";
10
+ function trimTrailingSlashes(value) {
11
+ return String(value || "").replace(/\/+$/, "");
12
+ }
13
+ function readSurfApiConfig() {
14
+ return {
15
+ baseUrl: trimTrailingSlashes(process.env.SURF_API_BASE_URL || DEFAULT_API_BASE_URL),
16
+ apiKey: process.env.SURF_API_KEY
17
+ };
18
+ }
19
+ function requireSurfApiConfig() {
20
+ const config = readSurfApiConfig();
21
+ if (!config.apiKey) {
22
+ throw new Error("SURF_API_KEY is required");
18
23
  }
19
- return { baseUrl: DEFAULT_PUBLIC_URL, headers: {} };
24
+ return { baseUrl: config.baseUrl, apiKey: config.apiKey };
25
+ }
26
+
27
+ // src/core/transport.ts
28
+ function sleep(ms) {
29
+ return new Promise((resolve) => setTimeout(resolve, ms));
20
30
  }
21
31
  function normalizePath(path) {
22
- return String(path || "").replace(/^\/+/, "").replace(/^(?:proxy\/)+/, "");
32
+ return String(path || "").replace(/^\/+/, "");
33
+ }
34
+ function buildUrl(path, params) {
35
+ const { baseUrl } = requireSurfApiConfig();
36
+ const url = new URL(`${baseUrl}/${normalizePath(path)}`);
37
+ if (params) {
38
+ for (const [key, value] of Object.entries(params)) {
39
+ if (value != null) {
40
+ url.searchParams.set(key, String(value));
41
+ }
42
+ }
43
+ }
44
+ return url.toString();
45
+ }
46
+ function buildHeaders(extra) {
47
+ const { apiKey } = requireSurfApiConfig();
48
+ const headers = new Headers(extra);
49
+ headers.set("Authorization", `Bearer ${apiKey}`);
50
+ return headers;
23
51
  }
24
52
  async function fetchJson(url, init, retries = 1) {
25
53
  for (let attempt = 0; attempt <= retries; attempt++) {
@@ -29,36 +57,178 @@ async function fetchJson(url, init, retries = 1) {
29
57
  throw new Error(`API error ${res.status}: ${text2.slice(0, 200)}`);
30
58
  }
31
59
  const text = await res.text();
32
- if (text) return JSON.parse(text);
33
- if (attempt < retries) await new Promise((r) => setTimeout(r, 1e3));
60
+ if (text) {
61
+ return JSON.parse(text);
62
+ }
63
+ if (attempt < retries) {
64
+ await sleep(1e3);
65
+ }
34
66
  }
35
67
  throw new Error(`Empty response from ${url}`);
36
68
  }
37
- async function get(path, params) {
38
- const config = resolveConfig();
39
- const cleaned = {};
40
- if (params) {
41
- for (const [k, v] of Object.entries(params)) {
42
- if (v != null) cleaned[k] = String(v);
43
- }
44
- }
45
- const qs = Object.keys(cleaned).length ? "?" + new URLSearchParams(cleaned).toString() : "";
46
- return fetchJson(`${config.baseUrl}/${normalizePath(path)}${qs}`, {
47
- headers: config.headers
69
+ async function getJson(path, params) {
70
+ return fetchJson(buildUrl(path, params), {
71
+ headers: buildHeaders()
48
72
  });
49
73
  }
50
- async function post(path, body) {
51
- const config = resolveConfig();
52
- return fetchJson(`${config.baseUrl}/${normalizePath(path)}`, {
74
+ async function postJson(path, body) {
75
+ return fetchJson(buildUrl(path), {
53
76
  method: "POST",
54
- headers: { ...config.headers, "Content-Type": "application/json" },
77
+ headers: buildHeaders({
78
+ "Content-Type": "application/json"
79
+ }),
55
80
  body: body ? JSON.stringify(body) : void 0
56
81
  });
57
82
  }
58
83
 
84
+ // src/data/client.ts
85
+ async function get(path, params) {
86
+ return getJson(path, params);
87
+ }
88
+ async function post(path, body) {
89
+ return postJson(path, body);
90
+ }
91
+
92
+ // src/db/schema-sync.ts
93
+ import fs from "fs";
94
+ var syncing = false;
95
+ async function syncSchema(options) {
96
+ const { schemaPath, retries = 3, retryDelay = 2e3 } = options;
97
+ for (let i = 0; i < retries; i++) {
98
+ try {
99
+ await doSyncSchema(schemaPath);
100
+ return;
101
+ } catch (err) {
102
+ console.error(`DB schema sync attempt ${i + 1}/${retries} failed: ${err.message}`);
103
+ if (i < retries - 1) await new Promise((r) => setTimeout(r, retryDelay * (i + 1)));
104
+ }
105
+ }
106
+ console.error("DB schema sync failed after all retries");
107
+ }
108
+ async function doSyncSchema(schemaPath) {
109
+ if (syncing) return;
110
+ syncing = true;
111
+ try {
112
+ if (!fs.existsSync(schemaPath)) return;
113
+ let schema;
114
+ if (schemaPath.endsWith(".ts")) {
115
+ try {
116
+ schema = await import(`${schemaPath}?t=${Date.now()}`);
117
+ } catch (err) {
118
+ if (err instanceof SyntaxError) {
119
+ console.log("DB: schema file has syntax error, waiting for next change...");
120
+ return;
121
+ }
122
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
123
+ return;
124
+ }
125
+ throw err;
126
+ }
127
+ } else {
128
+ try {
129
+ delete __require.cache[__require.resolve(schemaPath)];
130
+ } catch {
131
+ }
132
+ try {
133
+ schema = __require(schemaPath);
134
+ } catch (err) {
135
+ if (err instanceof SyntaxError) {
136
+ console.log("DB: schema file has syntax error, waiting for next change...");
137
+ return;
138
+ }
139
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
140
+ return;
141
+ }
142
+ throw err;
143
+ }
144
+ }
145
+ let getTableConfig;
146
+ try {
147
+ getTableConfig = __require("drizzle-orm/pg-core").getTableConfig;
148
+ } catch {
149
+ return;
150
+ }
151
+ const tables = Object.values(schema).filter(
152
+ (t) => t && typeof t === "object" && /* @__PURE__ */ Symbol.for("drizzle:Name") in t
153
+ );
154
+ if (tables.length === 0) return;
155
+ await post("db/provision", {});
156
+ const existing = (await get("db/tables")).map((t) => t.name);
157
+ const missing = tables.filter((t) => !existing.includes(getTableConfig(t).name));
158
+ if (missing.length > 0) {
159
+ const { generateDrizzleJson, generateMigration } = __require("drizzle-kit/api");
160
+ const missingSchema = {};
161
+ for (const t of missing) missingSchema[getTableConfig(t).name] = t;
162
+ const sqls = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(missingSchema));
163
+ for (const sql of sqls) {
164
+ for (let attempt = 0; attempt < 2; attempt++) {
165
+ try {
166
+ await post("db/query", { sql, params: [] });
167
+ console.log(`DB: Executed: ${sql.slice(0, 80)}...`);
168
+ break;
169
+ } catch (err) {
170
+ if (attempt === 0) {
171
+ console.warn(`DB: Retrying after: ${err.message}`);
172
+ await new Promise((r) => setTimeout(r, 1500));
173
+ } else {
174
+ console.error(`DB: Failed: ${sql.slice(0, 80)}... \u2014 ${err.message}`);
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ const existingTables = tables.filter((t) => existing.includes(getTableConfig(t).name));
181
+ for (const t of existingTables) {
182
+ const cfg = getTableConfig(t);
183
+ try {
184
+ const live = await get("db/table-schema", { table: cfg.name });
185
+ const liveCols = new Set((live.columns || []).map((c) => c.name));
186
+ for (const col of cfg.columns) {
187
+ if (!liveCols.has(col.name)) {
188
+ const colType = col.getSQLType();
189
+ const ddl = `ALTER TABLE "${cfg.name}" ADD COLUMN IF NOT EXISTS "${col.name}" ${colType}`;
190
+ try {
191
+ await post("db/query", { sql: ddl, params: [] });
192
+ console.log(`DB: Added column ${col.name} to ${cfg.name}`);
193
+ } catch (err) {
194
+ console.warn(`DB: Failed to add column ${col.name} to ${cfg.name}: ${err.message}`);
195
+ }
196
+ }
197
+ }
198
+ } catch (err) {
199
+ console.warn(`DB: Column check failed for ${cfg.name}: ${err.message}`);
200
+ }
201
+ }
202
+ } finally {
203
+ syncing = false;
204
+ }
205
+ }
206
+ function watchSchema(schemaPath, options) {
207
+ const { debounceMs = 1e3, retries = 2, retryDelay = 1500 } = options || {};
208
+ if (!fs.existsSync(schemaPath)) return () => {
209
+ };
210
+ let debounce = null;
211
+ fs.watchFile(schemaPath, { interval: 2e3 }, () => {
212
+ if (debounce) clearTimeout(debounce);
213
+ debounce = setTimeout(async () => {
214
+ console.log("DB: schema file changed, re-syncing tables...");
215
+ try {
216
+ await syncSchema({ schemaPath, retries, retryDelay });
217
+ console.log("DB: schema re-sync complete");
218
+ } catch (err) {
219
+ console.error(`DB: schema re-sync failed: ${err.message}`);
220
+ }
221
+ }, debounceMs);
222
+ });
223
+ return () => {
224
+ fs.unwatchFile(schemaPath);
225
+ if (debounce) clearTimeout(debounce);
226
+ };
227
+ }
228
+
59
229
  // src/db/index.ts
60
230
  async function dbProvision() {
61
- return post("db/provision");
231
+ return post("db/provision", {});
62
232
  }
63
233
  async function dbQuery(sql, params, options) {
64
234
  return post("db/query", { sql, params, arrayMode: options?.arrayMode ?? false });
@@ -77,5 +247,7 @@ export {
77
247
  dbQuery,
78
248
  dbStatus,
79
249
  dbTableSchema,
80
- dbTables
250
+ dbTables,
251
+ syncSchema,
252
+ watchSchema
81
253
  };