From 66ebff4a5fdd3a6edd1516a26c96f1eb367e9bb6 Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 00:09:45 +0100 Subject: [PATCH 01/13] refactor(installation): remove package installations --- package.json | 1 - src/module.ts | 21 ------------- src/package-utils/log-helpers.ts | 11 ------- src/package-utils/setup-helpers.ts | 49 ------------------------------ 4 files changed, 82 deletions(-) diff --git a/package.json b/package.json index b872c5b..e08b02b 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,6 @@ "chalk": "^5.3.0", "defu": "^6.1.4", "execa": "^8.0.1", - "nypm": "^0.4.1", "pathe": "^1.1.2", "prompts": "^2.4.2" }, diff --git a/src/module.ts b/src/module.ts index 4f00d0a..3b7297c 100644 --- a/src/module.ts +++ b/src/module.ts @@ -13,11 +13,8 @@ import { checkIfMigrationsFolderExists, checkIfPrismaSchemaExists, formatSchema, - installPrismaClient, initPrisma, - installPrismaCLI, installStudio, - isPrismaCLIInstalled, runMigration, writeClientInLib, writeToSchema, @@ -32,8 +29,6 @@ interface ModuleOptions extends Prisma.PrismaClientOptions { writeToSchema: boolean; formatSchema: boolean; runMigration: boolean; - installClient: boolean; - installCLI: boolean; generateClient: boolean; installStudio: boolean; autoSetupPrisma: boolean; @@ -62,8 +57,6 @@ export default defineNuxtModule({ writeToSchema: true, formatSchema: true, runMigration: true, - installClient: true, - installCLI: true, generateClient: true, installStudio: true, autoSetupPrisma: false, @@ -138,19 +131,6 @@ export default defineNuxtModule({ ? resolveProject(options.prismaRoot) // Combines paths safely : PROJECT_PATH; - // Ensure Prisma CLI is installed if required - if (options.installCLI) { - const prismaInstalled = await isPrismaCLIInstalled(PROJECT_PATH); - if (!prismaInstalled) { - await installPrismaCLI(PROJECT_PATH); - await generatePrismaClient( - PROJECT_PATH, - PRISMA_SCHEMA_CMD, - options.log?.includes("error"), - ); - } - } - // Check if Prisma schema exists const prismaSchemaExists = checkIfPrismaSchemaExists([ resolveProject(LAYER_PATH, "prisma", "schema.prisma"), @@ -242,7 +222,6 @@ export default defineNuxtModule({ await writeClientInLib(LAYER_PATH); if (options.generateClient) { - await installPrismaClient(PROJECT_PATH, options.installClient); await generatePrismaClient( PROJECT_PATH, PRISMA_SCHEMA_CMD, diff --git a/src/package-utils/log-helpers.ts b/src/package-utils/log-helpers.ts index d70e207..0c97234 100644 --- a/src/package-utils/log-helpers.ts +++ b/src/package-utils/log-helpers.ts @@ -17,15 +17,6 @@ export function log(message: any) { } export const PREDEFINED_LOG_MESSAGES = { - isPrismaCLIinstalled: { - yes: `Prisma CLI is already installed.`, - no: `Prisma CLI is not installed.`, - }, - installPrismaCLI: { - action: "Installing Prisma CLI...", - yes: `Successfully installed "Prisma CLI.`, - no: `Failed to install Prisma CLI.`, - }, checkIfPrismaSchemaExists: { yes: "Prisma schema file exists.", no: "Prisma schema file does not exist.", @@ -54,8 +45,6 @@ export const PREDEFINED_LOG_MESSAGES = { }, generatePrismaClient: { action: "Generating Prisma client...\n", - prismaClientInstallationError: "Failed to install Prisma Client.\n", - success: "Prisma Client successfully generated!", error: "Failed to generate Prisma Client.\n", }, installStudio: { diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index b71ec91..1c63321 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -7,7 +7,6 @@ import { } from "./log-helpers"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; import { join } from "pathe"; -import { addDependency, addDevDependency } from "nypm"; export type DatabaseProviderType = | "sqlite" @@ -24,33 +23,6 @@ export type PrismaInitOptions = { rootDir: string; }; -export async function isPrismaCLIInstalled( - directory: string, -): Promise { - try { - await execa("npx", ["prisma", "version"], { cwd: directory }); - logSuccess(PREDEFINED_LOG_MESSAGES.isPrismaCLIinstalled.yes); - return true; - } catch (error) { - logError(PREDEFINED_LOG_MESSAGES.isPrismaCLIinstalled.no); - // log(error); - return false; - } -} - -export async function installPrismaCLI(directory: string) { - try { - await addDevDependency("prisma", { - cwd: directory, - }); - - logSuccess(PREDEFINED_LOG_MESSAGES.installPrismaCLI.yes); - } catch (err) { - logError(PREDEFINED_LOG_MESSAGES.installPrismaCLI.no); - log(err); - } -} - export function checkIfPrismaSchemaExists(paths: string[]) { const exists = paths.reduce((prev, current) => { return existsSync(current) || prev; @@ -215,27 +187,6 @@ export async function formatSchema(directory: string, schemaPath: string[]) { } } -export async function installPrismaClient( - directory: string, - installPrismaClient: boolean = true, -) { - log(PREDEFINED_LOG_MESSAGES.generatePrismaClient.action); - - if (installPrismaClient) { - try { - await addDependency("@prisma/client", { - cwd: directory, - }); - } catch (error) { - logError( - PREDEFINED_LOG_MESSAGES.generatePrismaClient - .prismaClientInstallationError, - ); - // log(error); - } - } -} - export async function generatePrismaClient( directory: string, prismaSchemaPath: string[], From f722e681cd6fbdc0696b556686aed04d5af7837c Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 00:15:47 +0100 Subject: [PATCH 02/13] refactor(studio): replace tab hook with function --- src/module.ts | 35 +++++++++++++----------------- src/package-utils/setup-helpers.ts | 2 +- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/module.ts b/src/module.ts index 3b7297c..39c0262 100644 --- a/src/module.ts +++ b/src/module.ts @@ -5,6 +5,7 @@ import { addImportsDir, addServerImportsDir, } from "@nuxt/kit"; +import { addCustomTab } from '@nuxt/devtools-kit' import { fileURLToPath } from "url"; import defu from "defu"; @@ -14,7 +15,7 @@ import { checkIfPrismaSchemaExists, formatSchema, initPrisma, - installStudio, + startPrismaStudio, runMigration, writeClientInLib, writeToSchema, @@ -193,25 +194,19 @@ export default defineNuxtModule({ return; } - const installAndStartPrismaStudio = async () => { - await installStudio(PROJECT_PATH, PRISMA_SCHEMA_CMD); - - nuxt.hooks.hook("devtools:customTabs", (tab) => { - tab.push({ - name: "nuxt-prisma", - title: "Prisma Studio", - icon: "simple-icons:prisma", - category: "server", - view: { - type: "iframe", - src: "http://localhost:5555/", - persistent: true, - }, - }); - }); - }; - - await installAndStartPrismaStudio(); + await startPrismaStudio(PROJECT_PATH, PRISMA_SCHEMA_CMD); + + addCustomTab({ + name: "nuxt-prisma", + title: "Prisma Studio", + icon: "simple-icons:prisma", + category: "server", + view: { + type: "iframe", + src: "http://localhost:5555/", + persistent: true + } + }); }; // Execute workflows sequentially diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index 1c63321..faa5410 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -208,7 +208,7 @@ export async function generatePrismaClient( } } -export async function installStudio( +export async function startPrismaStudio( directory: string, schemaLocation: string[], ) { From 1df2f6622f5ff5d8e7827d24c5f5fdfe9ec5656e Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 00:19:25 +0100 Subject: [PATCH 03/13] refactor(package-utils): simplify Prisma command execution by removing static executor --- src/package-utils/setup-helpers.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index faa5410..52d79f4 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -73,7 +73,7 @@ export async function initPrisma({ provider = "sqlite", datasourceUrl, }: PrismaInitOptions) { - const commandArgs = ["prisma", "init", "--datasource-provider"]; + const commandArgs = ["init", "--datasource-provider"]; commandArgs.push(provider); @@ -85,7 +85,7 @@ export async function initPrisma({ try { log(PREDEFINED_LOG_MESSAGES.initPrisma.action); - const { stdout: initializePrisma } = await execa("npx", commandArgs, { + const { stdout: initializePrisma } = await execa("prisma", commandArgs, { cwd: directory, }); @@ -160,8 +160,8 @@ export async function runMigration(directory: string, schemaPath: string[]) { log(PREDEFINED_LOG_MESSAGES.runMigration.action); await execa( - "npx", - ["prisma", "migrate", "dev", "--name", "init"].concat(schemaPath), + "prisma", + ["migrate", "dev", "--name", "init"].concat(schemaPath), { cwd: directory, }, @@ -179,7 +179,7 @@ export async function runMigration(directory: string, schemaPath: string[]) { export async function formatSchema(directory: string, schemaPath: string[]) { try { log(PREDEFINED_LOG_MESSAGES.formatSchema.action); - await execa("npx", ["prisma", "format"].concat(schemaPath), { + await execa("prisma", ["format"].concat(schemaPath), { cwd: directory, }); } catch { @@ -194,8 +194,8 @@ export async function generatePrismaClient( ) { try { const { stdout: generateClient } = await execa( - "npx", - ["prisma", "generate"].concat(prismaSchemaPath), + "prisma", + ["generate"].concat(prismaSchemaPath), { cwd: directory }, ); @@ -216,8 +216,8 @@ export async function startPrismaStudio( log(PREDEFINED_LOG_MESSAGES.installStudio.action); const subprocess = execa( - "npx", - ["prisma", "studio", "--browser", "none"].concat(schemaLocation), + "prisma", + ["studio", "--browser", "none"].concat(schemaLocation), { cwd: directory, }, From 5e45b1c15193633da7620e651a5e56a9f31971e9 Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 00:22:49 +0100 Subject: [PATCH 04/13] style(logs): change names of logs & add generatePrismaClient log --- src/package-utils/log-helpers.ts | 6 +++--- src/package-utils/setup-helpers.ts | 8 +++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/package-utils/log-helpers.ts b/src/package-utils/log-helpers.ts index 0c97234..c97944e 100644 --- a/src/package-utils/log-helpers.ts +++ b/src/package-utils/log-helpers.ts @@ -47,14 +47,14 @@ export const PREDEFINED_LOG_MESSAGES = { action: "Generating Prisma client...\n", error: "Failed to generate Prisma Client.\n", }, - installStudio: { + startPrismaStudio: { action: "Starting Prisma Studio...\n", success: - `Prisma Studio installed.` + + `Prisma Studio started.` + chalk.white( `\nAfter clicking ${chalk.bold("Get Started")} in Nuxt DevTools, click on the ${chalk.bold("three dots (︙)")} in the lower left-hand side to reveal additional tabs.\nLocate the Prisma logo to open Prisma Studio.`, ), - error: "Failed to install Prisma Studio.", + error: "Failed to start Prisma Studio.", }, writeClientInLib: { found: diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index 52d79f4..3c78415 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -192,6 +192,8 @@ export async function generatePrismaClient( prismaSchemaPath: string[], verboseLog: boolean = false, ) { + log(PREDEFINED_LOG_MESSAGES.generatePrismaClient.action); + try { const { stdout: generateClient } = await execa( "prisma", @@ -213,7 +215,7 @@ export async function startPrismaStudio( schemaLocation: string[], ) { try { - log(PREDEFINED_LOG_MESSAGES.installStudio.action); + log(PREDEFINED_LOG_MESSAGES.startPrismaStudio.action); const subprocess = execa( "prisma", @@ -225,11 +227,11 @@ export async function startPrismaStudio( subprocess.unref(); - logSuccess(PREDEFINED_LOG_MESSAGES.installStudio.success); + logSuccess(PREDEFINED_LOG_MESSAGES.startPrismaStudio.success); return true; } catch (err) { - logError(PREDEFINED_LOG_MESSAGES.installStudio.error); + logError(PREDEFINED_LOG_MESSAGES.startPrismaStudio.error); log(err); return false; } From db3b3469cd83782072bd8747cd98259438fc363a Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 00:28:05 +0100 Subject: [PATCH 05/13] refactor(logs): replace chalk with tinyrainbow --- package.json | 2 +- src/package-utils/log-helpers.ts | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index e08b02b..22ddf3a 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,6 @@ "@nuxt/devtools-kit": "^1.3.3", "@nuxt/kit": "^3.11.2", "@prisma/client": "^6.1.0", - "chalk": "^5.3.0", "defu": "^6.1.4", "execa": "^8.0.1", "pathe": "^1.1.2", @@ -67,6 +66,7 @@ "prettier": "3.2.5", "prisma": "^6.1.0", "semantic-release": "^24.2.0", + "tinyrainbow": "^1.2.0", "vitest": "^1.2.2" }, "config": { diff --git a/src/package-utils/log-helpers.ts b/src/package-utils/log-helpers.ts index c97944e..19e3e4c 100644 --- a/src/package-utils/log-helpers.ts +++ b/src/package-utils/log-helpers.ts @@ -1,15 +1,15 @@ -import chalk from "chalk"; +import c from 'tinyrainbow' export function logSuccess(message: string) { - console.log(chalk.green(`✔ ${message}`)); + console.log(c.green(`✔ ${message}`)); } export function logWarning(message: string) { - console.warn(chalk.yellow(`⚠️ ${message}`)); + console.warn(c.yellow(`⚠️ ${message}`)); } export function logError(message: string) { - console.error(chalk.red(`✘ ${message}`)); + console.error(c.red(`✘ ${message}`)); } export function log(message: any) { @@ -51,8 +51,8 @@ export const PREDEFINED_LOG_MESSAGES = { action: "Starting Prisma Studio...\n", success: `Prisma Studio started.` + - chalk.white( - `\nAfter clicking ${chalk.bold("Get Started")} in Nuxt DevTools, click on the ${chalk.bold("three dots (︙)")} in the lower left-hand side to reveal additional tabs.\nLocate the Prisma logo to open Prisma Studio.`, + c.white( + `\nAfter clicking ${c.bold("Get Started")} in Nuxt DevTools, click on the ${c.bold("three dots (︙)")} in the lower left-hand side to reveal additional tabs.\nLocate the Prisma logo to open Prisma Studio.`, ), error: "Failed to start Prisma Studio.", }, @@ -61,15 +61,15 @@ export const PREDEFINED_LOG_MESSAGES = { "Skipping the creation of a lib/prisma.ts file that would hold a global instance of the Prisma Client because the prisma.ts file already exists in the lib folder.", success: "Global instance of Prisma Client created in lib/prisma.ts.", }, - PRISMA_SETUP_SKIPPED_WARNING: chalk.yellow( - `${chalk.bold("Warning")}: Nuxt Prisma Module setup skipped.\nThis may cause unexpected behavior.`, + PRISMA_SETUP_SKIPPED_WARNING: c.yellow( + `${c.bold("Warning")}: Nuxt Prisma Module setup skipped.\nThis may cause unexpected behavior.`, ), skipMigrations: `\nNot migrating the database.`, skipInstallingPrismaStudio: "Skipped installing Prisma Studio.", suggestions: { migrate: - chalk.yellow(chalk.bold("\nHint: ")) + - `You can manually run migrations by executing ${chalk.cyan.bold("npx prisma migrate dev")} or visit the ${chalk.blue.bold("Prisma Migrate")} docs for more info:\n${chalk.underline.blue("https://pris.ly/nuxt/migrate")}. ` + - `Or if you have pre-existing data on your database, you have to introspect it. Learn more in our docs:\n${chalk.underline.blue("https://pris.ly/nuxt/dbpull")}.\n`, + c.yellow(c.bold("\nHint: ")) + + `You can manually run migrations by executing ${c.cyan(c.bold("npx prisma migrate dev"))} or visit the ${c.blue(c.bold("Prisma Migrate"))} docs for more info:\n${c.underline(c.blue("https://pris.ly/nuxt/migrate"))}. ` + + `Or if you have pre-existing data on your database, you have to introspect it. Learn more in our docs:\n${c.underline(c.blue("https://pris.ly/nuxt/dbpull"))}.\n`, }, }; From 7f5df9cd9c22dbf5a1d16e572e84e889d97f78de Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 00:42:31 +0100 Subject: [PATCH 06/13] refactor(package-utils): replace execa with tinyexec for command execution --- package.json | 4 +-- src/package-utils/setup-helpers.ts | 52 +++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index 22ddf3a..ba350b9 100644 --- a/package.json +++ b/package.json @@ -41,9 +41,9 @@ "@nuxt/kit": "^3.11.2", "@prisma/client": "^6.1.0", "defu": "^6.1.4", - "execa": "^8.0.1", "pathe": "^1.1.2", - "prompts": "^2.4.2" + "prompts": "^2.4.2", + "tinyexec": "^0.3.2" }, "devDependencies": { "@commitlint/cli": "^19.5.0", diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index 3c78415..a9e6ed6 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -1,4 +1,4 @@ -import { execa } from "execa"; +import { x } from 'tinyexec' import { log, logError, @@ -85,9 +85,15 @@ export async function initPrisma({ try { log(PREDEFINED_LOG_MESSAGES.initPrisma.action); - const { stdout: initializePrisma } = await execa("prisma", commandArgs, { - cwd: directory, - }); + const { stdout: initializePrisma } = await x( + "prisma", + commandArgs, + { + nodeOptions: { + cwd: directory + } + } + ); log(initializePrisma?.split("Next steps")?.[0]); @@ -159,12 +165,14 @@ export async function runMigration(directory: string, schemaPath: string[]) { try { log(PREDEFINED_LOG_MESSAGES.runMigration.action); - await execa( + await x( "prisma", ["migrate", "dev", "--name", "init"].concat(schemaPath), { - cwd: directory, - }, + nodeOptions: { + cwd: directory + } + } ); logSuccess(PREDEFINED_LOG_MESSAGES.runMigration.success); return true; @@ -179,9 +187,15 @@ export async function runMigration(directory: string, schemaPath: string[]) { export async function formatSchema(directory: string, schemaPath: string[]) { try { log(PREDEFINED_LOG_MESSAGES.formatSchema.action); - await execa("prisma", ["format"].concat(schemaPath), { - cwd: directory, - }); + await x( + "prisma", + ["format"].concat(schemaPath), + { + nodeOptions: { + cwd: directory + } + } + ); } catch { logError(PREDEFINED_LOG_MESSAGES.formatSchema.error); } @@ -195,10 +209,14 @@ export async function generatePrismaClient( log(PREDEFINED_LOG_MESSAGES.generatePrismaClient.action); try { - const { stdout: generateClient } = await execa( + const { stdout: generateClient } = await x( "prisma", ["generate"].concat(prismaSchemaPath), - { cwd: directory }, + { + nodeOptions: { + cwd: directory + } + } ); log("\n" + generateClient.split("\n").slice(0, 4).join("\n") + "\n"); @@ -217,15 +235,17 @@ export async function startPrismaStudio( try { log(PREDEFINED_LOG_MESSAGES.startPrismaStudio.action); - const subprocess = execa( + const subprocess = x( "prisma", ["studio", "--browser", "none"].concat(schemaLocation), { - cwd: directory, - }, + nodeOptions: { + cwd: directory + } + } ); - subprocess.unref(); + subprocess.process.unref(); logSuccess(PREDEFINED_LOG_MESSAGES.startPrismaStudio.success); From ba424eaa1a06e77fb7b3f5725a0c6de55f26080d Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 02:12:20 +0100 Subject: [PATCH 07/13] refactor(prompts): replace prompts package with consola --- package.json | 2 +- src/package-utils/prompts.ts | 65 +++++++++++++++--------------------- 2 files changed, 27 insertions(+), 40 deletions(-) diff --git a/package.json b/package.json index ba350b9..39b1927 100644 --- a/package.json +++ b/package.json @@ -40,9 +40,9 @@ "@nuxt/devtools-kit": "^1.3.3", "@nuxt/kit": "^3.11.2", "@prisma/client": "^6.1.0", + "consola": "^3.3.3", "defu": "^6.1.4", "pathe": "^1.1.2", - "prompts": "^2.4.2", "tinyexec": "^0.3.2" }, "devDependencies": { diff --git a/src/package-utils/prompts.ts b/src/package-utils/prompts.ts index efc4483..c08b741 100644 --- a/src/package-utils/prompts.ts +++ b/src/package-utils/prompts.ts @@ -1,68 +1,55 @@ -import prompts, { type PromptObject, type Answers } from "prompts"; +import { consola, PromptOptions } from "consola"; -export type RequiredPromptTypes = { +type RequiredPromptTypes = { promptForMigrate?: boolean; - promptForPrismaStudio?: boolean; }; enum RequiredPromptNames { - PROMPT_MIGRATE = "promptForPrismaMigrate", - PROMPT_STUDIO = "promptForInstallingStudio", + PROMPT_MIGRATE = "promptForPrismaMigrate" } -export type RequiredPromptAnswers = { +type RequiredPromptAnswers = { [RequiredPromptNames.PROMPT_MIGRATE]: boolean; - [RequiredPromptNames.PROMPT_STUDIO]: boolean; }; +interface CustomPromptOptions { + message: string; + options: PromptOptions; + key: RequiredPromptNames; +} + export async function executeRequiredPrompts({ - promptForMigrate = true, - promptForPrismaStudio = true, + promptForMigrate = true }: RequiredPromptTypes): Promise { - const options: PromptObject[] = []; + const options: CustomPromptOptions[] = []; - // Add migration prompt if required if (promptForMigrate) { options.push({ - type: "confirm", - name: RequiredPromptNames.PROMPT_MIGRATE, message: "Do you want to migrate database changes to your database?", - initial: true, + options: { + type: "confirm", + initial: true + }, + key: RequiredPromptNames.PROMPT_MIGRATE }); } - // Add Prisma Studio prompt if required - if (promptForPrismaStudio) { - options.push({ - type: "confirm", - name: RequiredPromptNames.PROMPT_STUDIO, - message: - "Do you want to view and edit your data by installing Prisma Studio in Nuxt DevTools?", - initial: true, - }); - } - - // If no prompts are required, return null if (options.length === 0) { return null; } try { - // Execute the prompts and await the responses - const answers: Answers = await prompts(options); - - // Construct the result object with explicit type checking - const result: RequiredPromptAnswers = { - [RequiredPromptNames.PROMPT_MIGRATE]: - answers[RequiredPromptNames.PROMPT_MIGRATE] ?? false, - [RequiredPromptNames.PROMPT_STUDIO]: - answers[RequiredPromptNames.PROMPT_STUDIO] ?? false, + const answers: RequiredPromptAnswers = { + [RequiredPromptNames.PROMPT_MIGRATE]: false }; - return result; + for (const { message, options: promptOptions, key } of options) { + answers[key] = (await consola.prompt(message, promptOptions)) as boolean; // Explicitly cast the response to a boolean since it's only boolean prompts for now + } + + return answers; } catch (error) { - // Log any errors encountered during the prompt execution - console.error("Error during prompts execution:", error); + consola.error("Error during prompts execution:", error); return null; } -} +} \ No newline at end of file From d999a9c33662f2d2d9d82bc67bde67950e27a28d Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 02:12:41 +0100 Subject: [PATCH 08/13] refactor(logging): replace log functions with consola --- src/module.ts | 12 ++--- src/package-utils/log-helpers.ts | 41 ++++------------ src/package-utils/setup-helpers.ts | 76 +++++++++++++++--------------- 3 files changed, 53 insertions(+), 76 deletions(-) diff --git a/src/module.ts b/src/module.ts index 39c0262..5199ac9 100644 --- a/src/module.ts +++ b/src/module.ts @@ -21,9 +21,10 @@ import { writeToSchema, generatePrismaClient, } from "./package-utils/setup-helpers"; -import { log, PREDEFINED_LOG_MESSAGES } from "./package-utils/log-helpers"; +import { PREDEFINED_LOG_MESSAGES } from "./package-utils/log-helpers"; import type { Prisma } from "@prisma/client"; import { executeRequiredPrompts } from "./package-utils/prompts"; +import consola from "consola"; // Module configuration interface interface ModuleOptions extends Prisma.PrismaClientOptions { @@ -119,7 +120,7 @@ export default defineNuxtModule({ if (forceSkipPrismaSetup || npmLifecycleEvent === "postinstall") { if (npmLifecycleEvent !== "postinstall") { - log(PREDEFINED_LOG_MESSAGES.PRISMA_SETUP_SKIPPED_WARNING); + consola.warn(PREDEFINED_LOG_MESSAGES.PRISMA_SETUP_SKIPPED_WARNING); } prepareModule(); return; @@ -147,7 +148,7 @@ export default defineNuxtModule({ ); if (migrationFolderExists || !options.runMigration) { - log(PREDEFINED_LOG_MESSAGES.skipMigrations); + consola.info(PREDEFINED_LOG_MESSAGES.skipMigrations); return; } @@ -164,8 +165,7 @@ export default defineNuxtModule({ } const promptResult = await executeRequiredPrompts({ - promptForMigrate: true && !skipAllPrompts, - promptForPrismaStudio: false && !skipAllPrompts, + promptForMigrate: true && !skipAllPrompts }); if (promptResult?.promptForPrismaMigrate && options.runMigration) { @@ -190,7 +190,7 @@ export default defineNuxtModule({ */ const prismaStudioWorkflow = async () => { if (!options.installStudio || npmLifecycleEvent !== "dev") { - log(PREDEFINED_LOG_MESSAGES.skipInstallingPrismaStudio); + consola.info(PREDEFINED_LOG_MESSAGES.skipInstallingPrismaStudio); return; } diff --git a/src/package-utils/log-helpers.ts b/src/package-utils/log-helpers.ts index 19e3e4c..47f0315 100644 --- a/src/package-utils/log-helpers.ts +++ b/src/package-utils/log-helpers.ts @@ -1,20 +1,4 @@ -import c from 'tinyrainbow' - -export function logSuccess(message: string) { - console.log(c.green(`✔ ${message}`)); -} - -export function logWarning(message: string) { - console.warn(c.yellow(`⚠️ ${message}`)); -} - -export function logError(message: string) { - console.error(c.red(`✘ ${message}`)); -} - -export function log(message: any) { - console.log(message); -} +import c from 'tinyrainbow'; export const PREDEFINED_LOG_MESSAGES = { checkIfPrismaSchemaExists: { @@ -34,26 +18,23 @@ export const PREDEFINED_LOG_MESSAGES = { failedToWrite: "Failed to write models to Prisma schema.", }, runMigration: { - action: "Migrating database schema...\n", - success: "Created User and Post tables in the database.", + action: "Migrating database schema...", + success: "Created User and Post tables in the database.\n", error: "Failed to run Prisma migration.", }, formatSchema: { - action: "Formatting Prisma schema...\n", - success: "Successfully formatted Prisma schema.", + action: "Formatting Prisma schema...", + success: "Successfully formatted Prisma schema.\n", error: "Failed to format Prisma schema file.", }, generatePrismaClient: { - action: "Generating Prisma client...\n", + action: "Generating Prisma client...", error: "Failed to generate Prisma Client.\n", }, startPrismaStudio: { - action: "Starting Prisma Studio...\n", - success: - `Prisma Studio started.` + - c.white( - `\nAfter clicking ${c.bold("Get Started")} in Nuxt DevTools, click on the ${c.bold("three dots (︙)")} in the lower left-hand side to reveal additional tabs.\nLocate the Prisma logo to open Prisma Studio.`, - ), + action: "Starting Prisma Studio...", + success: "Prisma Studio started.\n", + info: `After clicking ${c.bold("Get Started")} in Nuxt DevTools, click on the ${c.bold("three dots (︙)")} in the lower left-hand side to reveal additional tabs. Locate the Prisma logo to open Prisma Studio.\n`, error: "Failed to start Prisma Studio.", }, writeClientInLib: { @@ -61,9 +42,7 @@ export const PREDEFINED_LOG_MESSAGES = { "Skipping the creation of a lib/prisma.ts file that would hold a global instance of the Prisma Client because the prisma.ts file already exists in the lib folder.", success: "Global instance of Prisma Client created in lib/prisma.ts.", }, - PRISMA_SETUP_SKIPPED_WARNING: c.yellow( - `${c.bold("Warning")}: Nuxt Prisma Module setup skipped.\nThis may cause unexpected behavior.`, - ), + PRISMA_SETUP_SKIPPED_WARNING: "Nuxt Prisma Module setup skipped.\nThis may cause unexpected behavior.", skipMigrations: `\nNot migrating the database.`, skipInstallingPrismaStudio: "Skipped installing Prisma Studio.", suggestions: { diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index a9e6ed6..d039635 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -1,12 +1,8 @@ import { x } from 'tinyexec' -import { - log, - logError, - logSuccess, - PREDEFINED_LOG_MESSAGES, -} from "./log-helpers"; +import { PREDEFINED_LOG_MESSAGES } from "./log-helpers"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; import { join } from "pathe"; +import consola from 'consola'; export type DatabaseProviderType = | "sqlite" @@ -29,11 +25,11 @@ export function checkIfPrismaSchemaExists(paths: string[]) { }, false); if (exists) { - logSuccess(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.yes); + consola.success(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.yes); return true; } - logError(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.no); + consola.error(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.no); return false; } @@ -47,7 +43,7 @@ function moveEnvFileContent(dirA: string, dirB: string) { try { if (!existsSync(envFileB)) { - console.error(`Source .env file does not exist in directory: ${dirB}`); + consola.error(`Source .env file does not exist in directory: ${dirB}`); return; } @@ -61,9 +57,9 @@ function moveEnvFileContent(dirA: string, dirB: string) { writeFileSync(envFileA, envContentB, "utf8"); } - console.log(`Successfully moved content from ${envFileB} to ${envFileA}`); + consola.success(`Successfully moved content from ${envFileB} to ${envFileA}`); } catch (error) { - console.error(`Failed to move .env file content: ${error}`); + consola.error(`Failed to move .env file content: ${error}`); } } @@ -83,7 +79,7 @@ export async function initPrisma({ } try { - log(PREDEFINED_LOG_MESSAGES.initPrisma.action); + consola.info(PREDEFINED_LOG_MESSAGES.initPrisma.action); const { stdout: initializePrisma } = await x( "prisma", @@ -95,18 +91,17 @@ export async function initPrisma({ } ); - log(initializePrisma?.split("Next steps")?.[0]); + consola.info(initializePrisma?.split("Next steps")?.[0]); try { moveEnvFileContent(directory, rootDir); } catch (error) { - console.log(); + consola.error(error); } return true; } catch (err) { - logError(PREDEFINED_LOG_MESSAGES.initPrisma.error); - log(err); + consola.error(PREDEFINED_LOG_MESSAGES.initPrisma.error, err); return false; } @@ -114,11 +109,11 @@ export async function initPrisma({ export function checkIfMigrationsFolderExists(path: string) { if (existsSync(path)) { - logSuccess(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.success); + consola.success(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.success); return true; } - logError(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.error); + consola.error(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.error); return false; } @@ -129,7 +124,7 @@ export async function writeToSchema(prismaSchemaPath: string) { try { existingSchema = readFileSync(prismaSchemaPath, "utf-8"); } catch { - logError(PREDEFINED_LOG_MESSAGES.writeToSchema.errorReadingFile); + consola.error(PREDEFINED_LOG_MESSAGES.writeToSchema.errorReadingFile); return false; } @@ -157,13 +152,13 @@ model Post { const updatedSchema = `${existingSchema.trim()}\n\n${addModel}`; writeFileSync(prismaSchemaPath, updatedSchema); } catch { - logError(PREDEFINED_LOG_MESSAGES.writeToSchema.failedToWrite); + consola.error(PREDEFINED_LOG_MESSAGES.writeToSchema.failedToWrite); } } export async function runMigration(directory: string, schemaPath: string[]) { try { - log(PREDEFINED_LOG_MESSAGES.runMigration.action); + consola.info(PREDEFINED_LOG_MESSAGES.runMigration.action); await x( "prisma", @@ -174,19 +169,17 @@ export async function runMigration(directory: string, schemaPath: string[]) { } } ); - logSuccess(PREDEFINED_LOG_MESSAGES.runMigration.success); + consola.success(PREDEFINED_LOG_MESSAGES.runMigration.success); return true; } catch (err) { - logError(PREDEFINED_LOG_MESSAGES.runMigration.error); - log(err); - log(PREDEFINED_LOG_MESSAGES.suggestions.migrate); + consola.error(PREDEFINED_LOG_MESSAGES.runMigration.error, err) return false; } } export async function formatSchema(directory: string, schemaPath: string[]) { try { - log(PREDEFINED_LOG_MESSAGES.formatSchema.action); + consola.info(PREDEFINED_LOG_MESSAGES.formatSchema.action); await x( "prisma", ["format"].concat(schemaPath), @@ -196,8 +189,9 @@ export async function formatSchema(directory: string, schemaPath: string[]) { } } ); + consola.success(PREDEFINED_LOG_MESSAGES.formatSchema.success); } catch { - logError(PREDEFINED_LOG_MESSAGES.formatSchema.error); + consola.error(PREDEFINED_LOG_MESSAGES.formatSchema.error); } } @@ -206,7 +200,7 @@ export async function generatePrismaClient( prismaSchemaPath: string[], verboseLog: boolean = false, ) { - log(PREDEFINED_LOG_MESSAGES.generatePrismaClient.action); + consola.info(PREDEFINED_LOG_MESSAGES.generatePrismaClient.action); try { const { stdout: generateClient } = await x( @@ -219,11 +213,15 @@ export async function generatePrismaClient( } ); - log("\n" + generateClient.split("\n").slice(0, 4).join("\n") + "\n"); + generateClient?.split("\n\n").forEach((part, index) => { + if (index < 2) { + consola.success(index === 1 ? part.replace("✔ ", "") + "\n" : part); + } + }); } catch (err) { - logError(PREDEFINED_LOG_MESSAGES.generatePrismaClient.error); + consola.error(PREDEFINED_LOG_MESSAGES.generatePrismaClient.error); if (verboseLog) { - log(err); + consola.error(err); } } } @@ -233,7 +231,7 @@ export async function startPrismaStudio( schemaLocation: string[], ) { try { - log(PREDEFINED_LOG_MESSAGES.startPrismaStudio.action); + consola.info(PREDEFINED_LOG_MESSAGES.startPrismaStudio.action); const subprocess = x( "prisma", @@ -247,12 +245,12 @@ export async function startPrismaStudio( subprocess.process.unref(); - logSuccess(PREDEFINED_LOG_MESSAGES.startPrismaStudio.success); + consola.success(PREDEFINED_LOG_MESSAGES.startPrismaStudio.success); + consola.info(PREDEFINED_LOG_MESSAGES.startPrismaStudio.info); return true; } catch (err) { - logError(PREDEFINED_LOG_MESSAGES.startPrismaStudio.error); - log(err); + consola.error(PREDEFINED_LOG_MESSAGES.startPrismaStudio.error, err); return false; } } @@ -285,15 +283,15 @@ if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma } if (existsSync(`${path}/lib/prisma.ts`)) { - log(PREDEFINED_LOG_MESSAGES.writeClientInLib.found); + consola.info(PREDEFINED_LOG_MESSAGES.writeClientInLib.found); return; } writeFileSync(`${path}/lib/prisma.ts`, prismaClient); - logSuccess(PREDEFINED_LOG_MESSAGES.writeClientInLib.success); + consola.success(PREDEFINED_LOG_MESSAGES.writeClientInLib.success); } - } catch (e: any) { - log(e); + } catch (err) { + consola.error(err); } } From 640caa4bd6d9d925415c7b0d297a783be9d0098a Mon Sep 17 00:00:00 2001 From: Nils Gerersdorfer Date: Tue, 31 Dec 2024 02:54:09 +0100 Subject: [PATCH 09/13] refactor(logs): change error logs to warn --- src/package-utils/setup-helpers.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index d039635..441d24d 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -29,7 +29,7 @@ export function checkIfPrismaSchemaExists(paths: string[]) { return true; } - consola.error(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.no); + consola.warn(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.no); return false; } @@ -43,7 +43,7 @@ function moveEnvFileContent(dirA: string, dirB: string) { try { if (!existsSync(envFileB)) { - consola.error(`Source .env file does not exist in directory: ${dirB}`); + consola.warn(`Source .env file does not exist in directory: ${dirB}`); return; } @@ -113,7 +113,7 @@ export function checkIfMigrationsFolderExists(path: string) { return true; } - consola.error(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.error); + consola.warn(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.error); return false; } From 39cec3835fe9bc0bce25b6cd94154b3a652758bd Mon Sep 17 00:00:00 2001 From: Connor van Spronssen Date: Tue, 31 Dec 2024 11:09:41 +0100 Subject: [PATCH 10/13] feat(installation): update package-lock.json --- package-lock.json | 50 ++++++++++++++++++++--------------------------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8a91f98..7b20f33 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,12 +12,10 @@ "@nuxt/devtools-kit": "^1.3.3", "@nuxt/kit": "^3.11.2", "@prisma/client": "^6.1.0", - "chalk": "^5.3.0", + "consola": "^3.3.3", "defu": "^6.1.4", - "execa": "^8.0.1", - "nypm": "^0.4.1", "pathe": "^1.1.2", - "prompts": "^2.4.2" + "tinyexec": "^0.3.2" }, "devDependencies": { "@commitlint/cli": "^19.5.0", @@ -40,6 +38,7 @@ "prettier": "3.2.5", "prisma": "^6.1.0", "semantic-release": "^24.2.0", + "tinyrainbow": "^1.2.0", "vitest": "^1.2.2" } }, @@ -7756,9 +7755,10 @@ "license": "ISC" }, "node_modules/consola": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/consola/-/consola-3.2.3.tgz", - "integrity": "sha512-I5qxpzLv+sJhTVEoLYNcTW+bThDCPsit0vLNKShZx6rLtpilNpmmeTPaeqJb9ZE9dV3DGaeby6Vuhrw38WjeyQ==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.3.3.tgz", + "integrity": "sha512-Qil5KwghMzlqd51UXM0b6fyaGHtOC22scxrwrz4A2882LyUMwQjnvaedN1HAeXzphspQ6CpHkzMAWxBTUruDLg==", + "license": "MIT", "engines": { "node": "^14.18.0 || >=16.10.0" } @@ -16710,25 +16710,6 @@ "node": "^14.16.0 || >=16.10.0" } }, - "node_modules/nypm": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.4.1.tgz", - "integrity": "sha512-1b9mihliBh8UCcKtcGRu//G50iHpjxIQVUqkdhPT/SDVE7KdJKoHXLS0heuYTQCx95dFqiyUbXZB9r8ikn+93g==", - "dependencies": { - "citty": "^0.1.6", - "consola": "^3.2.3", - "pathe": "^1.1.2", - "pkg-types": "^1.2.1", - "tinyexec": "^0.3.1", - "ufo": "^1.5.4" - }, - "bin": { - "nypm": "dist/cli.mjs" - }, - "engines": { - "node": "^14.16.0 || >=16.10.0" - } - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -20446,9 +20427,10 @@ "dev": true }, "node_modules/tinyexec": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.1.tgz", - "integrity": "sha512-WiCJLEECkO18gwqIp6+hJg0//p23HXp4S+gGtAKu3mI2F2/sXC4FvHvXvB0zJVVaTPhx1/tOwdbRsa1sOBIKqQ==" + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "license": "MIT" }, "node_modules/tinypool": { "version": "0.8.4", @@ -20459,6 +20441,16 @@ "node": ">=14.0.0" } }, + "node_modules/tinyrainbow": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz", + "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/tinyspy": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-2.2.1.tgz", From 5f78ffe982df1a4a7e408c91d1dbc7a0f42faa3f Mon Sep 17 00:00:00 2001 From: Connor van Spronssen Date: Tue, 31 Dec 2024 11:16:14 +0100 Subject: [PATCH 11/13] fix(installation): move tinyrainbow to dependencies, to resolve a build warning --- package-lock.json | 5 ++--- package.json | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7b20f33..607510c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,7 +15,8 @@ "consola": "^3.3.3", "defu": "^6.1.4", "pathe": "^1.1.2", - "tinyexec": "^0.3.2" + "tinyexec": "^0.3.2", + "tinyrainbow": "^1.2.0" }, "devDependencies": { "@commitlint/cli": "^19.5.0", @@ -38,7 +39,6 @@ "prettier": "3.2.5", "prisma": "^6.1.0", "semantic-release": "^24.2.0", - "tinyrainbow": "^1.2.0", "vitest": "^1.2.2" } }, @@ -20445,7 +20445,6 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz", "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=14.0.0" diff --git a/package.json b/package.json index 39b1927..90b4a37 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,8 @@ "consola": "^3.3.3", "defu": "^6.1.4", "pathe": "^1.1.2", - "tinyexec": "^0.3.2" + "tinyexec": "^0.3.2", + "tinyrainbow": "^1.2.0" }, "devDependencies": { "@commitlint/cli": "^19.5.0", @@ -66,7 +67,6 @@ "prettier": "3.2.5", "prisma": "^6.1.0", "semantic-release": "^24.2.0", - "tinyrainbow": "^1.2.0", "vitest": "^1.2.2" }, "config": { From 995e5a1000040b744ebfc141e8d7e0dae98b7f4e Mon Sep 17 00:00:00 2001 From: Connor van Spronssen Date: Tue, 31 Dec 2024 12:32:01 +0100 Subject: [PATCH 12/13] refactor(logs): change up the logic for logging, to allow for a more concise control flow --- src/package-utils/log-helpers.ts | 17 +-- src/package-utils/setup-helpers.ts | 178 +++++++++++++++-------------- 2 files changed, 100 insertions(+), 95 deletions(-) diff --git a/src/package-utils/log-helpers.ts b/src/package-utils/log-helpers.ts index 47f0315..57fb48f 100644 --- a/src/package-utils/log-helpers.ts +++ b/src/package-utils/log-helpers.ts @@ -1,4 +1,4 @@ -import c from 'tinyrainbow'; +import c from "tinyrainbow"; export const PREDEFINED_LOG_MESSAGES = { checkIfPrismaSchemaExists: { @@ -6,7 +6,8 @@ export const PREDEFINED_LOG_MESSAGES = { no: "Prisma schema file does not exist.", }, initPrisma: { - action: "Initializing Prisma project...\n", + action: "Initializing Prisma project...", + success: "Initialized the Prisma project.", error: "Failed to initialize Prisma project.", }, checkIfMigrationsFolderExists: { @@ -19,21 +20,22 @@ export const PREDEFINED_LOG_MESSAGES = { }, runMigration: { action: "Migrating database schema...", - success: "Created User and Post tables in the database.\n", + success: "Created User and Post tables in the database.", error: "Failed to run Prisma migration.", }, formatSchema: { action: "Formatting Prisma schema...", - success: "Successfully formatted Prisma schema.\n", + success: "Successfully formatted Prisma schema.", error: "Failed to format Prisma schema file.", }, generatePrismaClient: { action: "Generating Prisma client...", - error: "Failed to generate Prisma Client.\n", + success: "Successfully generated Prisma client.", + error: "Failed to generate Prisma Client.", }, startPrismaStudio: { action: "Starting Prisma Studio...", - success: "Prisma Studio started.\n", + success: "Prisma Studio started.", info: `After clicking ${c.bold("Get Started")} in Nuxt DevTools, click on the ${c.bold("three dots (︙)")} in the lower left-hand side to reveal additional tabs. Locate the Prisma logo to open Prisma Studio.\n`, error: "Failed to start Prisma Studio.", }, @@ -42,7 +44,8 @@ export const PREDEFINED_LOG_MESSAGES = { "Skipping the creation of a lib/prisma.ts file that would hold a global instance of the Prisma Client because the prisma.ts file already exists in the lib folder.", success: "Global instance of Prisma Client created in lib/prisma.ts.", }, - PRISMA_SETUP_SKIPPED_WARNING: "Nuxt Prisma Module setup skipped.\nThis may cause unexpected behavior.", + PRISMA_SETUP_SKIPPED_WARNING: + "Nuxt Prisma Module setup skipped.\nThis may cause unexpected behavior.", skipMigrations: `\nNot migrating the database.`, skipInstallingPrismaStudio: "Skipped installing Prisma Studio.", suggestions: { diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index 441d24d..ea9c446 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -1,8 +1,8 @@ -import { x } from 'tinyexec' +import { x } from "tinyexec"; import { PREDEFINED_LOG_MESSAGES } from "./log-helpers"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; import { join } from "pathe"; -import consola from 'consola'; +import consola from "consola"; export type DatabaseProviderType = | "sqlite" @@ -29,7 +29,7 @@ export function checkIfPrismaSchemaExists(paths: string[]) { return true; } - consola.warn(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.no); + consola.info(PREDEFINED_LOG_MESSAGES.checkIfPrismaSchemaExists.no); return false; } @@ -57,7 +57,9 @@ function moveEnvFileContent(dirA: string, dirB: string) { writeFileSync(envFileA, envContentB, "utf8"); } - consola.success(`Successfully moved content from ${envFileB} to ${envFileA}`); + consola.success( + `Successfully moved content from ${envFileB} to ${envFileA}`, + ); } catch (error) { consola.error(`Failed to move .env file content: ${error}`); } @@ -69,7 +71,7 @@ export async function initPrisma({ provider = "sqlite", datasourceUrl, }: PrismaInitOptions) { - const commandArgs = ["init", "--datasource-provider"]; + const commandArgs = ["prisma", "init", "--datasource-provider"]; commandArgs.push(provider); @@ -78,42 +80,39 @@ export async function initPrisma({ commandArgs.push(datasourceUrl); } - try { - consola.info(PREDEFINED_LOG_MESSAGES.initPrisma.action); - - const { stdout: initializePrisma } = await x( - "prisma", - commandArgs, - { - nodeOptions: { - cwd: directory - } - } - ); + consola.info(PREDEFINED_LOG_MESSAGES.initPrisma.action); - consola.info(initializePrisma?.split("Next steps")?.[0]); + const { stderr, exitCode } = await x("npx", commandArgs, { + nodeOptions: { + cwd: directory, + }, + }); - try { - moveEnvFileContent(directory, rootDir); - } catch (error) { - consola.error(error); - } + if (exitCode !== 0) { + consola.error(PREDEFINED_LOG_MESSAGES.initPrisma.error, stderr); + return false; + } - return true; - } catch (err) { - consola.error(PREDEFINED_LOG_MESSAGES.initPrisma.error, err); + consola.success(PREDEFINED_LOG_MESSAGES.initPrisma.success); - return false; + try { + moveEnvFileContent(directory, rootDir); + } catch (error) { + consola.error(error); } + + return true; } export function checkIfMigrationsFolderExists(path: string) { if (existsSync(path)) { - consola.success(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.success); + consola.success( + PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.success, + ); return true; } - consola.warn(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.error); + consola.info(PREDEFINED_LOG_MESSAGES.checkIfMigrationsFolderExists.error); return false; } @@ -157,42 +156,46 @@ model Post { } export async function runMigration(directory: string, schemaPath: string[]) { - try { - consola.info(PREDEFINED_LOG_MESSAGES.runMigration.action); - - await x( - "prisma", - ["migrate", "dev", "--name", "init"].concat(schemaPath), - { - nodeOptions: { - cwd: directory - } - } - ); - consola.success(PREDEFINED_LOG_MESSAGES.runMigration.success); - return true; - } catch (err) { - consola.error(PREDEFINED_LOG_MESSAGES.runMigration.error, err) + consola.info(PREDEFINED_LOG_MESSAGES.runMigration.action); + + const { stderr, exitCode } = await x( + "npx", + ["prisma", "migrate", "dev", "--name", "init"].concat(schemaPath), + { + nodeOptions: { + cwd: directory, + }, + }, + ); + + if (exitCode !== 0) { + consola.error(PREDEFINED_LOG_MESSAGES.runMigration.error, stderr); return false; } + + consola.success(PREDEFINED_LOG_MESSAGES.runMigration.success); + return true; } export async function formatSchema(directory: string, schemaPath: string[]) { - try { - consola.info(PREDEFINED_LOG_MESSAGES.formatSchema.action); - await x( - "prisma", - ["format"].concat(schemaPath), - { - nodeOptions: { - cwd: directory - } - } - ); - consola.success(PREDEFINED_LOG_MESSAGES.formatSchema.success); - } catch { - consola.error(PREDEFINED_LOG_MESSAGES.formatSchema.error); + consola.info(PREDEFINED_LOG_MESSAGES.formatSchema.action); + + const { stderr, exitCode } = await x( + "npx", + ["prisma", "format"].concat(schemaPath), + { + nodeOptions: { + cwd: directory, + }, + }, + ); + + if (exitCode !== 0) { + consola.error(PREDEFINED_LOG_MESSAGES.formatSchema.error, stderr); + return; } + + consola.success(PREDEFINED_LOG_MESSAGES.formatSchema.success); } export async function generatePrismaClient( @@ -202,56 +205,55 @@ export async function generatePrismaClient( ) { consola.info(PREDEFINED_LOG_MESSAGES.generatePrismaClient.action); - try { - const { stdout: generateClient } = await x( - "prisma", - ["generate"].concat(prismaSchemaPath), - { - nodeOptions: { - cwd: directory - } - } - ); - - generateClient?.split("\n\n").forEach((part, index) => { - if (index < 2) { - consola.success(index === 1 ? part.replace("✔ ", "") + "\n" : part); - } - }); - } catch (err) { + const { stderr, exitCode } = await x( + "npx", + ["prisma", "generate"].concat(prismaSchemaPath), + { + nodeOptions: { + cwd: directory, + }, + }, + ); + + if (exitCode !== 0) { consola.error(PREDEFINED_LOG_MESSAGES.generatePrismaClient.error); + if (verboseLog) { - consola.error(err); + consola.error(stderr); } + + return; } + + consola.success(PREDEFINED_LOG_MESSAGES.generatePrismaClient.success); } export async function startPrismaStudio( directory: string, schemaLocation: string[], ) { - try { - consola.info(PREDEFINED_LOG_MESSAGES.startPrismaStudio.action); + consola.info(PREDEFINED_LOG_MESSAGES.startPrismaStudio.action); - const subprocess = x( - "prisma", - ["studio", "--browser", "none"].concat(schemaLocation), + try { + const proc = x( + "npx", + ["prisma", "studio", "--browser", "none"].concat(schemaLocation), { nodeOptions: { - cwd: directory - } - } + cwd: directory, + }, + throwOnError: true, + }, ); - subprocess.process.unref(); + proc.process?.unref(); consola.success(PREDEFINED_LOG_MESSAGES.startPrismaStudio.success); consola.info(PREDEFINED_LOG_MESSAGES.startPrismaStudio.info); return true; } catch (err) { - consola.error(PREDEFINED_LOG_MESSAGES.startPrismaStudio.error, err); - return false; + consola.error(PREDEFINED_LOG_MESSAGES.startPrismaStudio.error); } } From 902089d9747561d156e1ef42d3afc3fb68b68dec Mon Sep 17 00:00:00 2001 From: Connor van Spronssen Date: Wed, 1 Jan 2025 16:06:38 +0100 Subject: [PATCH 13/13] fix(installation): resolve an issue where moving the .env file could throw an error with Nuxt Layers --- src/package-utils/setup-helpers.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/package-utils/setup-helpers.ts b/src/package-utils/setup-helpers.ts index ea9c446..7ab4fb9 100644 --- a/src/package-utils/setup-helpers.ts +++ b/src/package-utils/setup-helpers.ts @@ -51,6 +51,11 @@ function moveEnvFileContent(dirA: string, dirB: string) { if (existsSync(envFileA)) { const envContentA = readFileSync(envFileA, "utf8"); + + if (envContentA.match(/^DATABASE_URL=.+$/gm)) { + return; + } + const combinedContent = `${envContentA}\n${envContentB}`; writeFileSync(envFileA, combinedContent, "utf8"); } else { @@ -96,7 +101,7 @@ export async function initPrisma({ consola.success(PREDEFINED_LOG_MESSAGES.initPrisma.success); try { - moveEnvFileContent(directory, rootDir); + moveEnvFileContent(rootDir, directory); } catch (error) { consola.error(error); }