create-graphql-markdown-docs 0.1.0 → 1.0.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.
@@ -0,0 +1,83 @@
1
+ import fs from "node:fs";
2
+
3
+ import * as prompts from "@clack/prompts";
4
+ import {
5
+ detect as detectPackageManager,
6
+ getUserAgent,
7
+ } from "package-manager-detector";
8
+
9
+ import { isRemoteSchemaSource } from "./schema.mjs";
10
+ import { INSTALL_COMMANDS } from "./tasks.mjs";
11
+
12
+ export const DOCS_URL = "https://graphql-markdown.dev";
13
+
14
+ /** Thrown to abort the run with an exit code; the message was already logged. */
15
+ export class CliExit extends Error {
16
+ constructor(code = 1) {
17
+ super("cli-exit");
18
+ this.code = code;
19
+ }
20
+ }
21
+
22
+ /** Abort the run when a prompt was cancelled; otherwise return its value. */
23
+ export function unlessCancelled(value) {
24
+ if (prompts.isCancel(value)) {
25
+ prompts.cancel("Setup cancelled.");
26
+ throw new CliExit(1);
27
+ }
28
+ return value;
29
+ }
30
+
31
+ /** Lists failed steps ahead of the next steps; empty when nothing failed. */
32
+ export function failureNote(outcomes) {
33
+ const failures = outcomes
34
+ .filter(({ status }) => status === "failed")
35
+ .map(({ step, error }) => ` - ${step.title}: ${error.message}`);
36
+ return failures.length > 0
37
+ ? `Some steps did not complete:\n${failures.join("\n")}\n\n`
38
+ : "";
39
+ }
40
+
41
+ /** Log an error and abort the run. */
42
+ export function fail(message) {
43
+ prompts.log.error(message);
44
+ throw new CliExit(1);
45
+ }
46
+
47
+ /** Prompt validator for a schema source (path, URL or git ref). */
48
+ export function validateSchemaSource(value) {
49
+ const source = value?.trim();
50
+ if (!source) return "Schema source is required";
51
+ if (isRemoteSchemaSource(source)) return undefined;
52
+ if (!fs.existsSync(source)) {
53
+ return `Schema file not found: ${source}`;
54
+ }
55
+ if (fs.statSync(source).isDirectory()) {
56
+ return `${source} is a directory — provide a schema file, URL or git ref.`;
57
+ }
58
+ return undefined;
59
+ }
60
+
61
+ /** Package manager from --pm, the launching agent, or the lockfiles in `cwd`. */
62
+ export async function resolvePackageManager(args, cwd = process.cwd()) {
63
+ if (args.pm) return args.pm;
64
+ // Set when launched via `<pm> create`, so it reflects what the user ran.
65
+ const agent = getUserAgent()?.split("/")[0];
66
+ if (agent && Object.hasOwn(INSTALL_COMMANDS, agent)) return agent;
67
+ const detected = await detectPackageManager({ cwd });
68
+ if (detected?.name && Object.hasOwn(INSTALL_COMMANDS, detected.name)) {
69
+ return detected.name;
70
+ }
71
+ if (args.yes) return "npm";
72
+ return unlessCancelled(
73
+ await prompts.select({
74
+ message: "Which package manager would you like to use?",
75
+ options: [
76
+ { value: "npm", label: "npm" },
77
+ { value: "pnpm", label: "pnpm" },
78
+ { value: "yarn", label: "yarn" },
79
+ { value: "bun", label: "bun" },
80
+ ],
81
+ }),
82
+ );
83
+ }
@@ -0,0 +1,136 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ import { FRAMEWORKS } from "./frameworks/index.mjs";
6
+ import {
7
+ EXAMPLE_SCHEMA_REF,
8
+ detectLoader,
9
+ isRemoteSchemaSource,
10
+ } from "./schema.mjs";
11
+
12
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
+ export const packageRoot = path.resolve(__dirname, "..");
14
+ const templatesRoot = path.resolve(packageRoot, "templates");
15
+
16
+ /** Directory name used when the user gives none (empty prompt or --yes). */
17
+ export const DEFAULT_PROJECT_DIR = "my-graphql-docs";
18
+
19
+ /**
20
+ * Copy a directory recursively, excluding entries whose name matches any pattern.
21
+ */
22
+ export function copyDirRecursive(src, dst, excludePatterns = []) {
23
+ fs.cpSync(src, dst, {
24
+ recursive: true,
25
+ filter: (source) => {
26
+ // The root itself is always copied; patterns apply to entry names.
27
+ if (source === src) return true;
28
+ const name = path.basename(source);
29
+ return !excludePatterns.some((pattern) => pattern.test(name));
30
+ },
31
+ });
32
+ }
33
+
34
+ /**
35
+ * Derive a valid npm package name from a directory path (lowercase, no
36
+ * spaces or special characters, no leading dot/underscore/dash).
37
+ */
38
+ export function toPackageName(dir) {
39
+ let name = path
40
+ .basename(dir)
41
+ .toLowerCase()
42
+ .trim()
43
+ .replace(/[^a-z0-9._~-]+/g, "-")
44
+ .replace(/^[._-]+/, "");
45
+ let end = name.length;
46
+ while (end > 0 && name[end - 1] === "-") end--;
47
+ name = name.slice(0, end);
48
+ return name || DEFAULT_PROJECT_DIR;
49
+ }
50
+
51
+ /**
52
+ * Rewrite package.json to set the project name and add non-default loaders as dependencies.
53
+ */
54
+ export function writePackageJson(tempDir, projectDir, loader) {
55
+ const pkgJsonPath = path.join(tempDir, "package.json");
56
+ let pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
57
+ pkgJson.name = toPackageName(projectDir);
58
+ if (!loader.isDefault) {
59
+ pkgJson.dependencies[loader.package] = loader.version;
60
+ }
61
+ fs.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2) + "\n");
62
+ }
63
+
64
+ /**
65
+ * Copies a local SDL/JSON schema into the scaffold. Remote sources and local
66
+ * code-first schemas are referenced in place (code files may import siblings,
67
+ * so they must not be copied). Drops the bundled example in both cases.
68
+ */
69
+ export function placeSchema(tempDir, projectDir, schemaPath) {
70
+ const templateExamplePath = path.join(tempDir, EXAMPLE_SCHEMA_REF);
71
+ if (!schemaPath) return EXAMPLE_SCHEMA_REF;
72
+
73
+ const isCodeSchema = detectLoader(schemaPath).id === "code";
74
+ if (isRemoteSchemaSource(schemaPath) || isCodeSchema) {
75
+ // Nothing to copy — the bundled example is unused, drop it so it
76
+ // doesn't sit there implying it's still what gets generated.
77
+ fs.rmSync(templateExamplePath, { force: true });
78
+ if (isRemoteSchemaSource(schemaPath)) {
79
+ return schemaPath;
80
+ }
81
+ const relative = path.relative(projectDir, path.resolve(schemaPath));
82
+ // Another drive on Windows yields an absolute path: use it as-is.
83
+ if (path.isAbsolute(relative)) return relative.split(path.sep).join("/");
84
+ const relativePath = relative.split(path.sep).join("/");
85
+ return relativePath.startsWith("../") ? relativePath : `./${relativePath}`;
86
+ }
87
+
88
+ const destName = `schema${path.extname(schemaPath) || ".graphql"}`;
89
+ const destSchema = path.join(tempDir, "schema", destName);
90
+ if (destSchema !== templateExamplePath) {
91
+ fs.rmSync(templateExamplePath, { force: true });
92
+ }
93
+ fs.copyFileSync(schemaPath, destSchema);
94
+ return `./schema/${destName}`;
95
+ }
96
+
97
+ /** Phase 3: copy the template and apply all rewrites. */
98
+ export function applyTemplate(tempDir, ctx) {
99
+ const { framework, projectDir, schemaPath, loader, title, color } = ctx;
100
+ const fw = FRAMEWORKS[framework];
101
+
102
+ copyDirRecursive(path.join(templatesRoot, framework), tempDir, [
103
+ /^node_modules$/,
104
+ ...fw.scaffold.copyExcludes,
105
+ ]);
106
+
107
+ // npm strips `.gitignore` from published tarballs, so templates ship it as
108
+ // `gitignore` and it is renamed back here.
109
+ const gitignore = path.join(tempDir, "gitignore");
110
+ if (fs.existsSync(gitignore)) {
111
+ fs.renameSync(gitignore, path.join(tempDir, ".gitignore"));
112
+ }
113
+
114
+ const schemaRef = placeSchema(tempDir, projectDir, schemaPath);
115
+
116
+ fw.scaffold.apply(tempDir, { schemaRef, schemaPath, loader, title, color });
117
+
118
+ writePackageJson(tempDir, projectDir, loader);
119
+ }
120
+
121
+ export function moveIntoPlace(tempDir, projectDir) {
122
+ if (fs.existsSync(projectDir)) {
123
+ // Existing (empty) target, possibly the cwd: copy into it rather than
124
+ // replacing it, so the directory itself (and its inode) is preserved.
125
+ fs.cpSync(tempDir, projectDir, { recursive: true });
126
+ fs.rmSync(tempDir, { recursive: true, force: true });
127
+ return;
128
+ }
129
+ try {
130
+ fs.renameSync(tempDir, projectDir);
131
+ } catch (err) {
132
+ if (err.code !== "EXDEV") throw err;
133
+ // temp dir is on another filesystem; the caller removes it afterwards
134
+ fs.cpSync(tempDir, projectDir, { recursive: true });
135
+ }
136
+ }
@@ -0,0 +1,61 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import {
5
+ DEFAULT_LOADER,
6
+ EXAMPLE_SCHEMA_REF,
7
+ defaultSchemaLine,
8
+ } from "../schema.mjs";
9
+ import { INDENT_STEP, findIndentedLine } from "./lines.mjs";
10
+
11
+ /**
12
+ * Rewrite a graphql-config template's .graphqlrc `schema` line and loader entry.
13
+ * The template must contain a `schema: './schema/example.graphql'` line and the
14
+ * default loader entry under `extensions.graphql-markdown.loaders`; the new
15
+ * entry reuses that line's indentation.
16
+ */
17
+ export function writeGraphqlrc(tempDir, schemaRef, loader) {
18
+ const graphqlrcPath = path.join(tempDir, ".graphqlrc");
19
+ const originalContent = fs.readFileSync(graphqlrcPath, "utf-8");
20
+
21
+ const defaultLoaderEntry = `${DEFAULT_LOADER.className}: '${DEFAULT_LOADER.package}'`;
22
+
23
+ let updated = originalContent.replace(
24
+ defaultSchemaLine,
25
+ () => `schema: '${schemaRef.replaceAll("'", "''")}'`,
26
+ );
27
+
28
+ if (schemaRef !== EXAMPLE_SCHEMA_REF && updated === originalContent) {
29
+ throw new Error(
30
+ `Expected to find and replace "${defaultSchemaLine}" in ${graphqlrcPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
31
+ );
32
+ }
33
+
34
+ if (!loader.isDefault) {
35
+ // Loader options are rendered as-is; a token env var becomes a `${VAR}`
36
+ // reference (graphql-config interpolates `${VAR}` in .graphqlrc).
37
+ const options = {
38
+ ...loader.options,
39
+ ...(loader.tokenEnvVar && { token: `\${${loader.tokenEnvVar}}` }),
40
+ };
41
+ const found = findIndentedLine(updated, defaultLoaderEntry);
42
+ if (!found) {
43
+ throw new Error(
44
+ `Expected to find and replace "${defaultLoaderEntry}" in ${graphqlrcPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
45
+ );
46
+ }
47
+
48
+ const { line, indent } = found;
49
+ const child = indent + INDENT_STEP;
50
+ const optionLines = Object.entries(options).map(
51
+ ([key, value]) => `\n${child}${INDENT_STEP}${key}: '${value}'`,
52
+ );
53
+ const loaderEntry =
54
+ optionLines.length === 0
55
+ ? `${indent}${loader.className}: '${loader.package}'`
56
+ : `${indent}${loader.className}:\n${child}module: '${loader.package}'\n${child}options:${optionLines.join("")}`;
57
+ updated = updated.replace(line, () => loaderEntry);
58
+ }
59
+
60
+ fs.writeFileSync(graphqlrcPath, updated);
61
+ }
@@ -0,0 +1,18 @@
1
+ /** One nesting level in the templates' YAML and TS files. */
2
+ export const INDENT_STEP = " ";
3
+
4
+ /** Escapes `value` for literal use inside a RegExp. */
5
+ function escapeRegExp(value) {
6
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
7
+ }
8
+
9
+ /**
10
+ * Finds the line whose trimmed content is `content`, so rewrites follow the
11
+ * template's own indentation instead of hardcoding it. Returns the full
12
+ * `line` and its leading `indent`, or `undefined` when no line matches.
13
+ */
14
+ export function findIndentedLine(text, content) {
15
+ const pattern = String.raw`^([ \t]*)${escapeRegExp(content)}$`;
16
+ const match = new RegExp(pattern, "m").exec(text);
17
+ return match ? { line: match[0], indent: match[1] } : undefined;
18
+ }
package/lib/schema.mjs ADDED
@@ -0,0 +1,102 @@
1
+ import fs from "node:fs";
2
+
3
+ import { buildSchema } from "graphql";
4
+
5
+ export const EXAMPLE_SCHEMA_REF = "./schema/example.graphql";
6
+ export const defaultSchemaLine = `schema: '${EXAMPLE_SCHEMA_REF}'`;
7
+
8
+ /**
9
+ * The official graphql-tools loaders (github.com/ardatan/graphql-tools/tree/
10
+ * master/packages/loaders) that make sense as a schema *source* for
11
+ * graphql-markdown — excludes loaders for things that aren't ever a whole
12
+ * schema's source (e.g. `@graphql-tools/apollo-engine-loader` targets a
13
+ * managed-federation registry, out of scope here).
14
+ *
15
+ * `version: 'latest'` deliberately, not a pinned range: a scaffolded project
16
+ * runs `npm install` (or equivalent) immediately, once, right after this
17
+ * file is written — there's no ongoing lockfile for this CLI to keep in sync
18
+ * with graphql-tools' own release cadence, so pinning a version here would
19
+ * just silently go stale the day graphql-tools cuts a release. Same
20
+ * rationale most `create-*` scaffolding CLIs use for freshly-installed deps.
21
+ *
22
+ * `match` runs against the raw schema source string the user provided (a
23
+ * path or a URL) to pick the loader graphql-markdown needs to actually read
24
+ * it; order matters, first match wins.
25
+ */
26
+ const LOADERS = [
27
+ {
28
+ id: "url",
29
+ match: (source) => /^https?:\/\//i.test(source),
30
+ className: "UrlLoader",
31
+ package: "@graphql-tools/url-loader",
32
+ version: "latest",
33
+ // URL sources are introspected with POST.
34
+ options: { method: "POST" },
35
+ },
36
+ {
37
+ id: "github",
38
+ match: (source) => /^github:/i.test(source),
39
+ className: "GithubLoader",
40
+ package: "@graphql-tools/github-loader",
41
+ version: "latest",
42
+ // GithubLoader needs an API token, read from this env var.
43
+ tokenEnvVar: "GITHUB_TOKEN",
44
+ },
45
+ {
46
+ id: "git",
47
+ match: (source) => /^git:/i.test(source),
48
+ className: "GitLoader",
49
+ package: "@graphql-tools/git-loader",
50
+ version: "latest",
51
+ },
52
+ {
53
+ id: "json",
54
+ match: (source) => /\.json$/i.test(source),
55
+ className: "JsonFileLoader",
56
+ package: "@graphql-tools/json-file-loader",
57
+ version: "latest",
58
+ },
59
+ {
60
+ id: "code",
61
+ match: (source) => /\.(js|mjs|cjs|ts|mts|cts)$/i.test(source),
62
+ className: "CodeFileLoader",
63
+ package: "@graphql-tools/code-file-loader",
64
+ version: "latest",
65
+ },
66
+ {
67
+ // Default: a local .graphql/.gql SDL file. This is the loader
68
+ // `createGenerateDocs` already defaults to internally, so scaffolds that
69
+ // land here emit no explicit `loaders` option at all — one less thing
70
+ // for the common case to carry, and no version to track either.
71
+ id: "file",
72
+ match: (source) => /\.(graphql|gql)$/i.test(source),
73
+ className: "GraphQLFileLoader",
74
+ package: "@graphql-tools/graphql-file-loader",
75
+ isDefault: true,
76
+ },
77
+ ];
78
+
79
+ export const DEFAULT_LOADER = LOADERS.find((loader) => loader.isDefault);
80
+
81
+ /** Picks the loader for a schema source string, falling back to the local-file loader. */
82
+ export function detectLoader(schemaSource) {
83
+ return LOADERS.find((loader) => loader.match(schemaSource)) ?? DEFAULT_LOADER;
84
+ }
85
+
86
+ /** A schema "path" that's actually a remote/VCS reference, not a local file to copy. */
87
+ export function isRemoteSchemaSource(source) {
88
+ return /^(https?|git|github):/i.test(source);
89
+ }
90
+
91
+ /**
92
+ * Validate a GraphQL schema file by attempting to parse it with buildSchema.
93
+ */
94
+ export async function validateGraphQLSchema(schemaPath) {
95
+ try {
96
+ const schemaText = await fs.promises.readFile(schemaPath, "utf-8");
97
+ buildSchema(schemaText);
98
+ return true;
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
package/lib/target.mjs ADDED
@@ -0,0 +1,95 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import { WIRE_FRAMEWORKS } from "./frameworks/index.mjs";
5
+ import { isRemoteSchemaSource } from "./schema.mjs";
6
+
7
+ /** Entries that do not make a folder a "project". */
8
+ const IGNORED_ENTRIES = new Set([".git", ".DS_Store", "Thumbs.db"]);
9
+
10
+ /** Flags that only make sense when creating a new project. */
11
+ const SCAFFOLD_ONLY_FLAGS = ["example", "title", "color", "no-git"];
12
+
13
+ /** Flags that only make sense when adding to an existing project. */
14
+ const WIRE_ONLY_FLAGS = [
15
+ "formatter",
16
+ "output",
17
+ "link-root",
18
+ "site-base",
19
+ "script",
20
+ "dry-run",
21
+ ];
22
+
23
+ /**
24
+ * Whether a folder is missing or holds nothing but ignorable entries.
25
+ * @param {string} dir
26
+ * @returns {boolean}
27
+ */
28
+ export function isEffectivelyEmpty(dir) {
29
+ if (!fs.existsSync(dir)) return true;
30
+ return fs.readdirSync(dir).every((entry) => IGNORED_ENTRIES.has(entry));
31
+ }
32
+
33
+ /**
34
+ * Mode implied by the target folder.
35
+ * @param {string} dir
36
+ * @returns {"scaffold" | "wire"}
37
+ */
38
+ export function modeFor(dir) {
39
+ return isEffectivelyEmpty(dir) ? "scaffold" : "wire";
40
+ }
41
+
42
+ /**
43
+ * Error message for a flag that does not apply to the resolved mode.
44
+ * @param {object} args Parsed CLI arguments.
45
+ * @param {"scaffold" | "wire"} mode
46
+ * @param {string} dir
47
+ * @returns {string | undefined}
48
+ */
49
+ export function flagModeError(args, mode, dir) {
50
+ if (mode === "wire") {
51
+ const flag = SCAFFOLD_ONLY_FLAGS.find((name) => args[name] !== undefined);
52
+ if (flag) {
53
+ return `--${flag} only applies when creating a new project, but ${dir} is an existing project.`;
54
+ }
55
+ return undefined;
56
+ }
57
+ const flag = WIRE_ONLY_FLAGS.find((name) => args[name] !== undefined);
58
+ if (flag) {
59
+ return `--${flag} only applies when adding GraphQL-Markdown to an existing project, but ${dir} is empty.`;
60
+ }
61
+ return undefined;
62
+ }
63
+
64
+ /**
65
+ * Ids of the wire frameworks whose dependencies appear in a package.json.
66
+ * @param {object | null} packageJson
67
+ * @returns {string[]}
68
+ */
69
+ export function detectFrameworks(packageJson) {
70
+ if (!packageJson) return [];
71
+ const deps = new Set([
72
+ ...Object.keys(packageJson.dependencies ?? {}),
73
+ ...Object.keys(packageJson.devDependencies ?? {}),
74
+ ]);
75
+ return Object.entries(WIRE_FRAMEWORKS)
76
+ .filter(([, fw]) => (fw.detect ?? []).some((name) => deps.has(name)))
77
+ .map(([id]) => id);
78
+ }
79
+
80
+ /**
81
+ * Schema reference as written in .graphqlrc: remote sources unchanged, local
82
+ * paths made relative to the project directory.
83
+ * @param {string} source
84
+ * @param {string} projectDir
85
+ * @param {string} [cwd]
86
+ * @returns {string}
87
+ */
88
+ export function toSchemaRef(source, projectDir, cwd = process.cwd()) {
89
+ if (isRemoteSchemaSource(source)) return source;
90
+ const relative = path
91
+ .relative(projectDir, path.resolve(cwd, source))
92
+ .split(path.sep)
93
+ .join("/");
94
+ return relative.startsWith("../") ? relative : `./${relative}`;
95
+ }
package/lib/tasks.mjs ADDED
@@ -0,0 +1,154 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ import * as prompts from "@clack/prompts";
4
+
5
+ /**
6
+ * Maps each package manager to its install command and arguments.
7
+ * Each entry is [command, args] to be passed to spawn().
8
+ */
9
+ export const INSTALL_COMMANDS = {
10
+ npm: ["npm", ["install"]],
11
+ pnpm: ["pnpm", ["install"]],
12
+ yarn: ["yarn", []],
13
+ bun: ["bun", ["install"]],
14
+ };
15
+
16
+ /**
17
+ * Maps each package manager to the command that adds dev dependencies.
18
+ * Each entry is [command, args]; the packages are appended to args.
19
+ */
20
+ const ADD_DEV_COMMANDS = {
21
+ npm: ["npm", ["install", "--save-dev"]],
22
+ pnpm: ["pnpm", ["add", "--save-dev"]],
23
+ yarn: ["yarn", ["add", "--dev"]],
24
+ bun: ["bun", ["add", "--dev"]],
25
+ };
26
+
27
+ function addDevArgs(packageManager, packages, { workspaceRoot = false } = {}) {
28
+ const [command, args] =
29
+ ADD_DEV_COMMANDS[packageManager] ?? ADD_DEV_COMMANDS.npm;
30
+ const rootFlag = workspaceRoot
31
+ ? ({ pnpm: ["-w"], yarn: ["-W"] }[packageManager] ?? [])
32
+ : [];
33
+ return [command, [...args, ...rootFlag, ...packages]];
34
+ }
35
+
36
+ /**
37
+ * Run a command in a shell.
38
+ */
39
+ export function runCommand(command, args, options = {}) {
40
+ return new Promise((resolve, reject) => {
41
+ const proc = spawn(command, args, {
42
+ stdio: "inherit",
43
+ ...options,
44
+ });
45
+ proc.on("close", (code) => {
46
+ if (code === 0) {
47
+ resolve();
48
+ } else {
49
+ reject(new Error(`Command failed with exit code ${code}`));
50
+ }
51
+ });
52
+ proc.on("error", (err) => {
53
+ reject(
54
+ err?.code === "ENOENT"
55
+ ? new Error(`${command} is not installed or not on your PATH`)
56
+ : err,
57
+ );
58
+ });
59
+ });
60
+ }
61
+
62
+ /** Whether `git` is installed and runnable. */
63
+ export async function isGitAvailable() {
64
+ return runCommand("git", ["--version"], { stdio: "ignore" }).then(
65
+ () => true,
66
+ () => false,
67
+ );
68
+ }
69
+
70
+ /**
71
+ * Install dependencies for a project using the specified package manager.
72
+ * Logs info, runs the install command and logs success; throws on failure.
73
+ */
74
+ export async function installDependencies(packageManager, projectDir) {
75
+ prompts.log.info(`Installing dependencies with ${packageManager}...`);
76
+ const [command, args] =
77
+ INSTALL_COMMANDS[packageManager] ?? INSTALL_COMMANDS.npm;
78
+ await runCommand(command, args, { cwd: projectDir });
79
+ prompts.log.success("Dependencies installed!");
80
+ }
81
+
82
+ /**
83
+ * Command line that adds packages as dev dependencies, e.g. "bun add --dev a b".
84
+ * @param {string} packageManager
85
+ * @param {string[]} packages
86
+ * @returns {string}
87
+ */
88
+ export function addDevCommand(packageManager, packages, options = {}) {
89
+ const [command, args] = addDevArgs(packageManager, packages, options);
90
+ return [command, ...args].join(" ");
91
+ }
92
+
93
+ /**
94
+ * Add packages as dev dependencies using the specified package manager.
95
+ * Logs info, runs the add command and logs success; throws on failure.
96
+ */
97
+ export async function addDevDependencies(
98
+ packageManager,
99
+ projectDir,
100
+ packages,
101
+ options = {},
102
+ ) {
103
+ prompts.log.info(`Adding ${packages.join(", ")} with ${packageManager}...`);
104
+ const [command, args] = addDevArgs(packageManager, packages, options);
105
+ await runCommand(command, args, { cwd: projectDir });
106
+ prompts.log.success("Dev dependencies added!");
107
+ }
108
+
109
+ /**
110
+ * Initialize a git repository in the project directory.
111
+ * Skips when already inside a git work tree (no nested repos) and resolves to
112
+ * `false`; otherwise runs git init, git add, and git commit with an initial
113
+ * commit message and resolves to `true`. Throws on failure (after stopping the
114
+ * spinner).
115
+ */
116
+ export async function initGitRepo(projectDir) {
117
+ // Git output is silenced (stdio "ignore") so it doesn't garble the prompt UI.
118
+ const options = { cwd: projectDir, stdio: "ignore" };
119
+
120
+ // A nested repo inside an existing one is almost never wanted.
121
+ const insideRepo = await runCommand(
122
+ "git",
123
+ ["rev-parse", "--is-inside-work-tree"],
124
+ options,
125
+ ).then(
126
+ () => true,
127
+ () => false,
128
+ );
129
+ if (insideRepo) {
130
+ prompts.log.info("Already inside a git repository — skipping git init.");
131
+ return false;
132
+ }
133
+
134
+ const spinner = prompts.spinner();
135
+ spinner.start("Initializing git repository...");
136
+ try {
137
+ await runCommand("git", ["init"], options);
138
+ await runCommand("git", ["add", "."], options);
139
+ } catch (error) {
140
+ spinner.stop("Git initialization incomplete.");
141
+ throw error;
142
+ }
143
+ try {
144
+ await runCommand("git", ["commit", "-m", "Initial commit"], options);
145
+ spinner.stop("Git repository initialized!");
146
+ } catch (error) {
147
+ spinner.stop("Git initialization incomplete.");
148
+ throw new Error(
149
+ `${error.message} (the commit can fail when git user.name / user.email are not configured).`,
150
+ { cause: error },
151
+ );
152
+ }
153
+ return true;
154
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Package name behind a module specifier: "@scope/name/sub" gives "@scope/name",
3
+ * "name/sub" gives "name". Local paths ("." or "/" prefixed) have no package and
4
+ * give `undefined`.
5
+ * @param {string} specifier
6
+ * @returns {string | undefined}
7
+ */
8
+ export function packageNameOf(specifier) {
9
+ if (specifier.startsWith(".") || specifier.startsWith("/")) return undefined;
10
+ const [first, second] = specifier.split("/");
11
+ if (first.startsWith("@")) return second ? `${first}/${second}` : undefined;
12
+ return first;
13
+ }
14
+
15
+ /**
16
+ * Packages wire mode needs in the project: the CLI, the formatter (the
17
+ * --formatter value, else the framework preset's) and the schema loader.
18
+ * Duplicates and packages already listed in package.json are left out.
19
+ * @param {{ descriptor: { formatter?: string }, loader: { package: string }, formatter?: string, packageJson?: object | null }} inputs
20
+ * @returns {string[]}
21
+ */
22
+ export function requiredPackages({
23
+ descriptor,
24
+ loader,
25
+ formatter,
26
+ packageJson,
27
+ }) {
28
+ const present = new Set([
29
+ ...Object.keys(packageJson?.dependencies ?? {}),
30
+ ...Object.keys(packageJson?.devDependencies ?? {}),
31
+ ]);
32
+ const formatterSpecifier = formatter || descriptor.formatter;
33
+ const names = ["@graphql-markdown/cli"];
34
+ if (formatterSpecifier) names.push(packageNameOf(formatterSpecifier));
35
+ names.push(loader.package);
36
+ const unique = [...new Set(names.filter(Boolean))];
37
+ return unique.filter((name) => !present.has(name));
38
+ }