create-ts-saas 0.1.0-canary.0

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/cli.mjs ADDED
@@ -0,0 +1,857 @@
1
+ #!/usr/bin/env node
2
+ import { os } from "@orpc/server";
3
+ import { createCli } from "trpc-cli";
4
+ import { z } from "zod";
5
+ import { consola } from "consola";
6
+ import { $ } from "execa";
7
+ import pc from "picocolors";
8
+ import semver from "semver";
9
+ import path from "node:path";
10
+ import fs from "fs-extra";
11
+ import os$1 from "node:os";
12
+ import { confirm, intro, isCancel, log, note, select, spinner, text } from "@clack/prompts";
13
+ import open from "open";
14
+ import { createWriteStream } from "node:fs";
15
+ import { Readable } from "node:stream";
16
+ import { pipeline } from "node:stream/promises";
17
+ import unzipper from "unzipper";
18
+ //#region src/lib/version.ts
19
+ function getCliVersion() {
20
+ return "0.1.0-canary.0";
21
+ }
22
+ function getCliPlatform() {
23
+ return `${process.platform}-${process.arch}`;
24
+ }
25
+ //#endregion
26
+ //#region src/lib/api.ts
27
+ var ApiError = class extends Error {
28
+ code;
29
+ retryable;
30
+ status;
31
+ minCliVersion;
32
+ constructor(init) {
33
+ super(init.message);
34
+ this.name = "ApiError";
35
+ this.code = init.code;
36
+ this.retryable = init.retryable ?? false;
37
+ if (init.status !== void 0) this.status = init.status;
38
+ if (init.minCliVersion !== void 0) this.minCliVersion = init.minCliVersion;
39
+ }
40
+ };
41
+ function parseApiErrorBody(text) {
42
+ try {
43
+ const raw = JSON.parse(text);
44
+ if (raw === null || typeof raw !== "object") return null;
45
+ const envelope = raw;
46
+ if (envelope["success"] !== false || envelope["data"] !== null) return null;
47
+ const error = typeof envelope["error"] === "object" && envelope["error"] !== null ? envelope["error"] : null;
48
+ if (!error || typeof error["code"] !== "string" || typeof error["message"] !== "string") return null;
49
+ return {
50
+ code: error["code"],
51
+ message: error["message"],
52
+ ...typeof error["retryable"] === "boolean" && { retryable: error["retryable"] }
53
+ };
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+ function buildRequestHeaders(init, options) {
59
+ const headers = new Headers(init.headers);
60
+ headers.set("Accept", "application/json");
61
+ headers.set("x-cli-version", options.cliVersion);
62
+ headers.set("x-cli-platform", options.cliPlatform);
63
+ if (options.deviceId) headers.set("x-cli-device-id", options.deviceId);
64
+ if (options.accessToken) headers.set("Authorization", `Bearer ${options.accessToken}`);
65
+ return headers;
66
+ }
67
+ function checkMinCliVersion(cliVersion, minCli, status) {
68
+ if (minCli && semver.valid(cliVersion) && semver.valid(minCli) && semver.lt(cliVersion, minCli)) throw new ApiError({
69
+ code: "UPGRADE_REQUIRED",
70
+ message: `CLI version ${cliVersion} is below minimum supported ${minCli}. Please upgrade.`,
71
+ status,
72
+ minCliVersion: minCli
73
+ });
74
+ }
75
+ function parseSuccessBody(text) {
76
+ if (!text) return {};
77
+ const json = JSON.parse(text);
78
+ if (json !== null && typeof json === "object" && json["success"] === true && "data" in json) return json["data"];
79
+ throw new ApiError({
80
+ code: "INVALID_RESPONSE",
81
+ message: "Unexpected API response shape.",
82
+ retryable: false
83
+ });
84
+ }
85
+ function throwApiErrorFromResponse(text, res, minCli) {
86
+ const body = parseApiErrorBody(text);
87
+ throw new ApiError({
88
+ code: body?.code ?? (res.status === 401 ? "AUTH_INVALID" : "REQUEST_FAILED"),
89
+ message: body?.message ?? res.statusText,
90
+ retryable: body?.retryable ?? false,
91
+ status: res.status,
92
+ minCliVersion: minCli ?? void 0
93
+ });
94
+ }
95
+ function createApiClient(options) {
96
+ const { config, accessToken, deviceId } = options;
97
+ const baseUrl = config.apiBaseUrl.replace(/\/$/, "");
98
+ const cliVersion = getCliVersion();
99
+ const cliPlatform = getCliPlatform();
100
+ async function request(path, init = {}) {
101
+ const url = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
102
+ const headers = buildRequestHeaders(init, {
103
+ cliVersion,
104
+ cliPlatform,
105
+ deviceId,
106
+ accessToken
107
+ });
108
+ let res;
109
+ try {
110
+ res = await fetch(url, {
111
+ ...init,
112
+ headers
113
+ });
114
+ } catch {
115
+ throw new ApiError({
116
+ code: "NETWORK_ERROR",
117
+ message: "Network error — could not connect to the server.",
118
+ retryable: true
119
+ });
120
+ }
121
+ const minCli = res.headers.get("x-min-supported-cli");
122
+ checkMinCliVersion(cliVersion, minCli, res.status);
123
+ const text = await res.text();
124
+ if (!res.ok) throwApiErrorFromResponse(text, res, minCli);
125
+ return parseSuccessBody(text);
126
+ }
127
+ async function stream(url) {
128
+ const headers = buildRequestHeaders({}, {
129
+ cliVersion,
130
+ cliPlatform,
131
+ deviceId,
132
+ accessToken
133
+ });
134
+ let res;
135
+ try {
136
+ res = await fetch(url, { headers });
137
+ } catch {
138
+ throw new ApiError({
139
+ code: "NETWORK_ERROR",
140
+ message: "Network error — could not connect to the server.",
141
+ retryable: true
142
+ });
143
+ }
144
+ if (!res.ok) {
145
+ const body = parseApiErrorBody(await res.text());
146
+ throw new ApiError({
147
+ code: body?.code ?? "DOWNLOAD_FAILED",
148
+ message: body?.message ?? "Template download failed",
149
+ status: res.status
150
+ });
151
+ }
152
+ return res;
153
+ }
154
+ return {
155
+ baseUrl,
156
+ request,
157
+ stream,
158
+ deviceInit: () => request("/cli/device/init", {
159
+ method: "POST",
160
+ headers: { "Content-Type": "application/json" },
161
+ body: JSON.stringify({})
162
+ }),
163
+ devicePoll: (deviceCode) => request("/cli/device/poll", {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify({ deviceCode })
167
+ }),
168
+ refresh: (refreshToken) => request("/cli/auth/refresh", {
169
+ method: "POST",
170
+ headers: { "Content-Type": "application/json" },
171
+ body: JSON.stringify({ refreshToken })
172
+ }),
173
+ logoutDevice: (refreshToken) => request("/cli/device/logout", {
174
+ method: "POST",
175
+ headers: { "Content-Type": "application/json" },
176
+ body: JSON.stringify({ refreshToken })
177
+ }),
178
+ me: () => request("/cli/me"),
179
+ getTemplates: () => request("/cli/templates"),
180
+ authorizeInit: (input) => request("/cli/init/authorize", {
181
+ method: "POST",
182
+ headers: { "Content-Type": "application/json" },
183
+ body: JSON.stringify(input)
184
+ }),
185
+ getLatestVersion: () => request("/cli/latest-version")
186
+ };
187
+ }
188
+ //#endregion
189
+ //#region src/constant.ts
190
+ const DEFAULT_API_BASE_URL = "https://dev.api.ts-saas.com/api/v1";
191
+ const CONFIG_DIR_NAME = "ts-saas-cli";
192
+ const CONFIG_FILE_NAME = "config.json";
193
+ const KEYTAR_SERVICE_NAME = "create-ts-saas";
194
+ const KEYTAR_ACCOUNT_NAME = "default";
195
+ //#endregion
196
+ //#region src/lib/config.ts
197
+ function getConfigDir() {
198
+ const home = os$1.homedir();
199
+ const configHome = process.env["XDG_CONFIG_HOME"] || path.join(home, ".config");
200
+ return path.join(configHome, CONFIG_DIR_NAME);
201
+ }
202
+ function getConfigPath() {
203
+ return path.join(getConfigDir(), CONFIG_FILE_NAME);
204
+ }
205
+ async function loadConfig() {
206
+ const fromEnv = {
207
+ apiBaseUrl: DEFAULT_API_BASE_URL,
208
+ disableTelemetry: process.env["TS_SAAS_CLI_DISABLE_TELEMETRY"] === "1" || process.env["TS_SAAS_CLI_DISABLE_TELEMETRY"] === "true"
209
+ };
210
+ const configPath = getConfigPath();
211
+ try {
212
+ if (await fs.pathExists(configPath)) {
213
+ const data = await fs.readJson(configPath);
214
+ return {
215
+ apiBaseUrl: data.apiBaseUrl || fromEnv.apiBaseUrl || "https://dev.api.ts-saas.com/api/v1",
216
+ disableTelemetry: data.disableTelemetry ?? fromEnv.disableTelemetry ?? false
217
+ };
218
+ }
219
+ } catch {}
220
+ return {
221
+ apiBaseUrl: fromEnv.apiBaseUrl || "https://dev.api.ts-saas.com/api/v1",
222
+ disableTelemetry: fromEnv.disableTelemetry ?? false
223
+ };
224
+ }
225
+ //#endregion
226
+ //#region src/lib/storage.ts
227
+ const FALLBACK_FILE = "session.json";
228
+ let cachedKeytar;
229
+ function getFallbackSessionPath() {
230
+ return path.join(path.dirname(getConfigPath()), FALLBACK_FILE);
231
+ }
232
+ async function getStoredSession() {
233
+ const keytar = await getKeytar();
234
+ try {
235
+ const value = keytar ? await keytar.getPassword(KEYTAR_SERVICE_NAME, KEYTAR_ACCOUNT_NAME) : null;
236
+ if (!value) return await getFallbackSession();
237
+ const parsed = JSON.parse(value);
238
+ if (typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string" || typeof parsed.deviceId !== "string" || typeof parsed.expiresAt !== "number") return null;
239
+ return parsed;
240
+ } catch {
241
+ return await getFallbackSession();
242
+ }
243
+ }
244
+ async function setStoredSession(session) {
245
+ const serialized = JSON.stringify(session);
246
+ const keytar = await getKeytar();
247
+ try {
248
+ if (keytar) {
249
+ await keytar.setPassword(KEYTAR_SERVICE_NAME, KEYTAR_ACCOUNT_NAME, serialized);
250
+ return;
251
+ }
252
+ await setFallbackSession(session);
253
+ } catch {
254
+ await setFallbackSession(session);
255
+ }
256
+ }
257
+ async function clearStoredSession() {
258
+ const keytar = await getKeytar();
259
+ try {
260
+ if (keytar) await keytar.deletePassword(KEYTAR_SERVICE_NAME, KEYTAR_ACCOUNT_NAME);
261
+ } catch {}
262
+ try {
263
+ await fs.remove(getFallbackSessionPath());
264
+ } catch {}
265
+ }
266
+ async function getFallbackSession() {
267
+ const filePath = getFallbackSessionPath();
268
+ try {
269
+ if (!await fs.pathExists(filePath)) return null;
270
+ const value = await fs.readJson(filePath);
271
+ if (typeof value.accessToken !== "string" || typeof value.refreshToken !== "string" || typeof value.deviceId !== "string" || typeof value.expiresAt !== "number") return null;
272
+ return value;
273
+ } catch {
274
+ return null;
275
+ }
276
+ }
277
+ async function setFallbackSession(session) {
278
+ await fs.ensureDir(path.dirname(getFallbackSessionPath()));
279
+ await fs.writeJson(getFallbackSessionPath(), session, { spaces: 0 });
280
+ try {
281
+ await fs.chmod(getFallbackSessionPath(), 384);
282
+ } catch {}
283
+ }
284
+ async function getKeytar() {
285
+ if (cachedKeytar !== void 0) return cachedKeytar;
286
+ try {
287
+ const imported = await import("keytar");
288
+ cachedKeytar = imported.default || imported;
289
+ return cachedKeytar;
290
+ } catch {
291
+ cachedKeytar = null;
292
+ return null;
293
+ }
294
+ }
295
+ //#endregion
296
+ //#region src/commands/doctor.ts
297
+ async function doctorCommand() {
298
+ consola.log(pc.bold("Environment checks\n"));
299
+ const checks = [];
300
+ checks.push({
301
+ name: "Node.js",
302
+ status: Number(process.versions.node.split(".")[0]) >= 20 ? "ok" : "fail",
303
+ detail: process.version
304
+ });
305
+ try {
306
+ const result = await $`pnpm --version`;
307
+ checks.push({
308
+ name: "pnpm",
309
+ status: "ok",
310
+ detail: result.stdout.trim()
311
+ });
312
+ } catch {
313
+ checks.push({
314
+ name: "pnpm",
315
+ status: "fail",
316
+ detail: "not found"
317
+ });
318
+ }
319
+ try {
320
+ await $`git --version`;
321
+ checks.push({
322
+ name: "git",
323
+ status: "ok",
324
+ detail: "installed"
325
+ });
326
+ } catch {
327
+ checks.push({
328
+ name: "git",
329
+ status: "fail",
330
+ detail: "not found"
331
+ });
332
+ }
333
+ const config = await loadConfig();
334
+ const session = await getStoredSession();
335
+ checks.push({
336
+ name: "session",
337
+ status: session ? "ok" : "fail",
338
+ detail: session ? "present" : "missing"
339
+ });
340
+ try {
341
+ await createApiClient({
342
+ config,
343
+ accessToken: session?.accessToken || null,
344
+ deviceId: session?.deviceId || null
345
+ }).getLatestVersion();
346
+ checks.push({
347
+ name: "api",
348
+ status: "ok",
349
+ detail: config.apiBaseUrl
350
+ });
351
+ } catch {
352
+ checks.push({
353
+ name: "api",
354
+ status: "fail",
355
+ detail: "unreachable"
356
+ });
357
+ }
358
+ for (const check of checks) {
359
+ const icon = check.status === "ok" ? pc.green("✓") : pc.red("✗");
360
+ consola.log(`${icon} ${check.name}: ${check.detail}`);
361
+ }
362
+ consola.log(`\nCLI version: ${getCliVersion()}`);
363
+ }
364
+ //#endregion
365
+ //#region src/utils/open-url.ts
366
+ async function openUrl(url) {
367
+ try {
368
+ await open(url);
369
+ } catch {}
370
+ }
371
+ //#endregion
372
+ //#region src/lib/auth.ts
373
+ async function getValidSession() {
374
+ const session = await getStoredSession();
375
+ if (!session) return null;
376
+ if (session.expiresAt <= Date.now() + 6e4) return null;
377
+ return session;
378
+ }
379
+ const NOT_LOGGED_IN_MESSAGE = "Not logged in. Run `npx create-ts-saas login` first.";
380
+ var NotLoggedInError = class extends Error {
381
+ constructor() {
382
+ super(NOT_LOGGED_IN_MESSAGE);
383
+ this.name = "NotLoggedInError";
384
+ }
385
+ };
386
+ async function requireSession(apiFactory) {
387
+ const valid = await getValidSession();
388
+ if (valid) return valid;
389
+ const current = await getStoredSession();
390
+ if (current?.refreshToken) try {
391
+ const refreshed = await apiFactory(current).refresh(current.refreshToken);
392
+ const next = {
393
+ accessToken: refreshed.accessToken,
394
+ refreshToken: refreshed.refreshToken,
395
+ deviceId: current.deviceId,
396
+ expiresAt: Date.now() + refreshed.expiresIn * 1e3
397
+ };
398
+ await setStoredSession(next);
399
+ return next;
400
+ } catch {
401
+ await clearStoredSession();
402
+ }
403
+ throw new NotLoggedInError();
404
+ }
405
+ async function ensureSession(apiFactory) {
406
+ const valid = await getValidSession();
407
+ if (valid) return valid;
408
+ const current = await getStoredSession();
409
+ if (current?.refreshToken) try {
410
+ const refreshed = await apiFactory(current).refresh(current.refreshToken);
411
+ const next = {
412
+ accessToken: refreshed.accessToken,
413
+ refreshToken: refreshed.refreshToken,
414
+ deviceId: current.deviceId,
415
+ expiresAt: Date.now() + refreshed.expiresIn * 1e3
416
+ };
417
+ await setStoredSession(next);
418
+ return next;
419
+ } catch {
420
+ await clearStoredSession();
421
+ }
422
+ return await loginWithDeviceFlow(apiFactory());
423
+ }
424
+ async function loginWithDeviceFlow(api) {
425
+ const init = await api.deviceInit();
426
+ const verificationUrlWithCode = `${init.verificationUrl}${init.verificationUrl.includes("?") ? "&" : "?"}code=${encodeURIComponent(init.userCode)}`;
427
+ note(`Open ${verificationUrlWithCode} and confirm code ${init.userCode}\nCode expires in ${Math.floor(init.expiresIn / 60)} minutes.`, "Device Login");
428
+ openUrl(verificationUrlWithCode);
429
+ const deadline = Date.now() + init.expiresIn * 1e3;
430
+ while (Date.now() < deadline) {
431
+ await new Promise((resolve) => {
432
+ setTimeout(resolve, Math.max(init.interval, 3) * 1e3);
433
+ });
434
+ try {
435
+ const token = await api.devicePoll(init.deviceCode);
436
+ const session = {
437
+ accessToken: token.accessToken,
438
+ refreshToken: token.refreshToken,
439
+ deviceId: token.deviceId,
440
+ expiresAt: Date.now() + token.expiresIn * 1e3
441
+ };
442
+ await setStoredSession(session);
443
+ return session;
444
+ } catch (error) {
445
+ const code = error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
446
+ const retryable = error !== null && typeof error === "object" && "retryable" in error ? error.retryable : false;
447
+ if (code === "AUTH_PENDING" || retryable) continue;
448
+ throw error;
449
+ }
450
+ }
451
+ throw new Error("Device code expired. Run login again.");
452
+ }
453
+ async function logout(apiFactory) {
454
+ const session = await getStoredSession();
455
+ if (session?.refreshToken) try {
456
+ await apiFactory(session).logoutDevice(session.refreshToken);
457
+ } catch {}
458
+ await clearStoredSession();
459
+ }
460
+ //#endregion
461
+ //#region src/lib/scaffolder.ts
462
+ const IGNORED_ROOT_ENTRIES = /* @__PURE__ */ new Set(["__MACOSX"]);
463
+ async function streamAndExtractTemplate(downloadResponse, projectDir) {
464
+ if (!downloadResponse.body) throw new Error("Template response body is empty.");
465
+ await fs.ensureDir(projectDir);
466
+ const tempDir = path.join(projectDir, "..", `.create-ts-saas-tmp-${Date.now()}`);
467
+ const extractDir = path.join(tempDir, "extracted");
468
+ await fs.ensureDir(tempDir);
469
+ await fs.ensureDir(extractDir);
470
+ const zipPath = path.join(tempDir, "template.zip");
471
+ const writable = createWriteStream(zipPath);
472
+ await pipeline(Readable.fromWeb(downloadResponse.body), writable);
473
+ await (await unzipper.Open.file(zipPath)).extract({ path: extractDir });
474
+ const meaningfulEntries = (await fs.readdir(extractDir)).filter((name) => !IGNORED_ROOT_ENTRIES.has(name));
475
+ if (meaningfulEntries.length === 1 && meaningfulEntries[0]) {
476
+ const singleRoot = path.join(extractDir, meaningfulEntries[0]);
477
+ if ((await fs.stat(singleRoot)).isDirectory()) {
478
+ const children = await fs.readdir(singleRoot);
479
+ for (const child of children) await fs.move(path.join(singleRoot, child), path.join(projectDir, child), { overwrite: true });
480
+ } else await fs.move(singleRoot, path.join(projectDir, meaningfulEntries[0]), { overwrite: true });
481
+ } else for (const entry of meaningfulEntries) await fs.move(path.join(extractDir, entry), path.join(projectDir, entry), { overwrite: true });
482
+ await fs.remove(tempDir).catch(() => {});
483
+ }
484
+ async function writeWatermark(projectDir, payload) {
485
+ const pkgJsonPath = path.join(projectDir, "package.json");
486
+ if (await fs.pathExists(pkgJsonPath)) {
487
+ const pkgJson = await fs.readJson(pkgJsonPath);
488
+ pkgJson["create-ts-saas"] = { wId: payload["watermarkId"] || payload["issuanceId"] };
489
+ await fs.writeJson(pkgJsonPath, pkgJson, { spaces: 2 });
490
+ }
491
+ }
492
+ //#endregion
493
+ //#region src/prompts/install.ts
494
+ async function promptInstall(defaultValue = true) {
495
+ const value = await confirm({
496
+ message: "Install dependencies now?",
497
+ initialValue: defaultValue
498
+ });
499
+ if (isCancel(value)) throw new Error("Operation cancelled.");
500
+ return value;
501
+ }
502
+ //#endregion
503
+ //#region src/prompts/package-manager.ts
504
+ async function promptPackageManager(initialValue) {
505
+ const value = await select({
506
+ message: "Select package manager",
507
+ options: [
508
+ {
509
+ value: "pnpm",
510
+ label: "pnpm"
511
+ },
512
+ {
513
+ value: "npm",
514
+ label: "npm"
515
+ },
516
+ {
517
+ value: "bun",
518
+ label: "bun"
519
+ }
520
+ ],
521
+ initialValue
522
+ });
523
+ if (isCancel(value)) throw new Error("Operation cancelled.");
524
+ return value;
525
+ }
526
+ //#endregion
527
+ //#region src/prompts/project-name.ts
528
+ async function promptProjectName(initialValue = "my-saas-app") {
529
+ const value = await text({
530
+ message: "Project name",
531
+ initialValue,
532
+ validate: (input) => input?.trim() ? void 0 : "Project name is required"
533
+ });
534
+ if (isCancel(value) || typeof value !== "string") throw new Error("Operation cancelled.");
535
+ return value.trim();
536
+ }
537
+ //#endregion
538
+ //#region src/prompts/template.ts
539
+ async function promptTemplate(templates) {
540
+ const value = await select({
541
+ message: "Select template",
542
+ options: templates.map((t) => ({
543
+ value: t.slug,
544
+ label: t.slug,
545
+ hint: `latest ${t.latestVersion}`
546
+ }))
547
+ });
548
+ if (isCancel(value) || typeof value !== "string") throw new Error("Operation cancelled.");
549
+ const chosen = templates.find((t) => t.slug === value);
550
+ if (!chosen) throw new Error(`Unknown template "${value}".`);
551
+ return chosen;
552
+ }
553
+ //#endregion
554
+ //#region src/utils/get-package-manager.ts
555
+ function getUserPackageManager() {
556
+ const userAgent = process.env["npm_config_user_agent"];
557
+ if (userAgent?.startsWith("pnpm")) return "pnpm";
558
+ if (userAgent?.startsWith("bun")) return "bun";
559
+ return "npm";
560
+ }
561
+ //#endregion
562
+ //#region src/utils/handle-cli-error.ts
563
+ const DEBUG_FLAG = process.env["TS_SAAS_CLI_DEBUG"] === "1" || process.env["TS_SAAS_CLI_DEBUG"] === "true";
564
+ function isNetworkError(error) {
565
+ if (!(error instanceof Error)) return false;
566
+ const cause = error.cause;
567
+ if (cause instanceof Error) {
568
+ const code = "code" in cause ? cause.code : void 0;
569
+ if (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "ETIMEDOUT" || code === "ECONNRESET") return true;
570
+ }
571
+ return error.message === "fetch failed";
572
+ }
573
+ function handleCliError(error) {
574
+ if (isNetworkError(error)) {
575
+ log.error(pc.red("Network error — could not connect to the server."));
576
+ if (DEBUG_FLAG) console.error(error);
577
+ process.exit(1);
578
+ }
579
+ if (error instanceof ApiError) {
580
+ log.error(pc.red(error.message));
581
+ if (DEBUG_FLAG) console.error(error);
582
+ process.exit(getExitCode(error));
583
+ }
584
+ if (error instanceof NotLoggedInError) {
585
+ log.info(pc.yellow(error.message));
586
+ process.exit(2);
587
+ }
588
+ if (error instanceof Error) {
589
+ log.error(pc.red(error.message || "Something went wrong"));
590
+ console.error(error);
591
+ process.exit(1);
592
+ }
593
+ console.error("Unhandled non-Error:", error);
594
+ log.error(pc.red(typeof error === "string" ? error : "Something went wrong"));
595
+ process.exit(1);
596
+ }
597
+ function getExitCode(error) {
598
+ switch (error.code) {
599
+ case "AUTH_EXPIRED":
600
+ case "AUTH_INVALID": return 2;
601
+ case "PLAN_FORBIDDEN": return 3;
602
+ case "UPGRADE_REQUIRED": return 4;
603
+ default: return error.status && error.status >= 500 ? 1 : 1;
604
+ }
605
+ }
606
+ //#endregion
607
+ //#region src/utils/project-directory.ts
608
+ async function resolveProjectDirectory(initialInput) {
609
+ const current = initialInput;
610
+ while (true) {
611
+ const fullPath = path.resolve(process.cwd(), current);
612
+ if (!(await fs.pathExists(fullPath) && (await fs.readdir(fullPath)).length > 0)) {
613
+ await fs.ensureDir(fullPath);
614
+ return {
615
+ projectDir: fullPath,
616
+ projectName: path.basename(fullPath)
617
+ };
618
+ }
619
+ log.warn(`Directory "${pc.yellow(current)}" already exists and is not empty.`);
620
+ const action = await select({
621
+ message: "Choose how to proceed",
622
+ options: [
623
+ {
624
+ value: "merge",
625
+ label: "Merge into existing directory"
626
+ },
627
+ {
628
+ value: "overwrite",
629
+ label: "Overwrite directory contents"
630
+ },
631
+ {
632
+ value: "cancel",
633
+ label: "Cancel"
634
+ }
635
+ ],
636
+ initialValue: "merge"
637
+ });
638
+ if (isCancel(action) || action === "cancel") throw new Error("Operation cancelled.");
639
+ if (action === "merge") return {
640
+ projectDir: fullPath,
641
+ projectName: path.basename(fullPath)
642
+ };
643
+ await fs.emptyDir(fullPath);
644
+ return {
645
+ projectDir: fullPath,
646
+ projectName: path.basename(fullPath)
647
+ };
648
+ }
649
+ }
650
+ //#endregion
651
+ //#region src/commands/init.ts
652
+ async function initCommand(options) {
653
+ intro(pc.magenta("Initialize your saas..."));
654
+ try {
655
+ const config = await loadConfig();
656
+ const session = await ensureSession((current) => createApiClient({
657
+ config,
658
+ accessToken: current?.accessToken || null,
659
+ deviceId: current?.deviceId || null
660
+ }));
661
+ const api = createApiClient({
662
+ config,
663
+ accessToken: session.accessToken,
664
+ deviceId: session.deviceId
665
+ });
666
+ const { projectDir, projectName } = await resolveProjectDirectory(options.projectName || options.dir || await promptProjectName());
667
+ const templates = (await api.getTemplates()).templates;
668
+ if (!templates.length) throw new Error("No templates available for this account.");
669
+ const selectedTemplate = options.template && templates.find((template) => template.slug === options.template) ? templates.find((template) => template.slug === options.template) : await promptTemplate(templates);
670
+ if (!selectedTemplate) {
671
+ log.error(pc.red("Selected template not found."));
672
+ process.exit(1);
673
+ }
674
+ const s = spinner();
675
+ s.start("Authorizing template download...");
676
+ try {
677
+ const authz = await api.authorizeInit({ templateSlug: selectedTemplate.slug });
678
+ s.message("Downloading template...");
679
+ await streamAndExtractTemplate(await api.stream(authz.downloadUrl), projectDir);
680
+ await writeWatermark(projectDir, authz.watermark);
681
+ s.stop("Template ready.");
682
+ } catch (error) {
683
+ s.stop(pc.red("Failed to scaffold template."));
684
+ throw error;
685
+ }
686
+ const packageManager = options.packageManager || await promptPackageManager(getUserPackageManager());
687
+ if (options.install || (options.yes ? true : await promptInstall(true))) {
688
+ s.start(`Running ${packageManager} install...`);
689
+ await $({
690
+ cwd: projectDir,
691
+ stderr: "inherit"
692
+ })`${packageManager} install`;
693
+ s.stop("Dependencies installed.");
694
+ }
695
+ if (options.git || (options.yes ? true : await confirm({
696
+ message: "Initialize git?",
697
+ initialValue: true
698
+ }))) try {
699
+ await $({
700
+ cwd: projectDir,
701
+ stderr: "ignore",
702
+ stdout: "ignore"
703
+ })`git init`;
704
+ } catch {
705
+ log.warn("Git init failed. Continuing without repository setup.");
706
+ }
707
+ log.success(pc.green(`Project created at ${projectDir}`));
708
+ note([
709
+ `cd ${path.basename(projectDir)}`,
710
+ ``,
711
+ `Copy ${pc.cyan(".env.example")} → ${pc.cyan(".env")} and fill in your values`,
712
+ `Run ${pc.cyan(`${packageManager} db:migrate`)} to set up the database`,
713
+ `Run ${pc.cyan(`${packageManager} db:seed`)} to seed initial data`,
714
+ `Run ${pc.cyan(`${packageManager} dev`)} to start`
715
+ ].join("\n"), `Next steps (${projectName})`);
716
+ } catch (error) {
717
+ handleCliError(error);
718
+ }
719
+ }
720
+ //#endregion
721
+ //#region src/commands/login.ts
722
+ async function loginCommand() {
723
+ intro(pc.magenta("Login to ts-saas"));
724
+ try {
725
+ await loginWithDeviceFlow(createApiClient({ config: await loadConfig() }));
726
+ log.success(pc.green("Logged in successfully."));
727
+ } catch (error) {
728
+ handleCliError(error);
729
+ }
730
+ }
731
+ //#endregion
732
+ //#region src/commands/logout.ts
733
+ async function logoutCommand() {
734
+ intro(pc.magenta("Logout from create-ts-saas"));
735
+ try {
736
+ if (!await getStoredSession()) {
737
+ log.info(pc.yellow("No active session."));
738
+ return;
739
+ }
740
+ const config = await loadConfig();
741
+ await logout((current) => createApiClient({
742
+ config,
743
+ accessToken: current?.accessToken || null,
744
+ deviceId: current?.deviceId || null
745
+ }));
746
+ log.success(pc.green("Logged out and local session cleared."));
747
+ } catch (error) {
748
+ handleCliError(error);
749
+ }
750
+ }
751
+ //#endregion
752
+ //#region src/commands/upgrade.ts
753
+ async function upgradeCommand() {
754
+ intro(pc.magenta("Checking for updates"));
755
+ const latest = await createApiClient({ config: await loadConfig() }).getLatestVersion();
756
+ const current = getCliVersion();
757
+ if (latest.version !== current) {
758
+ log.warn(pc.yellow(`Update available: current ${current}, latest ${latest.version}. Run: npx create-ts-saas@latest`));
759
+ return;
760
+ }
761
+ log.success(pc.green(`You are on latest version (${current}).`));
762
+ }
763
+ //#endregion
764
+ //#region src/commands/whoami.ts
765
+ async function whoamiCommand() {
766
+ intro(pc.magenta("Current CLI account"));
767
+ try {
768
+ const config = await loadConfig();
769
+ if (!(await getStoredSession())?.refreshToken) {
770
+ log.info(pc.yellow(NOT_LOGGED_IN_MESSAGE));
771
+ return;
772
+ }
773
+ const session = await requireSession((current) => createApiClient({
774
+ config,
775
+ accessToken: current?.accessToken || null,
776
+ deviceId: current?.deviceId || null
777
+ }));
778
+ const data = await createApiClient({
779
+ config,
780
+ accessToken: session.accessToken,
781
+ deviceId: session.deviceId
782
+ }).me();
783
+ const lastInit = data.lastInitAt ? new Date(data.lastInitAt).toLocaleString() : "never";
784
+ note([
785
+ `Email: ${data.email}`,
786
+ `Plan: ${data.plan}`,
787
+ `Active devices: ${data.activeDevices}`,
788
+ `Last init: ${lastInit}`
789
+ ].join("\n"), "Account");
790
+ log.success(pc.green("Account lookup completed."));
791
+ } catch (error) {
792
+ handleCliError(error);
793
+ }
794
+ }
795
+ //#endregion
796
+ //#region src/index.ts
797
+ const createInputSchema = z.tuple([z.string().optional(), z.object({
798
+ dir: z.string().optional(),
799
+ yes: z.boolean().optional().default(false),
800
+ template: z.string().optional(),
801
+ packageManager: z.enum([
802
+ "npm",
803
+ "pnpm",
804
+ "bun"
805
+ ]).optional(),
806
+ install: z.boolean().optional(),
807
+ git: z.boolean().optional()
808
+ })]);
809
+ async function runCreateCommand({ input }) {
810
+ const [projectName, options] = input;
811
+ await initCommand({ ...projectName ? {
812
+ ...options,
813
+ projectName
814
+ } : options });
815
+ }
816
+ const router = os.router({
817
+ create: os.meta({
818
+ description: "Create a new project from your paid SaaS template",
819
+ default: true,
820
+ negateBooleans: true
821
+ }).input(createInputSchema).handler(runCreateCommand),
822
+ init: os.meta({ description: "Alias for create command" }).input(createInputSchema).handler(runCreateCommand),
823
+ login: os.meta({ description: "Login with device flow" }).handler(async () => {
824
+ await loginCommand();
825
+ }),
826
+ logout: os.meta({ description: "Logout and clear local auth session" }).handler(async () => {
827
+ await logoutCommand();
828
+ }),
829
+ doctor: os.meta({ description: "Run local environment checks" }).handler(async () => {
830
+ await doctorCommand();
831
+ }),
832
+ whoami: os.meta({ description: "Show authenticated account details" }).handler(async () => {
833
+ await whoamiCommand();
834
+ }),
835
+ upgrade: os.meta({ description: "Check CLI version status" }).handler(async () => {
836
+ await upgradeCommand();
837
+ })
838
+ });
839
+ function createCliApp() {
840
+ return createCli({
841
+ router,
842
+ name: "create-ts-saas",
843
+ version: getCliVersion()
844
+ });
845
+ }
846
+ async function runCli() {
847
+ try {
848
+ await createCliApp().run();
849
+ } catch (error) {
850
+ handleCliError(error);
851
+ }
852
+ }
853
+ //#endregion
854
+ //#region src/cli.ts
855
+ runCli();
856
+ //#endregion
857
+ export {};