tthr 0.3.5 → 0.3.7

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.
@@ -0,0 +1,684 @@
1
+ // src/commands/generate.ts
2
+ import chalk2 from "chalk";
3
+ import ora from "ora";
4
+ import fs3 from "fs-extra";
5
+ import path3 from "path";
6
+
7
+ // src/utils/auth.ts
8
+ import chalk from "chalk";
9
+ import fs from "fs-extra";
10
+ import path from "path";
11
+ var CONFIG_DIR = path.join(process.env.HOME || process.env.USERPROFILE || "", ".tether");
12
+ var CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
13
+ var isDev = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
14
+ var API_URL = isDev ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
15
+ var REFRESH_THRESHOLD_DAYS = 7;
16
+ async function getCredentials() {
17
+ try {
18
+ if (await fs.pathExists(CREDENTIALS_FILE)) {
19
+ return await fs.readJSON(CREDENTIALS_FILE);
20
+ }
21
+ } catch {
22
+ }
23
+ return null;
24
+ }
25
+ async function refreshSession(credentials) {
26
+ try {
27
+ const response = await fetch(`${API_URL}/auth/session/refresh`, {
28
+ method: "POST",
29
+ headers: {
30
+ "Content-Type": "application/json",
31
+ "Authorization": `Bearer ${credentials.accessToken}`
32
+ }
33
+ });
34
+ if (!response.ok) {
35
+ return null;
36
+ }
37
+ const data = await response.json();
38
+ const updated = {
39
+ ...credentials,
40
+ expiresAt: data.expiresAt
41
+ };
42
+ await saveCredentials(updated);
43
+ return updated;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ async function requireAuth() {
49
+ const credentials = await getCredentials();
50
+ if (!credentials) {
51
+ console.error(chalk.red("\n\u2717 Not logged in\n"));
52
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
53
+ process.exit(1);
54
+ }
55
+ if (credentials.expiresAt) {
56
+ const expiresAt = new Date(credentials.expiresAt);
57
+ const now = /* @__PURE__ */ new Date();
58
+ if (now > expiresAt) {
59
+ await clearCredentials();
60
+ console.error(chalk.red("\n\u2717 Session expired \u2014 you have been signed out\n"));
61
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
62
+ process.exit(1);
63
+ }
64
+ const daysUntilExpiry = (expiresAt.getTime() - now.getTime()) / (1e3 * 60 * 60 * 24);
65
+ if (daysUntilExpiry <= REFRESH_THRESHOLD_DAYS) {
66
+ const refreshed = await refreshSession(credentials);
67
+ if (refreshed) {
68
+ return refreshed;
69
+ }
70
+ }
71
+ }
72
+ return credentials;
73
+ }
74
+ async function saveCredentials(credentials) {
75
+ await fs.ensureDir(CONFIG_DIR);
76
+ await fs.writeJSON(CREDENTIALS_FILE, credentials, { spaces: 2, mode: 384 });
77
+ }
78
+ async function clearCredentials() {
79
+ try {
80
+ await fs.remove(CREDENTIALS_FILE);
81
+ } catch {
82
+ }
83
+ }
84
+
85
+ // src/utils/config.ts
86
+ import fs2 from "fs-extra";
87
+ import path2 from "path";
88
+ var DEFAULT_CONFIG = {
89
+ schema: "./tether/schema.ts",
90
+ functions: "./tether/functions",
91
+ output: "./tether/_generated",
92
+ dev: {
93
+ port: 3001,
94
+ host: "localhost"
95
+ },
96
+ database: {
97
+ walMode: true
98
+ }
99
+ };
100
+ async function loadConfig(cwd = process.cwd()) {
101
+ const configPath = path2.resolve(cwd, "tether.config.ts");
102
+ if (!await fs2.pathExists(configPath)) {
103
+ return DEFAULT_CONFIG;
104
+ }
105
+ const configSource = await fs2.readFile(configPath, "utf-8");
106
+ const config = {};
107
+ const schemaMatch = configSource.match(/schema\s*:\s*['"]([^'"]+)['"]/);
108
+ if (schemaMatch) {
109
+ config.schema = schemaMatch[1];
110
+ }
111
+ const functionsMatch = configSource.match(/functions\s*:\s*['"]([^'"]+)['"]/);
112
+ if (functionsMatch) {
113
+ config.functions = functionsMatch[1];
114
+ }
115
+ const outputMatch = configSource.match(/output\s*:\s*['"]([^'"]+)['"]/);
116
+ if (outputMatch) {
117
+ config.output = outputMatch[1];
118
+ }
119
+ const envMatch = configSource.match(/environment\s*:\s*['"]([^'"]+)['"]/);
120
+ if (envMatch) {
121
+ config.environment = envMatch[1];
122
+ }
123
+ const portMatch = configSource.match(/port\s*:\s*(\d+)/);
124
+ if (portMatch) {
125
+ config.dev = { ...config.dev, port: parseInt(portMatch[1], 10) };
126
+ }
127
+ const hostMatch = configSource.match(/host\s*:\s*['"]([^'"]+)['"]/);
128
+ if (hostMatch) {
129
+ config.dev = { ...config.dev, host: hostMatch[1] };
130
+ }
131
+ return {
132
+ ...DEFAULT_CONFIG,
133
+ ...config,
134
+ dev: { ...DEFAULT_CONFIG.dev, ...config.dev },
135
+ database: { ...DEFAULT_CONFIG.database, ...config.database }
136
+ };
137
+ }
138
+ function resolvePath(configPath, cwd = process.cwd()) {
139
+ const normalised = configPath.replace(/^\.\//, "");
140
+ return path2.resolve(cwd, normalised);
141
+ }
142
+ async function detectFramework(cwd = process.cwd()) {
143
+ const packageJsonPath = path2.resolve(cwd, "package.json");
144
+ if (!await fs2.pathExists(packageJsonPath)) {
145
+ return "unknown";
146
+ }
147
+ try {
148
+ const packageJson = await fs2.readJson(packageJsonPath);
149
+ const deps = {
150
+ ...packageJson.dependencies,
151
+ ...packageJson.devDependencies
152
+ };
153
+ if (deps.nuxt || deps["@nuxt/kit"]) {
154
+ return "nuxt";
155
+ }
156
+ if (deps.next) {
157
+ return "next";
158
+ }
159
+ if (deps["@sveltejs/kit"]) {
160
+ return "sveltekit";
161
+ }
162
+ if (deps.vite && !deps.nuxt && !deps.next && !deps["@sveltejs/kit"]) {
163
+ return "vite";
164
+ }
165
+ return "vanilla";
166
+ } catch {
167
+ return "unknown";
168
+ }
169
+ }
170
+ function getFrameworkDevCommand(framework) {
171
+ switch (framework) {
172
+ case "nuxt":
173
+ return "nuxt dev";
174
+ case "next":
175
+ return "next dev";
176
+ case "sveltekit":
177
+ return "vite dev";
178
+ case "vite":
179
+ return "vite dev";
180
+ case "vanilla":
181
+ return null;
182
+ // No default dev server for vanilla
183
+ default:
184
+ return null;
185
+ }
186
+ }
187
+
188
+ // src/commands/generate.ts
189
+ var isDev2 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
190
+ var API_URL2 = isDev2 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
191
+ function parseSchemaFile(source) {
192
+ const tables = [];
193
+ const schemaMatch = source.match(/defineSchema\s*\(\s*\{([\s\S]*)\}\s*\)/);
194
+ if (!schemaMatch) return tables;
195
+ const schemaContent = schemaMatch[1];
196
+ const tableStartRegex = /(\w+)\s*:\s*\{/g;
197
+ let match;
198
+ while ((match = tableStartRegex.exec(schemaContent)) !== null) {
199
+ const tableName = match[1];
200
+ const startOffset = match.index + match[0].length;
201
+ let braceCount = 1;
202
+ let endOffset = startOffset;
203
+ for (let i = startOffset; i < schemaContent.length && braceCount > 0; i++) {
204
+ const char = schemaContent[i];
205
+ if (char === "{") braceCount++;
206
+ else if (char === "}") braceCount--;
207
+ endOffset = i;
208
+ }
209
+ const columnsContent = schemaContent.slice(startOffset, endOffset);
210
+ const columns = parseColumns(columnsContent);
211
+ tables.push({ name: tableName, columns });
212
+ }
213
+ return tables;
214
+ }
215
+ function parseColumns(content) {
216
+ const columns = [];
217
+ const columnRegex = /(\w+)\s*:\s*(\w+)(?:<([^>]+)>)?\s*\(\s*\)((?:\[.*?\]|[^,\n}])*)/g;
218
+ let match;
219
+ while ((match = columnRegex.exec(content)) !== null) {
220
+ const name = match[1];
221
+ const schemaType = match[2];
222
+ const genericType = match[3];
223
+ const modifiers = match[4] || "";
224
+ const nullable = !modifiers.includes(".notNull()");
225
+ const oneOfMatch = modifiers.match(/\.oneOf\s*\(\s*\[(.*?)\]\s*\)/);
226
+ let oneOf;
227
+ if (oneOfMatch) {
228
+ oneOf = [...oneOfMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
229
+ }
230
+ columns.push({
231
+ name,
232
+ type: schemaTypeToTS(schemaType),
233
+ nullable,
234
+ jsonType: genericType,
235
+ // Store the generic type for json columns
236
+ oneOf
237
+ });
238
+ }
239
+ return columns;
240
+ }
241
+ function schemaTypeToTS(schemaType) {
242
+ switch (schemaType) {
243
+ case "text":
244
+ return "string";
245
+ case "integer":
246
+ return "number";
247
+ case "real":
248
+ return "number";
249
+ case "boolean":
250
+ return "boolean";
251
+ case "timestamp":
252
+ return "string";
253
+ case "json":
254
+ return "unknown";
255
+ case "blob":
256
+ return "Uint8Array";
257
+ case "asset":
258
+ return "TetherAsset";
259
+ // Asset object returned by API
260
+ default:
261
+ return "unknown";
262
+ }
263
+ }
264
+ function extractSingleType(source, typeName) {
265
+ const interfaceStart = new RegExp(`(?:export\\s+)?interface\\s+${typeName}\\s*\\{`);
266
+ const interfaceMatch = interfaceStart.exec(source);
267
+ if (interfaceMatch) {
268
+ const braceStart = interfaceMatch.index + interfaceMatch[0].length;
269
+ let braceCount = 1;
270
+ let endIdx = braceStart;
271
+ for (let i = braceStart; i < source.length && braceCount > 0; i++) {
272
+ if (source[i] === "{") braceCount++;
273
+ else if (source[i] === "}") braceCount--;
274
+ endIdx = i;
275
+ }
276
+ return source.slice(interfaceMatch.index, endIdx + 1).replace(/^export\s+/, "");
277
+ }
278
+ const typeStart = new RegExp(`(?:export\\s+)?type\\s+${typeName}\\s*=`);
279
+ const typeMatch = typeStart.exec(source);
280
+ if (typeMatch) {
281
+ const semiIdx = source.indexOf(";", typeMatch.index);
282
+ if (semiIdx !== -1) {
283
+ return source.slice(typeMatch.index, semiIdx + 1).replace(/^export\s+/, "");
284
+ }
285
+ }
286
+ return null;
287
+ }
288
+ function extractTypeDefinitions(source, typeNames) {
289
+ if (typeNames.size === 0) return [];
290
+ const allDefinedTypes = /* @__PURE__ */ new Set();
291
+ const typeDefRegex = /(?:export\s+)?(?:interface|type)\s+(\w+)/g;
292
+ let m;
293
+ while ((m = typeDefRegex.exec(source)) !== null) {
294
+ allDefinedTypes.add(m[1]);
295
+ }
296
+ const resolved = /* @__PURE__ */ new Map();
297
+ const queue = [...typeNames];
298
+ while (queue.length > 0) {
299
+ const name = queue.shift();
300
+ if (resolved.has(name)) continue;
301
+ const block = extractSingleType(source, name);
302
+ if (!block) continue;
303
+ resolved.set(name, block);
304
+ for (const definedType of allDefinedTypes) {
305
+ if (!resolved.has(definedType) && !queue.includes(definedType)) {
306
+ const refRegex = new RegExp(`\\b${definedType}\\b`);
307
+ if (refRegex.test(block)) {
308
+ queue.push(definedType);
309
+ }
310
+ }
311
+ }
312
+ }
313
+ const ordered = [];
314
+ const visited = /* @__PURE__ */ new Set();
315
+ function visit(name) {
316
+ if (visited.has(name)) return;
317
+ visited.add(name);
318
+ const block = resolved.get(name);
319
+ if (!block) return;
320
+ for (const dep of resolved.keys()) {
321
+ if (dep !== name && new RegExp(`\\b${dep}\\b`).test(block)) {
322
+ visit(dep);
323
+ }
324
+ }
325
+ ordered.push(name);
326
+ }
327
+ for (const name of resolved.keys()) {
328
+ visit(name);
329
+ }
330
+ return ordered.map((name) => resolved.get(name));
331
+ }
332
+ function tableNameToInterface(tableName) {
333
+ let name = tableName;
334
+ if (name.endsWith("ies")) {
335
+ name = name.slice(0, -3) + "y";
336
+ } else if (name.endsWith("s") && !name.endsWith("ss")) {
337
+ name = name.slice(0, -1);
338
+ }
339
+ return name.charAt(0).toUpperCase() + name.slice(1);
340
+ }
341
+ function generateDbFile(tables, schemaSource) {
342
+ const TS_PRIMITIVES = /* @__PURE__ */ new Set(["number", "string", "boolean", "unknown", "any", "void", "never", "undefined", "null", "object"]);
343
+ const jsonTypes = /* @__PURE__ */ new Set();
344
+ for (const table of tables) {
345
+ for (const col of table.columns) {
346
+ if (col.jsonType) {
347
+ const baseType = col.jsonType.replace(/\s*\|\s*null/g, "").replace(/\[\]/g, "").trim();
348
+ if (!TS_PRIMITIVES.has(baseType)) {
349
+ jsonTypes.add(baseType);
350
+ }
351
+ }
352
+ }
353
+ }
354
+ const lines = [
355
+ "// Auto-generated by Tether CLI - do not edit manually",
356
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
357
+ "",
358
+ "import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
359
+ "import {",
360
+ " type QueryDefinition,",
361
+ " type MutationDefinition,",
362
+ " z,",
363
+ "} from '@tthr/server';",
364
+ "import type { TetherEnv } from './env';"
365
+ ];
366
+ if (jsonTypes.size > 0) {
367
+ const typeBlocks = extractTypeDefinitions(schemaSource, jsonTypes);
368
+ if (typeBlocks.length > 0) {
369
+ lines.push("");
370
+ lines.push("// Schema types (inlined from schema.ts)");
371
+ for (const block of typeBlocks) {
372
+ lines.push(block);
373
+ lines.push("");
374
+ }
375
+ }
376
+ }
377
+ lines.push("");
378
+ lines.push("// Asset type returned by the API for asset columns");
379
+ lines.push("export interface TetherAsset {");
380
+ lines.push(" id: string;");
381
+ lines.push(" filename: string;");
382
+ lines.push(" contentType: string;");
383
+ lines.push(" size: number;");
384
+ lines.push(" url: string;");
385
+ lines.push(" createdAt: string;");
386
+ lines.push("}");
387
+ lines.push("");
388
+ for (const table of tables) {
389
+ const interfaceName = tableNameToInterface(table.name);
390
+ lines.push(`export interface ${interfaceName} {`);
391
+ lines.push(" _id: string;");
392
+ for (const col of table.columns) {
393
+ let colType;
394
+ if (col.oneOf && col.oneOf.length > 0) {
395
+ colType = col.oneOf.map((v) => `'${v}'`).join(" | ");
396
+ } else {
397
+ colType = col.jsonType || col.type;
398
+ }
399
+ const typeStr = col.nullable ? `${colType} | null` : colType;
400
+ const optional = col.nullable ? "?" : "";
401
+ lines.push(` ${col.name}${optional}: ${typeStr};`);
402
+ }
403
+ lines.push(" _createdAt: string;");
404
+ lines.push(" _updatedAt?: string | null;");
405
+ lines.push(" _deletedAt?: string | null;");
406
+ lines.push("}");
407
+ lines.push("");
408
+ }
409
+ lines.push("export interface Schema {");
410
+ for (const table of tables) {
411
+ const interfaceName = tableNameToInterface(table.name);
412
+ lines.push(` ${table.name}: ${interfaceName};`);
413
+ }
414
+ lines.push("}");
415
+ lines.push("");
416
+ lines.push("// Database client with typed tables");
417
+ lines.push("// This is a proxy that will be populated by the Tether runtime");
418
+ lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
419
+ lines.push("");
420
+ lines.push("// ============================================================================");
421
+ lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
422
+ lines.push("// This ensures the `db` and `env` parameters in handlers are properly typed");
423
+ lines.push("// ============================================================================");
424
+ lines.push("");
425
+ lines.push("/**");
426
+ lines.push(" * Define a query function with typed database and environment variable access.");
427
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
428
+ lines.push(" */");
429
+ lines.push("export function query<TArgs = void, TResult = unknown>(");
430
+ lines.push(" definition: QueryDefinition<TArgs, TResult, Schema, TetherEnv>");
431
+ lines.push("): QueryDefinition<TArgs, TResult, Schema, TetherEnv> {");
432
+ lines.push(" return definition;");
433
+ lines.push("}");
434
+ lines.push("");
435
+ lines.push("/**");
436
+ lines.push(" * Define a mutation function with typed database and environment variable access.");
437
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
438
+ lines.push(" */");
439
+ lines.push("export function mutation<TArgs = void, TResult = unknown>(");
440
+ lines.push(" definition: MutationDefinition<TArgs, TResult, Schema, TetherEnv>");
441
+ lines.push("): MutationDefinition<TArgs, TResult, Schema, TetherEnv> {");
442
+ lines.push(" return definition;");
443
+ lines.push("}");
444
+ lines.push("");
445
+ lines.push("// Re-export z for convenience");
446
+ lines.push("export { z };");
447
+ lines.push("");
448
+ return lines.join("\n");
449
+ }
450
+ async function parseFunctionsDir(functionsDir) {
451
+ const functions = [];
452
+ if (!await fs3.pathExists(functionsDir)) {
453
+ return functions;
454
+ }
455
+ const files = await fs3.readdir(functionsDir);
456
+ for (const file of files) {
457
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
458
+ const filePath = path3.join(functionsDir, file);
459
+ const stat = await fs3.stat(filePath);
460
+ if (!stat.isFile()) continue;
461
+ const moduleName = file.replace(/\.(ts|js)$/, "");
462
+ const source = await fs3.readFile(filePath, "utf-8");
463
+ const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation)\s*\(/g;
464
+ let match;
465
+ while ((match = exportRegex.exec(source)) !== null) {
466
+ functions.push({
467
+ name: match[1],
468
+ moduleName
469
+ });
470
+ }
471
+ }
472
+ return functions;
473
+ }
474
+ async function generateApiFile(functionsDir) {
475
+ const functions = await parseFunctionsDir(functionsDir);
476
+ const moduleMap = /* @__PURE__ */ new Map();
477
+ for (const fn of functions) {
478
+ if (!moduleMap.has(fn.moduleName)) {
479
+ moduleMap.set(fn.moduleName, []);
480
+ }
481
+ moduleMap.get(fn.moduleName).push(fn.name);
482
+ }
483
+ const lines = [
484
+ "// Auto-generated by Tether CLI - do not edit manually",
485
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
486
+ "",
487
+ "import { createApiProxy } from '@tthr/client';",
488
+ "",
489
+ "/**",
490
+ " * API function reference type for useQuery/useMutation.",
491
+ ' * The _name property contains the function path (e.g., "users.list").',
492
+ " */",
493
+ "export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
494
+ " _name: string;",
495
+ " _args?: TArgs;",
496
+ " _result?: TResult;",
497
+ "}",
498
+ ""
499
+ ];
500
+ if (moduleMap.size > 0) {
501
+ for (const [moduleName, fnNames] of moduleMap) {
502
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
503
+ lines.push(`export interface ${interfaceName} {`);
504
+ for (const fnName of fnNames) {
505
+ lines.push(` ${fnName}: ApiFunction;`);
506
+ }
507
+ lines.push("}");
508
+ lines.push("");
509
+ }
510
+ lines.push("export interface Api {");
511
+ for (const moduleName of moduleMap.keys()) {
512
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
513
+ lines.push(` ${moduleName}: ${interfaceName};`);
514
+ }
515
+ lines.push("}");
516
+ } else {
517
+ lines.push("/**");
518
+ lines.push(" * Flexible API type that allows access to any function path.");
519
+ lines.push(" * Functions are accessed as api.moduleName.functionName");
520
+ lines.push(" * The actual types depend on your function definitions.");
521
+ lines.push(" */");
522
+ lines.push("export type Api = {");
523
+ lines.push(" [module: string]: {");
524
+ lines.push(" [fn: string]: ApiFunction;");
525
+ lines.push(" };");
526
+ lines.push("};");
527
+ }
528
+ lines.push("");
529
+ lines.push("// API client proxy - provides typed access to your functions");
530
+ lines.push("// On the client: returns { _name } references for useQuery/useMutation");
531
+ lines.push("// In Tether functions: calls the actual function implementation");
532
+ lines.push("export const api = createApiProxy<Api>();");
533
+ lines.push("");
534
+ return lines.join("\n");
535
+ }
536
+ async function fetchEnvVarKeys(projectId, environment) {
537
+ const credentials = await getCredentials();
538
+ if (!credentials) return [];
539
+ const envPath = environment !== "production" ? `/projects/${projectId}/env/${environment}/env-vars` : `/projects/${projectId}/env-vars`;
540
+ try {
541
+ const response = await fetch(`${API_URL2}${envPath}`, {
542
+ headers: {
543
+ "Authorization": `Bearer ${credentials.accessToken}`
544
+ }
545
+ });
546
+ if (!response.ok) return [];
547
+ const data = await response.json();
548
+ return (data.envVars || []).map((v) => v.key).sort();
549
+ } catch {
550
+ return [];
551
+ }
552
+ }
553
+ function generateEnvFile(keys) {
554
+ const lines = [
555
+ "// Auto-generated by Tether CLI - do not edit manually",
556
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
557
+ "",
558
+ "/**",
559
+ " * Typed environment variables for this project.",
560
+ " * Keys are fetched from the Tether API \u2014 values are never exposed.",
561
+ ' * Use `env.get("KEY")` in your functions to access them.',
562
+ " */",
563
+ ""
564
+ ];
565
+ if (keys.length > 0) {
566
+ lines.push("export type EnvVarKey =");
567
+ for (let i = 0; i < keys.length; i++) {
568
+ const sep = i === keys.length - 1 ? ";" : "";
569
+ lines.push(` | '${keys[i]}'${sep}`);
570
+ }
571
+ lines.push("");
572
+ lines.push("export interface TetherEnv {");
573
+ for (const key of keys) {
574
+ lines.push(` ${key}: string;`);
575
+ }
576
+ lines.push("}");
577
+ } else {
578
+ lines.push("export type EnvVarKey = string;");
579
+ lines.push("");
580
+ lines.push("export interface TetherEnv {");
581
+ lines.push(" [key: string]: string;");
582
+ lines.push("}");
583
+ }
584
+ lines.push("");
585
+ return lines.join("\n");
586
+ }
587
+ async function generateTypes(options = {}) {
588
+ const config = await loadConfig();
589
+ const schemaPath = resolvePath(config.schema);
590
+ const outputDir = resolvePath(config.output);
591
+ const functionsDir = resolvePath(config.functions);
592
+ if (!await fs3.pathExists(schemaPath)) {
593
+ throw new Error(`Schema file not found: ${schemaPath}`);
594
+ }
595
+ const schemaSource = await fs3.readFile(schemaPath, "utf-8");
596
+ const tables = parseSchemaFile(schemaSource);
597
+ const environment = config.environment || "development";
598
+ let projectId;
599
+ const envFilePath = path3.resolve(process.cwd(), ".env");
600
+ if (await fs3.pathExists(envFilePath)) {
601
+ const envContent = await fs3.readFile(envFilePath, "utf-8");
602
+ const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
603
+ projectId = match?.[1]?.trim();
604
+ }
605
+ const envVarKeys = projectId ? await fetchEnvVarKeys(projectId, environment) : [];
606
+ await fs3.ensureDir(outputDir);
607
+ await fs3.writeFile(
608
+ path3.join(outputDir, "db.ts"),
609
+ generateDbFile(tables, schemaSource)
610
+ );
611
+ await fs3.writeFile(
612
+ path3.join(outputDir, "api.ts"),
613
+ await generateApiFile(functionsDir)
614
+ );
615
+ await fs3.writeFile(
616
+ path3.join(outputDir, "env.ts"),
617
+ generateEnvFile(envVarKeys)
618
+ );
619
+ await fs3.writeFile(
620
+ path3.join(outputDir, "index.ts"),
621
+ `// Auto-generated by Tether CLI - do not edit manually
622
+ export * from './db';
623
+ export * from './api';
624
+ export * from './env';
625
+ `
626
+ );
627
+ return { tables, envVarKeys, outputDir };
628
+ }
629
+ async function generateCommand() {
630
+ await requireAuth();
631
+ const configPath = path3.resolve(process.cwd(), "tether.config.ts");
632
+ if (!await fs3.pathExists(configPath)) {
633
+ console.log(chalk2.red("\nError: Not a Tether project"));
634
+ console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
635
+ process.exit(1);
636
+ }
637
+ console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
638
+ const spinner = ora("Reading schema...").start();
639
+ try {
640
+ spinner.text = "Generating types...";
641
+ const { tables, envVarKeys, outputDir } = await generateTypes();
642
+ if (tables.length === 0) {
643
+ spinner.warn("No tables found in schema");
644
+ console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
645
+ return;
646
+ }
647
+ spinner.succeed(`Types generated for ${tables.length} table(s)`);
648
+ console.log("\n" + chalk2.green("\u2713") + " Tables:");
649
+ for (const table of tables) {
650
+ console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
651
+ }
652
+ if (envVarKeys.length > 0) {
653
+ console.log("\n" + chalk2.green("\u2713") + ` Environment variables: ${envVarKeys.length} key(s)`);
654
+ for (const key of envVarKeys) {
655
+ console.log(chalk2.dim(` - ${key}`));
656
+ }
657
+ }
658
+ const relativeOutput = path3.relative(process.cwd(), outputDir);
659
+ console.log("\n" + chalk2.green("\u2713") + " Generated files:");
660
+ console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
661
+ console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
662
+ console.log(chalk2.dim(` ${relativeOutput}/env.ts`));
663
+ console.log(chalk2.dim(` ${relativeOutput}/index.ts
664
+ `));
665
+ } catch (error) {
666
+ spinner.fail("Failed to generate types");
667
+ console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
668
+ process.exit(1);
669
+ }
670
+ }
671
+
672
+ export {
673
+ API_URL,
674
+ getCredentials,
675
+ requireAuth,
676
+ saveCredentials,
677
+ clearCredentials,
678
+ loadConfig,
679
+ resolvePath,
680
+ detectFramework,
681
+ getFrameworkDevCommand,
682
+ generateTypes,
683
+ generateCommand
684
+ };
@@ -0,0 +1,8 @@
1
+ import {
2
+ generateCommand,
3
+ generateTypes
4
+ } from "./chunk-CPBP6GSK.js";
5
+ export {
6
+ generateCommand,
7
+ generateTypes
8
+ };
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  requireAuth,
12
12
  resolvePath,
13
13
  saveCredentials
14
- } from "./chunk-VBD4DOWS.js";
14
+ } from "./chunk-CPBP6GSK.js";
15
15
 
16
16
  // src/index.ts
17
17
  import { Command } from "commander";
@@ -1224,8 +1224,8 @@ PUBLIC_TETHER_PROJECT_ID=\${TETHER_PROJECT_ID}
1224
1224
  }
1225
1225
  }
1226
1226
  }
1227
- function getInstallCommand(pm, isDev6 = false) {
1228
- const devFlag = isDev6 ? pm === "npm" ? "-D" : pm === "yarn" ? "-D" : pm === "pnpm" ? "-D" : "-d" : "";
1227
+ function getInstallCommand(pm, isDev7 = false) {
1228
+ const devFlag = isDev7 ? pm === "npm" ? "-D" : pm === "yarn" ? "-D" : pm === "pnpm" ? "-D" : "-d" : "";
1229
1229
  return `${pm} ${pm === "npm" ? "install" : "add"} ${devFlag}`.trim();
1230
1230
  }
1231
1231
  async function installTetherPackages(projectPath, template, packageManager) {
@@ -1670,9 +1670,12 @@ import fs3 from "fs-extra";
1670
1670
  import path3 from "path";
1671
1671
  import { spawn } from "child_process";
1672
1672
  import { watch } from "chokidar";
1673
+ var isDev3 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
1674
+ var API_BASE = isDev3 ? "http://localhost:3001" : "https://tether-api.strands.gg";
1673
1675
  var frameworkProcess = null;
1674
1676
  var schemaWatcher = null;
1675
1677
  var functionsWatcher = null;
1678
+ var envWs = null;
1676
1679
  var isGenerating = false;
1677
1680
  var pendingGenerate = false;
1678
1681
  var isDeploying = false;
@@ -1684,7 +1687,7 @@ async function runGenerate(spinner) {
1684
1687
  }
1685
1688
  isGenerating = true;
1686
1689
  try {
1687
- const { generateTypes: generateTypes2 } = await import("./generate-LVU4IEMB.js");
1690
+ const { generateTypes: generateTypes2 } = await import("./generate-FTLMBVLH.js");
1688
1691
  spinner.text = "Regenerating types...";
1689
1692
  await generateTypes2({ silent: true });
1690
1693
  spinner.succeed("Types regenerated");
@@ -1791,6 +1794,44 @@ async function validateFunctions(functionsDir) {
1791
1794
  }
1792
1795
  return { valid: errors.length === 0, errors };
1793
1796
  }
1797
+ function connectToEnvironment(projectId, environment, token, spinner) {
1798
+ const wsBase = API_BASE.replace("https://", "wss://").replace("http://", "ws://");
1799
+ const wsUrl = environment && environment !== "production" ? `${wsBase}/ws/${projectId}/${environment}?token=${encodeURIComponent(token)}` : `${wsBase}/ws/${projectId}?token=${encodeURIComponent(token)}`;
1800
+ let reconnectAttempts = 0;
1801
+ const maxReconnectAttempts = 10;
1802
+ function connect() {
1803
+ try {
1804
+ envWs = new WebSocket(wsUrl);
1805
+ } catch {
1806
+ return;
1807
+ }
1808
+ envWs.onopen = () => {
1809
+ reconnectAttempts = 0;
1810
+ };
1811
+ envWs.onmessage = async (event) => {
1812
+ try {
1813
+ const data = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
1814
+ if (data.type === "env_change") {
1815
+ console.log(chalk3.cyan(`
1816
+ Environment variable ${data.action}: ${data.key}`));
1817
+ await runGenerate(spinner);
1818
+ }
1819
+ } catch {
1820
+ }
1821
+ };
1822
+ envWs.onclose = () => {
1823
+ envWs = null;
1824
+ if (reconnectAttempts < maxReconnectAttempts) {
1825
+ reconnectAttempts++;
1826
+ const delay = Math.min(1e3 * Math.pow(2, reconnectAttempts - 1), 3e4);
1827
+ setTimeout(connect, delay);
1828
+ }
1829
+ };
1830
+ envWs.onerror = () => {
1831
+ };
1832
+ }
1833
+ connect();
1834
+ }
1794
1835
  function startFrameworkDev(command, port, spinner, extraArgs = []) {
1795
1836
  const [cmd, ...args] = command.split(" ");
1796
1837
  const portArgs = ["--port", port];
@@ -1845,6 +1886,10 @@ function cleanup() {
1845
1886
  functionsWatcher.close();
1846
1887
  functionsWatcher = null;
1847
1888
  }
1889
+ if (envWs) {
1890
+ envWs.close();
1891
+ envWs = null;
1892
+ }
1848
1893
  }
1849
1894
  async function devCommand(options) {
1850
1895
  const credentials = await requireAuth();
@@ -1904,7 +1949,7 @@ async function devCommand(options) {
1904
1949
  }
1905
1950
  }
1906
1951
  spinner.text = "Generating types...";
1907
- const { generateTypes: generateTypes2 } = await import("./generate-LVU4IEMB.js");
1952
+ const { generateTypes: generateTypes2 } = await import("./generate-FTLMBVLH.js");
1908
1953
  await generateTypes2({ silent: true });
1909
1954
  spinner.succeed("Types generated");
1910
1955
  if (config.projectId) {
@@ -1960,6 +2005,9 @@ async function devCommand(options) {
1960
2005
  });
1961
2006
  }
1962
2007
  spinner.succeed("File watchers ready");
2008
+ if (config.projectId) {
2009
+ connectToEnvironment(config.projectId, environment, credentials.accessToken, spinner);
2010
+ }
1963
2011
  if (devCmd && !options.skipFramework) {
1964
2012
  spinner.start(`Starting ${framework} dev server...`);
1965
2013
  frameworkProcess = startFrameworkDev(devCmd, port, spinner, options.extraArgs || []);
@@ -1986,9 +2034,9 @@ import ora4 from "ora";
1986
2034
  import os from "os";
1987
2035
  import { exec } from "child_process";
1988
2036
  import readline from "readline";
1989
- var isDev3 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
1990
- var API_URL4 = isDev3 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
1991
- var AUTH_URL = isDev3 ? "http://localhost:3000/cli" : "https://tthr.io/cli";
2037
+ var isDev4 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
2038
+ var API_URL4 = isDev4 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
2039
+ var AUTH_URL = isDev4 ? "http://localhost:3000/cli" : "https://tthr.io/cli";
1992
2040
  async function loginCommand() {
1993
2041
  console.log(chalk4.bold("\u26A1 Login to Tether\n"));
1994
2042
  const existing = await getCredentials();
@@ -2203,18 +2251,18 @@ function detectPackageManager() {
2203
2251
  }
2204
2252
  return "npm";
2205
2253
  }
2206
- function getInstallCommand2(pm, packages, isDev6) {
2254
+ function getInstallCommand2(pm, packages, isDev7) {
2207
2255
  const packagesStr = packages.join(" ");
2208
2256
  switch (pm) {
2209
2257
  case "bun":
2210
- return isDev6 ? `bun add -d ${packagesStr}` : `bun add ${packagesStr}`;
2258
+ return isDev7 ? `bun add -d ${packagesStr}` : `bun add ${packagesStr}`;
2211
2259
  case "pnpm":
2212
- return isDev6 ? `pnpm add -D ${packagesStr}` : `pnpm add ${packagesStr}`;
2260
+ return isDev7 ? `pnpm add -D ${packagesStr}` : `pnpm add ${packagesStr}`;
2213
2261
  case "yarn":
2214
- return isDev6 ? `yarn add -D ${packagesStr}` : `yarn add ${packagesStr}`;
2262
+ return isDev7 ? `yarn add -D ${packagesStr}` : `yarn add ${packagesStr}`;
2215
2263
  case "npm":
2216
2264
  default:
2217
- return isDev6 ? `npm install -D ${packagesStr}` : `npm install ${packagesStr}`;
2265
+ return isDev7 ? `npm install -D ${packagesStr}` : `npm install ${packagesStr}`;
2218
2266
  }
2219
2267
  }
2220
2268
  async function getLatestVersion2(packageName) {
@@ -2323,8 +2371,8 @@ import chalk6 from "chalk";
2323
2371
  import ora6 from "ora";
2324
2372
  import fs5 from "fs-extra";
2325
2373
  import path5 from "path";
2326
- var isDev4 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
2327
- var API_URL5 = isDev4 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
2374
+ var isDev5 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
2375
+ var API_URL5 = isDev5 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
2328
2376
  async function execCommand(sql) {
2329
2377
  if (!sql || sql.trim() === "") {
2330
2378
  console.log(chalk6.red("\nError: SQL query required"));
@@ -2396,8 +2444,8 @@ import chalk7 from "chalk";
2396
2444
  import ora7 from "ora";
2397
2445
  import fs6 from "fs-extra";
2398
2446
  import path6 from "path";
2399
- var isDev5 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
2400
- var API_URL6 = isDev5 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
2447
+ var isDev6 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
2448
+ var API_URL6 = isDev6 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
2401
2449
  async function getProjectId() {
2402
2450
  const envPath = path6.resolve(process.cwd(), ".env");
2403
2451
  let projectId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tthr",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "description": "Tether CLI - project scaffolding and deployment",
5
5
  "type": "module",
6
6
  "bin": {