@surf-ai/sdk 1.0.0-alpha.0 → 1.0.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/db/index.cjs +157 -4
- package/dist/db/index.d.cts +35 -1
- package/dist/db/index.d.ts +35 -1
- package/dist/db/index.js +151 -3
- package/dist/server/index.cjs +173 -186
- package/dist/server/index.js +254 -134
- package/package.json +2 -2
- package/dist/chunk-4NA3GKVD.js +0 -100
- package/dist/client-Z45B2GYT.js +0 -8
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ SDK 1.0 uses a single direct-auth model.
|
|
|
14
14
|
|
|
15
15
|
| Env Var | Default | Purpose |
|
|
16
16
|
| --- | --- | --- |
|
|
17
|
-
| `SURF_API_BASE_URL` | `https://api.
|
|
17
|
+
| `SURF_API_BASE_URL` | `https://api.asksurf.ai/gateway/v1` | Full Surf API base URL |
|
|
18
18
|
| `SURF_API_KEY` | none | Bearer token used for upstream requests and protected runtime endpoints |
|
|
19
19
|
| `PORT` | none | Express server port when `createServer({ port })` is not provided |
|
|
20
20
|
|
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,12 +34,14 @@ __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
43
|
// src/core/config.ts
|
|
32
|
-
var DEFAULT_API_BASE_URL = "https://api.
|
|
44
|
+
var DEFAULT_API_BASE_URL = "https://api.asksurf.ai/gateway/v1";
|
|
33
45
|
function trimTrailingSlashes(value) {
|
|
34
46
|
return String(value || "").replace(/\/+$/, "");
|
|
35
47
|
}
|
|
@@ -112,9 +124,148 @@ async function post(path, body) {
|
|
|
112
124
|
return postJson(path, body);
|
|
113
125
|
}
|
|
114
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 tablesResult = await get("db/tables");
|
|
192
|
+
const tablesList = Array.isArray(tablesResult) ? tablesResult : tablesResult.tables || [];
|
|
193
|
+
const existing = tablesList.map((t) => typeof t === "string" ? t : t.name);
|
|
194
|
+
const missing = tables.filter((t) => !existing.includes(getTableConfig(t).name));
|
|
195
|
+
if (missing.length > 0) {
|
|
196
|
+
const { generateDrizzleJson, generateMigration } = require("drizzle-kit/api");
|
|
197
|
+
const missingSchema = {};
|
|
198
|
+
for (const t of missing) missingSchema[getTableConfig(t).name] = t;
|
|
199
|
+
const sqls = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(missingSchema));
|
|
200
|
+
for (const sql of sqls) {
|
|
201
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
202
|
+
try {
|
|
203
|
+
await post("db/query", { sql, params: [] });
|
|
204
|
+
console.log(`DB: Executed: ${sql.slice(0, 80)}...`);
|
|
205
|
+
break;
|
|
206
|
+
} catch (err) {
|
|
207
|
+
if (attempt === 0) {
|
|
208
|
+
console.warn(`DB: Retrying after: ${err.message}`);
|
|
209
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
210
|
+
} else {
|
|
211
|
+
console.error(`DB: Failed: ${sql.slice(0, 80)}... \u2014 ${err.message}`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const existingTables = tables.filter((t) => existing.includes(getTableConfig(t).name));
|
|
218
|
+
for (const t of existingTables) {
|
|
219
|
+
const cfg = getTableConfig(t);
|
|
220
|
+
try {
|
|
221
|
+
const live = await get("db/table-schema", { table: cfg.name });
|
|
222
|
+
const liveCols = new Set((live.columns || []).map((c) => c.name));
|
|
223
|
+
for (const col of cfg.columns) {
|
|
224
|
+
if (!liveCols.has(col.name)) {
|
|
225
|
+
const colType = col.getSQLType();
|
|
226
|
+
const ddl = `ALTER TABLE "${cfg.name}" ADD COLUMN IF NOT EXISTS "${col.name}" ${colType}`;
|
|
227
|
+
try {
|
|
228
|
+
await post("db/query", { sql: ddl, params: [] });
|
|
229
|
+
console.log(`DB: Added column ${col.name} to ${cfg.name}`);
|
|
230
|
+
} catch (err) {
|
|
231
|
+
console.warn(`DB: Failed to add column ${col.name} to ${cfg.name}: ${err.message}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
} catch (err) {
|
|
236
|
+
console.warn(`DB: Column check failed for ${cfg.name}: ${err.message}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
} finally {
|
|
240
|
+
syncing = false;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function watchSchema(schemaPath, options) {
|
|
244
|
+
const { debounceMs = 1e3, retries = 2, retryDelay = 1500 } = options || {};
|
|
245
|
+
if (!import_fs.default.existsSync(schemaPath)) return () => {
|
|
246
|
+
};
|
|
247
|
+
let debounce = null;
|
|
248
|
+
import_fs.default.watchFile(schemaPath, { interval: 2e3 }, () => {
|
|
249
|
+
if (debounce) clearTimeout(debounce);
|
|
250
|
+
debounce = setTimeout(async () => {
|
|
251
|
+
console.log("DB: schema file changed, re-syncing tables...");
|
|
252
|
+
try {
|
|
253
|
+
await syncSchema({ schemaPath, retries, retryDelay });
|
|
254
|
+
console.log("DB: schema re-sync complete");
|
|
255
|
+
} catch (err) {
|
|
256
|
+
console.error(`DB: schema re-sync failed: ${err.message}`);
|
|
257
|
+
}
|
|
258
|
+
}, debounceMs);
|
|
259
|
+
});
|
|
260
|
+
return () => {
|
|
261
|
+
import_fs.default.unwatchFile(schemaPath);
|
|
262
|
+
if (debounce) clearTimeout(debounce);
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
115
266
|
// src/db/index.ts
|
|
116
267
|
async function dbProvision() {
|
|
117
|
-
return post("db/provision");
|
|
268
|
+
return post("db/provision", {});
|
|
118
269
|
}
|
|
119
270
|
async function dbQuery(sql, params, options) {
|
|
120
271
|
return post("db/query", { sql, params, arrayMode: options?.arrayMode ?? false });
|
|
@@ -134,5 +285,7 @@ async function dbStatus() {
|
|
|
134
285
|
dbQuery,
|
|
135
286
|
dbStatus,
|
|
136
287
|
dbTableSchema,
|
|
137
|
-
dbTables
|
|
288
|
+
dbTables,
|
|
289
|
+
syncSchema,
|
|
290
|
+
watchSchema
|
|
138
291
|
});
|
package/dist/db/index.d.cts
CHANGED
|
@@ -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,6 +45,7 @@
|
|
|
12
45
|
* // Raw SQL:
|
|
13
46
|
* const result = await dbQuery('SELECT * FROM users WHERE id = $1', [userId])
|
|
14
47
|
*/
|
|
48
|
+
|
|
15
49
|
/**
|
|
16
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.
|
|
@@ -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 };
|
package/dist/db/index.d.ts
CHANGED
|
@@ -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,6 +45,7 @@
|
|
|
12
45
|
* // Raw SQL:
|
|
13
46
|
* const result = await dbQuery('SELECT * FROM users WHERE id = $1', [userId])
|
|
14
47
|
*/
|
|
48
|
+
|
|
15
49
|
/**
|
|
16
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.
|
|
@@ -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 };
|
package/dist/db/index.js
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
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
|
+
|
|
1
8
|
// src/core/config.ts
|
|
2
|
-
var DEFAULT_API_BASE_URL = "https://api.
|
|
9
|
+
var DEFAULT_API_BASE_URL = "https://api.asksurf.ai/gateway/v1";
|
|
3
10
|
function trimTrailingSlashes(value) {
|
|
4
11
|
return String(value || "").replace(/\/+$/, "");
|
|
5
12
|
}
|
|
@@ -82,9 +89,148 @@ async function post(path, body) {
|
|
|
82
89
|
return postJson(path, body);
|
|
83
90
|
}
|
|
84
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 tablesResult = await get("db/tables");
|
|
157
|
+
const tablesList = Array.isArray(tablesResult) ? tablesResult : tablesResult.tables || [];
|
|
158
|
+
const existing = tablesList.map((t) => typeof t === "string" ? t : t.name);
|
|
159
|
+
const missing = tables.filter((t) => !existing.includes(getTableConfig(t).name));
|
|
160
|
+
if (missing.length > 0) {
|
|
161
|
+
const { generateDrizzleJson, generateMigration } = __require("drizzle-kit/api");
|
|
162
|
+
const missingSchema = {};
|
|
163
|
+
for (const t of missing) missingSchema[getTableConfig(t).name] = t;
|
|
164
|
+
const sqls = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(missingSchema));
|
|
165
|
+
for (const sql of sqls) {
|
|
166
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
167
|
+
try {
|
|
168
|
+
await post("db/query", { sql, params: [] });
|
|
169
|
+
console.log(`DB: Executed: ${sql.slice(0, 80)}...`);
|
|
170
|
+
break;
|
|
171
|
+
} catch (err) {
|
|
172
|
+
if (attempt === 0) {
|
|
173
|
+
console.warn(`DB: Retrying after: ${err.message}`);
|
|
174
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
175
|
+
} else {
|
|
176
|
+
console.error(`DB: Failed: ${sql.slice(0, 80)}... \u2014 ${err.message}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const existingTables = tables.filter((t) => existing.includes(getTableConfig(t).name));
|
|
183
|
+
for (const t of existingTables) {
|
|
184
|
+
const cfg = getTableConfig(t);
|
|
185
|
+
try {
|
|
186
|
+
const live = await get("db/table-schema", { table: cfg.name });
|
|
187
|
+
const liveCols = new Set((live.columns || []).map((c) => c.name));
|
|
188
|
+
for (const col of cfg.columns) {
|
|
189
|
+
if (!liveCols.has(col.name)) {
|
|
190
|
+
const colType = col.getSQLType();
|
|
191
|
+
const ddl = `ALTER TABLE "${cfg.name}" ADD COLUMN IF NOT EXISTS "${col.name}" ${colType}`;
|
|
192
|
+
try {
|
|
193
|
+
await post("db/query", { sql: ddl, params: [] });
|
|
194
|
+
console.log(`DB: Added column ${col.name} to ${cfg.name}`);
|
|
195
|
+
} catch (err) {
|
|
196
|
+
console.warn(`DB: Failed to add column ${col.name} to ${cfg.name}: ${err.message}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
} catch (err) {
|
|
201
|
+
console.warn(`DB: Column check failed for ${cfg.name}: ${err.message}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
} finally {
|
|
205
|
+
syncing = false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function watchSchema(schemaPath, options) {
|
|
209
|
+
const { debounceMs = 1e3, retries = 2, retryDelay = 1500 } = options || {};
|
|
210
|
+
if (!fs.existsSync(schemaPath)) return () => {
|
|
211
|
+
};
|
|
212
|
+
let debounce = null;
|
|
213
|
+
fs.watchFile(schemaPath, { interval: 2e3 }, () => {
|
|
214
|
+
if (debounce) clearTimeout(debounce);
|
|
215
|
+
debounce = setTimeout(async () => {
|
|
216
|
+
console.log("DB: schema file changed, re-syncing tables...");
|
|
217
|
+
try {
|
|
218
|
+
await syncSchema({ schemaPath, retries, retryDelay });
|
|
219
|
+
console.log("DB: schema re-sync complete");
|
|
220
|
+
} catch (err) {
|
|
221
|
+
console.error(`DB: schema re-sync failed: ${err.message}`);
|
|
222
|
+
}
|
|
223
|
+
}, debounceMs);
|
|
224
|
+
});
|
|
225
|
+
return () => {
|
|
226
|
+
fs.unwatchFile(schemaPath);
|
|
227
|
+
if (debounce) clearTimeout(debounce);
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
85
231
|
// src/db/index.ts
|
|
86
232
|
async function dbProvision() {
|
|
87
|
-
return post("db/provision");
|
|
233
|
+
return post("db/provision", {});
|
|
88
234
|
}
|
|
89
235
|
async function dbQuery(sql, params, options) {
|
|
90
236
|
return post("db/query", { sql, params, arrayMode: options?.arrayMode ?? false });
|
|
@@ -103,5 +249,7 @@ export {
|
|
|
103
249
|
dbQuery,
|
|
104
250
|
dbStatus,
|
|
105
251
|
dbTableSchema,
|
|
106
|
-
dbTables
|
|
252
|
+
dbTables,
|
|
253
|
+
syncSchema,
|
|
254
|
+
watchSchema
|
|
107
255
|
};
|