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