tthr 0.3.7 → 0.3.9

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,692 @@
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 projectIdMatch = configSource.match(/projectId\s*:\s*['"]([^'"]+)['"]/);
120
+ if (projectIdMatch) {
121
+ config.projectId = projectIdMatch[1];
122
+ }
123
+ const urlMatch = configSource.match(/(?:^|\n)\s*url\s*:\s*['"]([^'"]+)['"]/);
124
+ if (urlMatch) {
125
+ config.url = urlMatch[1];
126
+ }
127
+ const envMatch = configSource.match(/environment\s*:\s*['"]([^'"]+)['"]/);
128
+ if (envMatch) {
129
+ config.environment = envMatch[1];
130
+ }
131
+ const portMatch = configSource.match(/port\s*:\s*(\d+)/);
132
+ if (portMatch) {
133
+ config.dev = { ...config.dev, port: parseInt(portMatch[1], 10) };
134
+ }
135
+ const hostMatch = configSource.match(/host\s*:\s*['"]([^'"]+)['"]/);
136
+ if (hostMatch) {
137
+ config.dev = { ...config.dev, host: hostMatch[1] };
138
+ }
139
+ return {
140
+ ...DEFAULT_CONFIG,
141
+ ...config,
142
+ dev: { ...DEFAULT_CONFIG.dev, ...config.dev },
143
+ database: { ...DEFAULT_CONFIG.database, ...config.database }
144
+ };
145
+ }
146
+ function resolvePath(configPath, cwd = process.cwd()) {
147
+ const normalised = configPath.replace(/^\.\//, "");
148
+ return path2.resolve(cwd, normalised);
149
+ }
150
+ async function detectFramework(cwd = process.cwd()) {
151
+ const packageJsonPath = path2.resolve(cwd, "package.json");
152
+ if (!await fs2.pathExists(packageJsonPath)) {
153
+ return "unknown";
154
+ }
155
+ try {
156
+ const packageJson = await fs2.readJson(packageJsonPath);
157
+ const deps = {
158
+ ...packageJson.dependencies,
159
+ ...packageJson.devDependencies
160
+ };
161
+ if (deps.nuxt || deps["@nuxt/kit"]) {
162
+ return "nuxt";
163
+ }
164
+ if (deps.next) {
165
+ return "next";
166
+ }
167
+ if (deps["@sveltejs/kit"]) {
168
+ return "sveltekit";
169
+ }
170
+ if (deps.vite && !deps.nuxt && !deps.next && !deps["@sveltejs/kit"]) {
171
+ return "vite";
172
+ }
173
+ return "vanilla";
174
+ } catch {
175
+ return "unknown";
176
+ }
177
+ }
178
+ function getFrameworkDevCommand(framework) {
179
+ switch (framework) {
180
+ case "nuxt":
181
+ return "nuxt dev";
182
+ case "next":
183
+ return "next dev";
184
+ case "sveltekit":
185
+ return "vite dev";
186
+ case "vite":
187
+ return "vite dev";
188
+ case "vanilla":
189
+ return null;
190
+ // No default dev server for vanilla
191
+ default:
192
+ return null;
193
+ }
194
+ }
195
+
196
+ // src/commands/generate.ts
197
+ var isDev2 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
198
+ var API_URL2 = isDev2 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
199
+ function parseSchemaFile(source) {
200
+ const tables = [];
201
+ const schemaMatch = source.match(/defineSchema\s*\(\s*\{([\s\S]*)\}\s*\)/);
202
+ if (!schemaMatch) return tables;
203
+ const schemaContent = schemaMatch[1];
204
+ const tableStartRegex = /(\w+)\s*:\s*\{/g;
205
+ let match;
206
+ while ((match = tableStartRegex.exec(schemaContent)) !== null) {
207
+ const tableName = match[1];
208
+ const startOffset = match.index + match[0].length;
209
+ let braceCount = 1;
210
+ let endOffset = startOffset;
211
+ for (let i = startOffset; i < schemaContent.length && braceCount > 0; i++) {
212
+ const char = schemaContent[i];
213
+ if (char === "{") braceCount++;
214
+ else if (char === "}") braceCount--;
215
+ endOffset = i;
216
+ }
217
+ const columnsContent = schemaContent.slice(startOffset, endOffset);
218
+ const columns = parseColumns(columnsContent);
219
+ tables.push({ name: tableName, columns });
220
+ }
221
+ return tables;
222
+ }
223
+ function parseColumns(content) {
224
+ const columns = [];
225
+ const columnRegex = /(\w+)\s*:\s*(\w+)(?:<([^>]+)>)?\s*\(\s*\)((?:\[.*?\]|[^,\n}])*)/g;
226
+ let match;
227
+ while ((match = columnRegex.exec(content)) !== null) {
228
+ const name = match[1];
229
+ const schemaType = match[2];
230
+ const genericType = match[3];
231
+ const modifiers = match[4] || "";
232
+ const nullable = !modifiers.includes(".notNull()");
233
+ const oneOfMatch = modifiers.match(/\.oneOf\s*\(\s*\[(.*?)\]\s*\)/);
234
+ let oneOf;
235
+ if (oneOfMatch) {
236
+ oneOf = [...oneOfMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
237
+ }
238
+ columns.push({
239
+ name,
240
+ type: schemaTypeToTS(schemaType),
241
+ nullable,
242
+ jsonType: genericType,
243
+ // Store the generic type for json columns
244
+ oneOf
245
+ });
246
+ }
247
+ return columns;
248
+ }
249
+ function schemaTypeToTS(schemaType) {
250
+ switch (schemaType) {
251
+ case "text":
252
+ return "string";
253
+ case "integer":
254
+ return "number";
255
+ case "real":
256
+ return "number";
257
+ case "boolean":
258
+ return "boolean";
259
+ case "timestamp":
260
+ return "string";
261
+ case "json":
262
+ return "unknown";
263
+ case "blob":
264
+ return "Uint8Array";
265
+ case "asset":
266
+ return "TetherAsset";
267
+ // Asset object returned by API
268
+ default:
269
+ return "unknown";
270
+ }
271
+ }
272
+ function extractSingleType(source, typeName) {
273
+ const interfaceStart = new RegExp(`(?:export\\s+)?interface\\s+${typeName}\\s*\\{`);
274
+ const interfaceMatch = interfaceStart.exec(source);
275
+ if (interfaceMatch) {
276
+ const braceStart = interfaceMatch.index + interfaceMatch[0].length;
277
+ let braceCount = 1;
278
+ let endIdx = braceStart;
279
+ for (let i = braceStart; i < source.length && braceCount > 0; i++) {
280
+ if (source[i] === "{") braceCount++;
281
+ else if (source[i] === "}") braceCount--;
282
+ endIdx = i;
283
+ }
284
+ return source.slice(interfaceMatch.index, endIdx + 1).replace(/^export\s+/, "");
285
+ }
286
+ const typeStart = new RegExp(`(?:export\\s+)?type\\s+${typeName}\\s*=`);
287
+ const typeMatch = typeStart.exec(source);
288
+ if (typeMatch) {
289
+ const semiIdx = source.indexOf(";", typeMatch.index);
290
+ if (semiIdx !== -1) {
291
+ return source.slice(typeMatch.index, semiIdx + 1).replace(/^export\s+/, "");
292
+ }
293
+ }
294
+ return null;
295
+ }
296
+ function extractTypeDefinitions(source, typeNames) {
297
+ if (typeNames.size === 0) return [];
298
+ const allDefinedTypes = /* @__PURE__ */ new Set();
299
+ const typeDefRegex = /(?:export\s+)?(?:interface|type)\s+(\w+)/g;
300
+ let m;
301
+ while ((m = typeDefRegex.exec(source)) !== null) {
302
+ allDefinedTypes.add(m[1]);
303
+ }
304
+ const resolved = /* @__PURE__ */ new Map();
305
+ const queue = [...typeNames];
306
+ while (queue.length > 0) {
307
+ const name = queue.shift();
308
+ if (resolved.has(name)) continue;
309
+ const block = extractSingleType(source, name);
310
+ if (!block) continue;
311
+ resolved.set(name, block);
312
+ for (const definedType of allDefinedTypes) {
313
+ if (!resolved.has(definedType) && !queue.includes(definedType)) {
314
+ const refRegex = new RegExp(`\\b${definedType}\\b`);
315
+ if (refRegex.test(block)) {
316
+ queue.push(definedType);
317
+ }
318
+ }
319
+ }
320
+ }
321
+ const ordered = [];
322
+ const visited = /* @__PURE__ */ new Set();
323
+ function visit(name) {
324
+ if (visited.has(name)) return;
325
+ visited.add(name);
326
+ const block = resolved.get(name);
327
+ if (!block) return;
328
+ for (const dep of resolved.keys()) {
329
+ if (dep !== name && new RegExp(`\\b${dep}\\b`).test(block)) {
330
+ visit(dep);
331
+ }
332
+ }
333
+ ordered.push(name);
334
+ }
335
+ for (const name of resolved.keys()) {
336
+ visit(name);
337
+ }
338
+ return ordered.map((name) => resolved.get(name));
339
+ }
340
+ function tableNameToInterface(tableName) {
341
+ let name = tableName;
342
+ if (name.endsWith("ies")) {
343
+ name = name.slice(0, -3) + "y";
344
+ } else if (name.endsWith("s") && !name.endsWith("ss")) {
345
+ name = name.slice(0, -1);
346
+ }
347
+ return name.charAt(0).toUpperCase() + name.slice(1);
348
+ }
349
+ function generateDbFile(tables, schemaSource) {
350
+ const TS_PRIMITIVES = /* @__PURE__ */ new Set(["number", "string", "boolean", "unknown", "any", "void", "never", "undefined", "null", "object"]);
351
+ const jsonTypes = /* @__PURE__ */ new Set();
352
+ for (const table of tables) {
353
+ for (const col of table.columns) {
354
+ if (col.jsonType) {
355
+ const baseType = col.jsonType.replace(/\s*\|\s*null/g, "").replace(/\[\]/g, "").trim();
356
+ if (!TS_PRIMITIVES.has(baseType)) {
357
+ jsonTypes.add(baseType);
358
+ }
359
+ }
360
+ }
361
+ }
362
+ const lines = [
363
+ "// Auto-generated by Tether CLI - do not edit manually",
364
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
365
+ "",
366
+ "import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
367
+ "import {",
368
+ " type QueryDefinition,",
369
+ " type MutationDefinition,",
370
+ " z,",
371
+ "} from '@tthr/server';",
372
+ "import type { TetherEnv } from './env';"
373
+ ];
374
+ if (jsonTypes.size > 0) {
375
+ const typeBlocks = extractTypeDefinitions(schemaSource, jsonTypes);
376
+ if (typeBlocks.length > 0) {
377
+ lines.push("");
378
+ lines.push("// Schema types (inlined from schema.ts)");
379
+ for (const block of typeBlocks) {
380
+ lines.push(block);
381
+ lines.push("");
382
+ }
383
+ }
384
+ }
385
+ lines.push("");
386
+ lines.push("// Asset type returned by the API for asset columns");
387
+ lines.push("export interface TetherAsset {");
388
+ lines.push(" id: string;");
389
+ lines.push(" filename: string;");
390
+ lines.push(" contentType: string;");
391
+ lines.push(" size: number;");
392
+ lines.push(" url: string;");
393
+ lines.push(" createdAt: string;");
394
+ lines.push("}");
395
+ lines.push("");
396
+ for (const table of tables) {
397
+ const interfaceName = tableNameToInterface(table.name);
398
+ lines.push(`export interface ${interfaceName} {`);
399
+ lines.push(" _id: string;");
400
+ for (const col of table.columns) {
401
+ let colType;
402
+ if (col.oneOf && col.oneOf.length > 0) {
403
+ colType = col.oneOf.map((v) => `'${v}'`).join(" | ");
404
+ } else {
405
+ colType = col.jsonType || col.type;
406
+ }
407
+ const typeStr = col.nullable ? `${colType} | null` : colType;
408
+ const optional = col.nullable ? "?" : "";
409
+ lines.push(` ${col.name}${optional}: ${typeStr};`);
410
+ }
411
+ lines.push(" _createdAt: string;");
412
+ lines.push(" _updatedAt?: string | null;");
413
+ lines.push(" _deletedAt?: string | null;");
414
+ lines.push("}");
415
+ lines.push("");
416
+ }
417
+ lines.push("export interface Schema {");
418
+ for (const table of tables) {
419
+ const interfaceName = tableNameToInterface(table.name);
420
+ lines.push(` ${table.name}: ${interfaceName};`);
421
+ }
422
+ lines.push("}");
423
+ lines.push("");
424
+ lines.push("// Database client with typed tables");
425
+ lines.push("// This is a proxy that will be populated by the Tether runtime");
426
+ lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
427
+ lines.push("");
428
+ lines.push("// ============================================================================");
429
+ lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
430
+ lines.push("// This ensures the `db` and `env` parameters in handlers are properly typed");
431
+ lines.push("// ============================================================================");
432
+ lines.push("");
433
+ lines.push("/**");
434
+ lines.push(" * Define a query function with typed database and environment variable access.");
435
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
436
+ lines.push(" */");
437
+ lines.push("export function query<TArgs = void, TResult = unknown>(");
438
+ lines.push(" definition: QueryDefinition<TArgs, TResult, Schema, TetherEnv>");
439
+ lines.push("): QueryDefinition<TArgs, TResult, Schema, TetherEnv> {");
440
+ lines.push(" return definition;");
441
+ lines.push("}");
442
+ lines.push("");
443
+ lines.push("/**");
444
+ lines.push(" * Define a mutation function with typed database and environment variable access.");
445
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
446
+ lines.push(" */");
447
+ lines.push("export function mutation<TArgs = void, TResult = unknown>(");
448
+ lines.push(" definition: MutationDefinition<TArgs, TResult, Schema, TetherEnv>");
449
+ lines.push("): MutationDefinition<TArgs, TResult, Schema, TetherEnv> {");
450
+ lines.push(" return definition;");
451
+ lines.push("}");
452
+ lines.push("");
453
+ lines.push("// Re-export z for convenience");
454
+ lines.push("export { z };");
455
+ lines.push("");
456
+ return lines.join("\n");
457
+ }
458
+ async function parseFunctionsDir(functionsDir) {
459
+ const functions = [];
460
+ if (!await fs3.pathExists(functionsDir)) {
461
+ return functions;
462
+ }
463
+ const files = await fs3.readdir(functionsDir);
464
+ for (const file of files) {
465
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
466
+ const filePath = path3.join(functionsDir, file);
467
+ const stat = await fs3.stat(filePath);
468
+ if (!stat.isFile()) continue;
469
+ const moduleName = file.replace(/\.(ts|js)$/, "");
470
+ const source = await fs3.readFile(filePath, "utf-8");
471
+ const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation)\s*\(/g;
472
+ let match;
473
+ while ((match = exportRegex.exec(source)) !== null) {
474
+ functions.push({
475
+ name: match[1],
476
+ moduleName
477
+ });
478
+ }
479
+ }
480
+ return functions;
481
+ }
482
+ async function generateApiFile(functionsDir) {
483
+ const functions = await parseFunctionsDir(functionsDir);
484
+ const moduleMap = /* @__PURE__ */ new Map();
485
+ for (const fn of functions) {
486
+ if (!moduleMap.has(fn.moduleName)) {
487
+ moduleMap.set(fn.moduleName, []);
488
+ }
489
+ moduleMap.get(fn.moduleName).push(fn.name);
490
+ }
491
+ const lines = [
492
+ "// Auto-generated by Tether CLI - do not edit manually",
493
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
494
+ "",
495
+ "import { createApiProxy } from '@tthr/client';",
496
+ "",
497
+ "/**",
498
+ " * API function reference type for useQuery/useMutation.",
499
+ ' * The _name property contains the function path (e.g., "users.list").',
500
+ " */",
501
+ "export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
502
+ " _name: string;",
503
+ " _args?: TArgs;",
504
+ " _result?: TResult;",
505
+ "}",
506
+ ""
507
+ ];
508
+ if (moduleMap.size > 0) {
509
+ for (const [moduleName, fnNames] of moduleMap) {
510
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
511
+ lines.push(`export interface ${interfaceName} {`);
512
+ for (const fnName of fnNames) {
513
+ lines.push(` ${fnName}: ApiFunction;`);
514
+ }
515
+ lines.push("}");
516
+ lines.push("");
517
+ }
518
+ lines.push("export interface Api {");
519
+ for (const moduleName of moduleMap.keys()) {
520
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
521
+ lines.push(` ${moduleName}: ${interfaceName};`);
522
+ }
523
+ lines.push("}");
524
+ } else {
525
+ lines.push("/**");
526
+ lines.push(" * Flexible API type that allows access to any function path.");
527
+ lines.push(" * Functions are accessed as api.moduleName.functionName");
528
+ lines.push(" * The actual types depend on your function definitions.");
529
+ lines.push(" */");
530
+ lines.push("export type Api = {");
531
+ lines.push(" [module: string]: {");
532
+ lines.push(" [fn: string]: ApiFunction;");
533
+ lines.push(" };");
534
+ lines.push("};");
535
+ }
536
+ lines.push("");
537
+ lines.push("// API client proxy - provides typed access to your functions");
538
+ lines.push("// On the client: returns { _name } references for useQuery/useMutation");
539
+ lines.push("// In Tether functions: calls the actual function implementation");
540
+ lines.push("export const api = createApiProxy<Api>();");
541
+ lines.push("");
542
+ return lines.join("\n");
543
+ }
544
+ async function fetchEnvVarKeys(projectId, environment) {
545
+ const credentials = await getCredentials();
546
+ if (!credentials) return [];
547
+ const envPath = environment !== "production" ? `/projects/${projectId}/env/${environment}/env-vars` : `/projects/${projectId}/env-vars`;
548
+ try {
549
+ const response = await fetch(`${API_URL2}${envPath}`, {
550
+ headers: {
551
+ "Authorization": `Bearer ${credentials.accessToken}`
552
+ }
553
+ });
554
+ if (!response.ok) return [];
555
+ const data = await response.json();
556
+ return (data.envVars || []).map((v) => v.key).sort();
557
+ } catch {
558
+ return [];
559
+ }
560
+ }
561
+ function generateEnvFile(keys) {
562
+ const lines = [
563
+ "// Auto-generated by Tether CLI - do not edit manually",
564
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
565
+ "",
566
+ "/**",
567
+ " * Typed environment variables for this project.",
568
+ " * Keys are fetched from the Tether API \u2014 values are never exposed.",
569
+ ' * Use `env.get("KEY")` in your functions to access them.',
570
+ " */",
571
+ ""
572
+ ];
573
+ if (keys.length > 0) {
574
+ lines.push("export type EnvVarKey =");
575
+ for (let i = 0; i < keys.length; i++) {
576
+ const sep = i === keys.length - 1 ? ";" : "";
577
+ lines.push(` | '${keys[i]}'${sep}`);
578
+ }
579
+ lines.push("");
580
+ lines.push("export interface TetherEnv {");
581
+ for (const key of keys) {
582
+ lines.push(` ${key}: string;`);
583
+ }
584
+ lines.push("}");
585
+ } else {
586
+ lines.push("export type EnvVarKey = string;");
587
+ lines.push("");
588
+ lines.push("export interface TetherEnv {");
589
+ lines.push(" [key: string]: string;");
590
+ lines.push("}");
591
+ }
592
+ lines.push("");
593
+ return lines.join("\n");
594
+ }
595
+ async function generateTypes(options = {}) {
596
+ const config = await loadConfig();
597
+ const schemaPath = resolvePath(config.schema);
598
+ const outputDir = resolvePath(config.output);
599
+ const functionsDir = resolvePath(config.functions);
600
+ if (!await fs3.pathExists(schemaPath)) {
601
+ throw new Error(`Schema file not found: ${schemaPath}`);
602
+ }
603
+ const schemaSource = await fs3.readFile(schemaPath, "utf-8");
604
+ const tables = parseSchemaFile(schemaSource);
605
+ const environment = config.environment || "development";
606
+ let projectId;
607
+ const envFilePath = path3.resolve(process.cwd(), ".env");
608
+ if (await fs3.pathExists(envFilePath)) {
609
+ const envContent = await fs3.readFile(envFilePath, "utf-8");
610
+ const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
611
+ projectId = match?.[1]?.trim();
612
+ }
613
+ const envVarKeys = projectId ? await fetchEnvVarKeys(projectId, environment) : [];
614
+ await fs3.ensureDir(outputDir);
615
+ await fs3.writeFile(
616
+ path3.join(outputDir, "db.ts"),
617
+ generateDbFile(tables, schemaSource)
618
+ );
619
+ await fs3.writeFile(
620
+ path3.join(outputDir, "api.ts"),
621
+ await generateApiFile(functionsDir)
622
+ );
623
+ await fs3.writeFile(
624
+ path3.join(outputDir, "env.ts"),
625
+ generateEnvFile(envVarKeys)
626
+ );
627
+ await fs3.writeFile(
628
+ path3.join(outputDir, "index.ts"),
629
+ `// Auto-generated by Tether CLI - do not edit manually
630
+ export * from './db';
631
+ export * from './api';
632
+ export * from './env';
633
+ `
634
+ );
635
+ return { tables, envVarKeys, outputDir };
636
+ }
637
+ async function generateCommand() {
638
+ await requireAuth();
639
+ const configPath = path3.resolve(process.cwd(), "tether.config.ts");
640
+ if (!await fs3.pathExists(configPath)) {
641
+ console.log(chalk2.red("\nError: Not a Tether project"));
642
+ console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
643
+ process.exit(1);
644
+ }
645
+ console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
646
+ const spinner = ora("Reading schema...").start();
647
+ try {
648
+ spinner.text = "Generating types...";
649
+ const { tables, envVarKeys, outputDir } = await generateTypes();
650
+ if (tables.length === 0) {
651
+ spinner.warn("No tables found in schema");
652
+ console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
653
+ return;
654
+ }
655
+ spinner.succeed(`Types generated for ${tables.length} table(s)`);
656
+ console.log("\n" + chalk2.green("\u2713") + " Tables:");
657
+ for (const table of tables) {
658
+ console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
659
+ }
660
+ if (envVarKeys.length > 0) {
661
+ console.log("\n" + chalk2.green("\u2713") + ` Environment variables: ${envVarKeys.length} key(s)`);
662
+ for (const key of envVarKeys) {
663
+ console.log(chalk2.dim(` - ${key}`));
664
+ }
665
+ }
666
+ const relativeOutput = path3.relative(process.cwd(), outputDir);
667
+ console.log("\n" + chalk2.green("\u2713") + " Generated files:");
668
+ console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
669
+ console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
670
+ console.log(chalk2.dim(` ${relativeOutput}/env.ts`));
671
+ console.log(chalk2.dim(` ${relativeOutput}/index.ts
672
+ `));
673
+ } catch (error) {
674
+ spinner.fail("Failed to generate types");
675
+ console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
676
+ process.exit(1);
677
+ }
678
+ }
679
+
680
+ export {
681
+ API_URL,
682
+ getCredentials,
683
+ requireAuth,
684
+ saveCredentials,
685
+ clearCredentials,
686
+ loadConfig,
687
+ resolvePath,
688
+ detectFramework,
689
+ getFrameworkDevCommand,
690
+ generateTypes,
691
+ generateCommand
692
+ };
@@ -0,0 +1,8 @@
1
+ import {
2
+ generateCommand,
3
+ generateTypes
4
+ } from "./chunk-FUIPVG5Y.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-CPBP6GSK.js";
14
+ } from "./chunk-FUIPVG5Y.js";
15
15
 
16
16
  // src/index.ts
17
17
  import { Command } from "commander";
@@ -43,16 +43,19 @@ async function deployCommand(options) {
43
43
  console.log(chalk.dim("Run `tthr init` to create a new project\n"));
44
44
  process.exit(1);
45
45
  }
46
- const envPath = path.resolve(process.cwd(), ".env");
47
- let projectId;
48
- if (await fs.pathExists(envPath)) {
49
- const envContent = await fs.readFile(envPath, "utf-8");
50
- const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
51
- projectId = match?.[1]?.trim();
46
+ const config = await loadConfig();
47
+ let projectId = config.projectId;
48
+ if (!projectId) {
49
+ const envPath = path.resolve(process.cwd(), ".env");
50
+ if (await fs.pathExists(envPath)) {
51
+ const envContent = await fs.readFile(envPath, "utf-8");
52
+ const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
53
+ projectId = match?.[1]?.trim();
54
+ }
52
55
  }
53
56
  if (!projectId) {
54
57
  console.log(chalk.red("\nError: Project ID not found"));
55
- console.log(chalk.dim("Make sure TETHER_PROJECT_ID is set in your .env file\n"));
58
+ console.log(chalk.dim("Set projectId in tether.config.ts or TETHER_PROJECT_ID in your .env file\n"));
56
59
  process.exit(1);
57
60
  }
58
61
  const environment = options.env || "development";
@@ -68,7 +71,6 @@ async function deployCommand(options) {
68
71
  } catch (error) {
69
72
  console.log(chalk.dim(" Skipping type generation (schema may not exist yet)"));
70
73
  }
71
- const config = await loadConfig();
72
74
  const deploySchema = options.schema || !options.schema && !options.functions;
73
75
  const deployFunctions = options.functions || !options.schema && !options.functions;
74
76
  if (deploySchema) {
@@ -1687,7 +1689,7 @@ async function runGenerate(spinner) {
1687
1689
  }
1688
1690
  isGenerating = true;
1689
1691
  try {
1690
- const { generateTypes: generateTypes2 } = await import("./generate-FTLMBVLH.js");
1692
+ const { generateTypes: generateTypes2 } = await import("./generate-OKE6YGA3.js");
1691
1693
  spinner.text = "Regenerating types...";
1692
1694
  await generateTypes2({ silent: true });
1693
1695
  spinner.succeed("Types regenerated");
@@ -1837,7 +1839,7 @@ function startFrameworkDev(command, port, spinner, extraArgs = []) {
1837
1839
  const portArgs = ["--port", port];
1838
1840
  const allArgs = [...args, ...portArgs, ...extraArgs];
1839
1841
  spinner.text = `Starting ${command}${extraArgs.length ? ` with extra args: ${extraArgs.join(" ")}` : ""}...`;
1840
- const child = spawn(cmd, allArgs, {
1842
+ const child = spawn("npx", [cmd, ...allArgs], {
1841
1843
  cwd: process.cwd(),
1842
1844
  stdio: ["inherit", "pipe", "pipe"],
1843
1845
  shell: true,
@@ -1900,6 +1902,14 @@ async function devCommand(options) {
1900
1902
  process.exit(1);
1901
1903
  }
1902
1904
  const config = await loadConfig();
1905
+ if (!config.projectId) {
1906
+ const envPath = path3.resolve(process.cwd(), ".env");
1907
+ if (await fs3.pathExists(envPath)) {
1908
+ const envContent = await fs3.readFile(envPath, "utf-8");
1909
+ const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
1910
+ if (match) config.projectId = match[1].trim();
1911
+ }
1912
+ }
1903
1913
  const port = options.port || String(config.dev?.port || 3001);
1904
1914
  const schemaPath = resolvePath(config.schema);
1905
1915
  const functionsDir = resolvePath(config.functions);
@@ -1949,7 +1959,7 @@ async function devCommand(options) {
1949
1959
  }
1950
1960
  }
1951
1961
  spinner.text = "Generating types...";
1952
- const { generateTypes: generateTypes2 } = await import("./generate-FTLMBVLH.js");
1962
+ const { generateTypes: generateTypes2 } = await import("./generate-OKE6YGA3.js");
1953
1963
  await generateTypes2({ silent: true });
1954
1964
  spinner.succeed("Types generated");
1955
1965
  if (config.projectId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tthr",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "description": "Tether CLI - project scaffolding and deployment",
5
5
  "type": "module",
6
6
  "bin": {