create-graphql-markdown-docs 0.0.0-stage → 0.1.1
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/README.md +86 -2
- package/bin/create.mjs +5 -0
- package/lib/create.mjs +845 -0
- package/package.json +60 -4
- package/templates/docusaurus/.graphqlrc +13 -0
- package/templates/docusaurus/README.md +31 -0
- package/templates/docusaurus/babel.config.js +3 -0
- package/templates/docusaurus/docs/.gitkeep +0 -0
- package/templates/docusaurus/docusaurus.config.js +65 -0
- package/templates/docusaurus/package.json +45 -0
- package/templates/docusaurus/schema/example.graphql +55 -0
- package/templates/docusaurus/src/css/custom.css +39 -0
- package/templates/docusaurus/static/.nojekyll +0 -0
- package/templates/docusaurus/static/img/favicon.ico +0 -0
- package/templates/docusaurus/static/img/graphql-markdown.svg +204 -0
- package/templates/docusaurus/static/index.md +28 -0
- package/templates/nuxt/README.md +64 -0
- package/templates/nuxt/app/app.config.ts +11 -0
- package/templates/nuxt/app/pages/index.vue +10 -0
- package/templates/nuxt/content.config.ts +13 -0
- package/templates/nuxt/generate-docs.ts +5 -0
- package/templates/nuxt/nuxt.config.ts +8 -0
- package/templates/nuxt/package.json +25 -0
- package/templates/nuxt/schema/example.graphql +55 -0
package/lib/create.mjs
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
|
|
8
|
+
import * as prompts from "@clack/prompts";
|
|
9
|
+
import { detect as detectPackageManager } from "package-manager-detector";
|
|
10
|
+
|
|
11
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const packageRoot = path.resolve(__dirname, "..");
|
|
13
|
+
const templatesRoot = path.resolve(packageRoot, "templates");
|
|
14
|
+
|
|
15
|
+
/** Supported scaffold targets; each maps to `templates/<framework>`. */
|
|
16
|
+
const FRAMEWORKS = ["nuxt", "docusaurus"];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Maps each package manager to its install command and arguments.
|
|
20
|
+
* Each entry is [command, args] to be passed to spawn().
|
|
21
|
+
*/
|
|
22
|
+
const INSTALL_COMMANDS = {
|
|
23
|
+
npm: ["npm", ["install"]],
|
|
24
|
+
pnpm: ["pnpm", ["install"]],
|
|
25
|
+
yarn: ["yarn", []],
|
|
26
|
+
bun: ["bun", ["install"]],
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The official graphql-tools loaders (github.com/ardatan/graphql-tools/tree/
|
|
31
|
+
* master/packages/loaders) that make sense as a schema *source* for
|
|
32
|
+
* graphql-markdown — excludes loaders for things that aren't ever a whole
|
|
33
|
+
* schema's source (e.g. `@graphql-tools/apollo-engine-loader` targets a
|
|
34
|
+
* managed-federation registry, out of scope here).
|
|
35
|
+
*
|
|
36
|
+
* `version: 'latest'` deliberately, not a pinned range: a scaffolded project
|
|
37
|
+
* runs `npm install` (or equivalent) immediately, once, right after this
|
|
38
|
+
* file is written — there's no ongoing lockfile for this CLI to keep in sync
|
|
39
|
+
* with graphql-tools' own release cadence, so pinning a version here would
|
|
40
|
+
* just silently go stale the day graphql-tools cuts a release. Same
|
|
41
|
+
* rationale most `create-*` scaffolding CLIs use for freshly-installed deps.
|
|
42
|
+
*
|
|
43
|
+
* `match` runs against the raw schema source string the user provided (a
|
|
44
|
+
* path or a URL) to pick the loader graphql-markdown needs to actually read
|
|
45
|
+
* it; order matters, first match wins.
|
|
46
|
+
*/
|
|
47
|
+
const LOADERS = [
|
|
48
|
+
{
|
|
49
|
+
id: "url",
|
|
50
|
+
match: (source) => /^https?:\/\//i.test(source),
|
|
51
|
+
className: "UrlLoader",
|
|
52
|
+
package: "@graphql-tools/url-loader",
|
|
53
|
+
version: "latest",
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: "github",
|
|
57
|
+
match: (source) => /^github:/i.test(source),
|
|
58
|
+
className: "GithubLoader",
|
|
59
|
+
package: "@graphql-tools/github-loader",
|
|
60
|
+
version: "latest",
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
id: "git",
|
|
64
|
+
match: (source) => /^git:/i.test(source),
|
|
65
|
+
className: "GitLoader",
|
|
66
|
+
package: "@graphql-tools/git-loader",
|
|
67
|
+
version: "latest",
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
id: "json",
|
|
71
|
+
match: (source) => /\.json$/i.test(source),
|
|
72
|
+
className: "JsonFileLoader",
|
|
73
|
+
package: "@graphql-tools/json-file-loader",
|
|
74
|
+
version: "latest",
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
id: "code",
|
|
78
|
+
match: (source) => /\.(js|mjs|cjs|ts|mts|cts)$/i.test(source),
|
|
79
|
+
className: "CodeFileLoader",
|
|
80
|
+
package: "@graphql-tools/code-file-loader",
|
|
81
|
+
version: "latest",
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
// Default: a local .graphql/.gql SDL file. This is the loader
|
|
85
|
+
// `createGenerateDocs` already defaults to internally, so scaffolds that
|
|
86
|
+
// land here emit no explicit `loaders` option at all — one less thing
|
|
87
|
+
// for the common case to carry, and no version to track either.
|
|
88
|
+
id: "file",
|
|
89
|
+
match: (source) => /\.(graphql|gql)$/i.test(source),
|
|
90
|
+
className: "GraphQLFileLoader",
|
|
91
|
+
package: "@graphql-tools/graphql-file-loader",
|
|
92
|
+
isDefault: true,
|
|
93
|
+
},
|
|
94
|
+
];
|
|
95
|
+
|
|
96
|
+
/** Picks the loader for a schema source string, falling back to the local-file loader. */
|
|
97
|
+
export function detectLoader(schemaSource) {
|
|
98
|
+
return (
|
|
99
|
+
LOADERS.find((loader) => loader.match(schemaSource)) ??
|
|
100
|
+
LOADERS.find((l) => l.isDefault)
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A schema "path" that's actually a remote/VCS reference, not a local file to copy. */
|
|
105
|
+
export function isRemoteSchemaSource(source) {
|
|
106
|
+
return /^(https?|git|github):/i.test(source);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Copy a directory recursively, excluding certain patterns.
|
|
111
|
+
*/
|
|
112
|
+
export function copyDirRecursive(src, dst, excludePatterns = []) {
|
|
113
|
+
if (!fs.existsSync(dst)) {
|
|
114
|
+
fs.mkdirSync(dst, { recursive: true });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const files = fs.readdirSync(src);
|
|
118
|
+
for (const file of files) {
|
|
119
|
+
// Skip excluded patterns
|
|
120
|
+
if (excludePatterns.some((pattern) => pattern.exec(file))) {
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const srcPath = path.join(src, file);
|
|
125
|
+
const dstPath = path.join(dst, file);
|
|
126
|
+
const stat = fs.statSync(srcPath);
|
|
127
|
+
|
|
128
|
+
if (stat.isDirectory()) {
|
|
129
|
+
copyDirRecursive(srcPath, dstPath, excludePatterns);
|
|
130
|
+
} else {
|
|
131
|
+
fs.copyFileSync(srcPath, dstPath);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Validate a GraphQL schema file by attempting to parse it with buildSchema.
|
|
138
|
+
*/
|
|
139
|
+
export async function validateGraphQLSchema(schemaPath) {
|
|
140
|
+
try {
|
|
141
|
+
const fs = await import("node:fs/promises");
|
|
142
|
+
const schemaText = await fs.readFile(schemaPath, "utf-8");
|
|
143
|
+
|
|
144
|
+
// Use graphql's buildSchema to validate
|
|
145
|
+
const { buildSchema } = await import("graphql");
|
|
146
|
+
buildSchema(schemaText);
|
|
147
|
+
return true;
|
|
148
|
+
} catch {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Run a command in a shell.
|
|
155
|
+
*/
|
|
156
|
+
export function runCommand(command, args, options = {}) {
|
|
157
|
+
return new Promise((resolve, reject) => {
|
|
158
|
+
const proc = spawn(command, args, {
|
|
159
|
+
stdio: "inherit",
|
|
160
|
+
...options,
|
|
161
|
+
});
|
|
162
|
+
proc.on("close", (code) => {
|
|
163
|
+
if (code === 0) {
|
|
164
|
+
resolve();
|
|
165
|
+
} else {
|
|
166
|
+
reject(new Error(`Command failed with exit code ${code}`));
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
proc.on("error", reject);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Install dependencies for a project using the specified package manager.
|
|
175
|
+
* Logs info, runs the install command, logs success, and catches+logs errors.
|
|
176
|
+
*/
|
|
177
|
+
export async function installDependencies(packageManager, projectDir) {
|
|
178
|
+
prompts.log.info(`Installing dependencies with ${packageManager}...`);
|
|
179
|
+
try {
|
|
180
|
+
const [command, args] =
|
|
181
|
+
INSTALL_COMMANDS[packageManager] ?? INSTALL_COMMANDS.npm;
|
|
182
|
+
await runCommand(command, args, { cwd: projectDir });
|
|
183
|
+
prompts.log.success("Dependencies installed!");
|
|
184
|
+
} catch (error) {
|
|
185
|
+
prompts.log.error(`Failed to install dependencies: ${error.message}`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Initialize a git repository in the project directory.
|
|
191
|
+
* Runs git init, git add, and git commit with an initial commit message.
|
|
192
|
+
* Logs success and catches+logs errors.
|
|
193
|
+
*/
|
|
194
|
+
export async function initGitRepo(projectDir) {
|
|
195
|
+
try {
|
|
196
|
+
await runCommand("git", ["init"], { cwd: projectDir });
|
|
197
|
+
await runCommand("git", ["add", "."], { cwd: projectDir });
|
|
198
|
+
await runCommand("git", ["commit", "-m", "Initial commit"], {
|
|
199
|
+
cwd: projectDir,
|
|
200
|
+
});
|
|
201
|
+
prompts.log.success("Git repository initialized!");
|
|
202
|
+
} catch (error) {
|
|
203
|
+
prompts.log.warn(`Could not initialize git: ${error.message}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Rewrite app.config.ts with custom title and/or color overrides.
|
|
209
|
+
*/
|
|
210
|
+
export function writeAppConfig(tempDir, titleOverride, colorOverride) {
|
|
211
|
+
if (!titleOverride && !colorOverride) {
|
|
212
|
+
return; // No changes needed
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const appConfigPath = path.join(tempDir, "app", "app.config.ts");
|
|
216
|
+
let appConfig = fs.readFileSync(appConfigPath, "utf-8");
|
|
217
|
+
const originalContent = appConfig;
|
|
218
|
+
|
|
219
|
+
if (titleOverride) {
|
|
220
|
+
appConfig = appConfig.replace(
|
|
221
|
+
/siteTitle: 'My API'/,
|
|
222
|
+
() => `siteTitle: ${JSON.stringify(titleOverride)}`,
|
|
223
|
+
);
|
|
224
|
+
if (appConfig === originalContent) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`Expected to find and replace "siteTitle: 'My API'" in ${appConfigPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (colorOverride) {
|
|
232
|
+
// The template ships no `ui.colors` block at all (the layer's own
|
|
233
|
+
// violet/zinc defaults apply via `extends` until overridden) — add
|
|
234
|
+
// one rather than trying to replace a value that isn't there.
|
|
235
|
+
const beforeColorOverride = appConfig;
|
|
236
|
+
appConfig = appConfig.replace(
|
|
237
|
+
"export default defineAppConfig({",
|
|
238
|
+
() =>
|
|
239
|
+
`export default defineAppConfig({\n ui: {\n colors: {\n primary: ${JSON.stringify(colorOverride)},\n },\n },`,
|
|
240
|
+
);
|
|
241
|
+
if (appConfig === beforeColorOverride) {
|
|
242
|
+
throw new Error(
|
|
243
|
+
`Expected to find and replace "export default defineAppConfig({" in ${appConfigPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
fs.writeFileSync(appConfigPath, appConfig);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Rewrite generate-docs.ts to use the resolved schema path and loader.
|
|
253
|
+
*/
|
|
254
|
+
export function writeGenerateDocs(tempDir, schemaRef, loader) {
|
|
255
|
+
const generateDocsPath = path.join(tempDir, "generate-docs.ts");
|
|
256
|
+
const originalContent = fs.readFileSync(generateDocsPath, "utf-8");
|
|
257
|
+
|
|
258
|
+
// The default (bundled example, GraphQLFileLoader) needs no `loaders` option
|
|
259
|
+
// at all — createGenerateDocs already defaults to it — so only inject
|
|
260
|
+
// one when the detected loader differs.
|
|
261
|
+
const replacement = loader.isDefault
|
|
262
|
+
? ` schema: '${schemaRef}',`
|
|
263
|
+
: ` schema: '${schemaRef}',\n loaders: { ${loader.className}: '${loader.package}' },`;
|
|
264
|
+
|
|
265
|
+
const updated = originalContent.replace(
|
|
266
|
+
" schema: './schema/example.graphql',",
|
|
267
|
+
replacement,
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
// Only validate the replacement if we expected a change (i.e., the replacement differs from the original pattern).
|
|
271
|
+
if (
|
|
272
|
+
replacement !== " schema: './schema/example.graphql'," &&
|
|
273
|
+
updated === originalContent
|
|
274
|
+
) {
|
|
275
|
+
throw new Error(
|
|
276
|
+
`Expected to find and replace " schema: './schema/example.graphql'," in ${generateDocsPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
fs.writeFileSync(generateDocsPath, updated);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Removes the layer's `watch: [...]` block (and its leading comment) using
|
|
285
|
+
* linear string scanning, replacing it with a single newline. Returns the
|
|
286
|
+
* input unchanged when the block isn't found.
|
|
287
|
+
*/
|
|
288
|
+
export function removeWatchBlock(content) {
|
|
289
|
+
const marker = "// The layer's gqlmd-generate module";
|
|
290
|
+
const markerIdx = content.indexOf(marker);
|
|
291
|
+
if (markerIdx === -1) return content;
|
|
292
|
+
const watchIdx = content.indexOf("watch: [", markerIdx);
|
|
293
|
+
if (watchIdx === -1) return content;
|
|
294
|
+
const lineStart = content.lastIndexOf("\n", watchIdx);
|
|
295
|
+
if (lineStart < markerIdx || content.slice(lineStart + 1, watchIdx).trim()) {
|
|
296
|
+
return content;
|
|
297
|
+
}
|
|
298
|
+
const closeIdx = content.indexOf("]", watchIdx);
|
|
299
|
+
if (closeIdx === -1 || !content.startsWith(",\n", closeIdx + 1)) {
|
|
300
|
+
return content;
|
|
301
|
+
}
|
|
302
|
+
let start = markerIdx;
|
|
303
|
+
while (start > 0 && /\s/.test(content[start - 1])) start--;
|
|
304
|
+
return `${content.slice(0, start)}\n${content.slice(closeIdx + 3)}`;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Rewrite nuxt.config.ts's `watch` entry and/or schema filename to match the resolved schema.
|
|
309
|
+
*/
|
|
310
|
+
export function writeNuxtConfig(tempDir, schemaRef, isRemoteSource) {
|
|
311
|
+
const nuxtConfigPath = path.join(tempDir, "nuxt.config.ts");
|
|
312
|
+
const originalContent = fs.readFileSync(nuxtConfigPath, "utf-8");
|
|
313
|
+
|
|
314
|
+
let updated = originalContent;
|
|
315
|
+
|
|
316
|
+
if (isRemoteSource) {
|
|
317
|
+
// A remote schema source (URL/git/github) has no local file to watch at all —
|
|
318
|
+
// dev-server restarts on schema change simply aren't available for those,
|
|
319
|
+
// so the entry is dropped rather than left pointing at a path that no longer
|
|
320
|
+
// means anything.
|
|
321
|
+
const beforeWatchRemoval = updated;
|
|
322
|
+
updated = removeWatchBlock(updated);
|
|
323
|
+
|
|
324
|
+
if (updated === beforeWatchRemoval) {
|
|
325
|
+
throw new Error(
|
|
326
|
+
`Expected to find and replace the watch block in ${nuxtConfigPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const beforeImportRemoval = updated;
|
|
331
|
+
updated = updated.replace(
|
|
332
|
+
'import { fileURLToPath } from "node:url";\n\n',
|
|
333
|
+
"",
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
if (updated === beforeImportRemoval) {
|
|
337
|
+
throw new Error(
|
|
338
|
+
`Expected to find and replace the fileURLToPath import in ${nuxtConfigPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
} else {
|
|
342
|
+
// Local schema: replace the example filename with the actual one.
|
|
343
|
+
// Only validate if we expect a change (schemaRef differs from the default).
|
|
344
|
+
const beforeSchemaReplace = updated;
|
|
345
|
+
updated = updated.replace("./schema/example.graphql", schemaRef);
|
|
346
|
+
|
|
347
|
+
if (
|
|
348
|
+
schemaRef !== "./schema/example.graphql" &&
|
|
349
|
+
updated === beforeSchemaReplace
|
|
350
|
+
) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
`Expected to find and replace "./schema/example.graphql" in ${nuxtConfigPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
fs.writeFileSync(nuxtConfigPath, updated);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Rewrite the Docusaurus template's .graphqlrc `schema` line and loader entry.
|
|
362
|
+
*/
|
|
363
|
+
export function writeGraphqlrc(tempDir, schemaRef, loader) {
|
|
364
|
+
const graphqlrcPath = path.join(tempDir, ".graphqlrc");
|
|
365
|
+
const originalContent = fs.readFileSync(graphqlrcPath, "utf-8");
|
|
366
|
+
|
|
367
|
+
const defaultSchemaLine = "schema: './schema/example.graphql'";
|
|
368
|
+
const defaultLoaderLine =
|
|
369
|
+
" GraphQLFileLoader: '@graphql-tools/graphql-file-loader'";
|
|
370
|
+
|
|
371
|
+
let updated = originalContent.replace(
|
|
372
|
+
defaultSchemaLine,
|
|
373
|
+
() => `schema: '${schemaRef}'`,
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
if (schemaRef !== "./schema/example.graphql" && updated === originalContent) {
|
|
377
|
+
throw new Error(
|
|
378
|
+
`Expected to find and replace "${defaultSchemaLine}" in ${graphqlrcPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
if (!loader.isDefault) {
|
|
383
|
+
// URL sources are introspected with POST, as in the original template.
|
|
384
|
+
const loaderEntry =
|
|
385
|
+
loader.id === "url"
|
|
386
|
+
? ` ${loader.className}:\n module: '${loader.package}'\n options:\n method: 'POST'`
|
|
387
|
+
: ` ${loader.className}: '${loader.package}'`;
|
|
388
|
+
const beforeLoader = updated;
|
|
389
|
+
updated = updated.replace(defaultLoaderLine, () => loaderEntry);
|
|
390
|
+
|
|
391
|
+
if (updated === beforeLoader) {
|
|
392
|
+
throw new Error(
|
|
393
|
+
`Expected to find and replace "${defaultLoaderLine.trim()}" in ${graphqlrcPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
fs.writeFileSync(graphqlrcPath, updated);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Rewrite the Docusaurus template's docusaurus.config.js site title.
|
|
403
|
+
*/
|
|
404
|
+
export function writeDocusaurusConfig(tempDir, titleOverride) {
|
|
405
|
+
if (!titleOverride) {
|
|
406
|
+
return; // No changes needed
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const configPath = path.join(tempDir, "docusaurus.config.js");
|
|
410
|
+
const originalContent = fs.readFileSync(configPath, "utf-8");
|
|
411
|
+
const updated = originalContent.replace(
|
|
412
|
+
'title: "My API",',
|
|
413
|
+
() => `title: ${JSON.stringify(titleOverride)},`,
|
|
414
|
+
);
|
|
415
|
+
|
|
416
|
+
if (updated === originalContent) {
|
|
417
|
+
throw new Error(
|
|
418
|
+
`Expected to find and replace 'title: "My API",' in ${configPath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
fs.writeFileSync(configPath, updated);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Rewrite package.json to set the project name and add non-default loaders as dependencies.
|
|
427
|
+
*/
|
|
428
|
+
export function writePackageJson(tempDir, projectDir, loader) {
|
|
429
|
+
const pkgJsonPath = path.join(tempDir, "package.json");
|
|
430
|
+
let pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
431
|
+
const projectName = path.basename(projectDir);
|
|
432
|
+
pkgJson.name = projectName;
|
|
433
|
+
if (!loader.isDefault) {
|
|
434
|
+
pkgJson.dependencies[loader.package] = loader.version;
|
|
435
|
+
}
|
|
436
|
+
fs.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2) + "\n");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Rewrite README.md's schema section to document the actual schema source.
|
|
441
|
+
*/
|
|
442
|
+
export function writeReadme(tempDir, schemaPath, schemaRef, loader) {
|
|
443
|
+
if (!schemaPath) {
|
|
444
|
+
return; // No custom schema, keep the template's instructions
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const readmePath = path.join(tempDir, "README.md");
|
|
448
|
+
const originalContent = fs.readFileSync(readmePath, "utf-8");
|
|
449
|
+
const schemaSectionRe = /### Your GraphQL Schema\n\n[\s\S]*?(?=\n### |\n## )/;
|
|
450
|
+
|
|
451
|
+
const isRemoteSource = /^(https?|git|github):/i.test(schemaRef);
|
|
452
|
+
const replacement = isRemoteSource
|
|
453
|
+
? `### Your GraphQL Schema\n\nThis project reads its schema from \`${schemaRef}\` via ${loader.package} (${loader.className}) — configured in \`generate-docs.ts\`. There is no local schema file to edit; point \`generate-docs.ts\`'s \`schema\` option at a different source to change it.\n`
|
|
454
|
+
: `### Your GraphQL Schema\n\nYour schema lives at \`${schemaRef}\`. To point at a different file, update both \`generate-docs.ts\`'s \`schema\` option and \`nuxt.config.ts\`'s \`watch\` entry.\n`;
|
|
455
|
+
|
|
456
|
+
const updated = originalContent.replace(schemaSectionRe, replacement);
|
|
457
|
+
|
|
458
|
+
if (updated === originalContent) {
|
|
459
|
+
throw new Error(
|
|
460
|
+
`Expected to find and replace the schema section in ${readmePath}, but nothing matched — the template may have changed. Update the CLI's rewrite logic.`,
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
fs.writeFileSync(readmePath, updated);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Thrown to abort the scaffold with an exit code; the message was already logged. */
|
|
468
|
+
class CliExit extends Error {
|
|
469
|
+
constructor(code = 1) {
|
|
470
|
+
super("cli-exit");
|
|
471
|
+
this.code = code;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Abort the run when a prompt was cancelled; otherwise return its value. */
|
|
476
|
+
function unlessCancelled(value) {
|
|
477
|
+
if (prompts.isCancel(value)) {
|
|
478
|
+
prompts.cancel("Setup cancelled.");
|
|
479
|
+
throw new CliExit(1);
|
|
480
|
+
}
|
|
481
|
+
return value;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Log an error and abort the run. */
|
|
485
|
+
function fail(message) {
|
|
486
|
+
prompts.log.error(message);
|
|
487
|
+
throw new CliExit(1);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Phase 1: parse command-line arguments. */
|
|
491
|
+
export function parseCliArgs(argv) {
|
|
492
|
+
const { values } = parseArgs({
|
|
493
|
+
args: argv,
|
|
494
|
+
options: {
|
|
495
|
+
framework: { type: "string" },
|
|
496
|
+
dir: { type: "string", short: "d" },
|
|
497
|
+
schema: { type: "string" },
|
|
498
|
+
example: { type: "boolean" },
|
|
499
|
+
pm: { type: "string" },
|
|
500
|
+
title: { type: "string" },
|
|
501
|
+
color: { type: "string" },
|
|
502
|
+
"no-install": { type: "boolean" },
|
|
503
|
+
"no-git": { type: "boolean" },
|
|
504
|
+
yes: { type: "boolean" },
|
|
505
|
+
},
|
|
506
|
+
allowPositionals: false,
|
|
507
|
+
});
|
|
508
|
+
return values;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async function resolveFramework(args) {
|
|
512
|
+
if (args.framework) {
|
|
513
|
+
if (!FRAMEWORKS.includes(args.framework)) {
|
|
514
|
+
fail(
|
|
515
|
+
`Invalid --framework "${args.framework}" — expected one of: ${FRAMEWORKS.join(", ")}.`,
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
return args.framework;
|
|
519
|
+
}
|
|
520
|
+
if (args.yes) return "nuxt";
|
|
521
|
+
return unlessCancelled(
|
|
522
|
+
await prompts.select({
|
|
523
|
+
message: "Which framework would you like to use?",
|
|
524
|
+
options: [
|
|
525
|
+
{ value: "nuxt", label: "Nuxt (@graphql-markdown/nuxt-theme)" },
|
|
526
|
+
{ value: "docusaurus", label: "Docusaurus" },
|
|
527
|
+
],
|
|
528
|
+
}),
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function resolveProjectDir(args) {
|
|
533
|
+
let projectDir = args.dir;
|
|
534
|
+
if (!projectDir) {
|
|
535
|
+
projectDir = args.yes
|
|
536
|
+
? "./my-graphql-docs"
|
|
537
|
+
: await prompts.text({
|
|
538
|
+
message: "Where should we create your project?",
|
|
539
|
+
defaultValue: "./my-graphql-docs",
|
|
540
|
+
validate: (value) => {
|
|
541
|
+
if (!value || value.trim() === "") {
|
|
542
|
+
return "Project directory cannot be empty";
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
projectDir = path.resolve(unlessCancelled(projectDir));
|
|
548
|
+
|
|
549
|
+
// Refuse a non-empty target outright — never overwrite existing files,
|
|
550
|
+
// in interactive mode or --yes. There is no confirm-to-overwrite path:
|
|
551
|
+
// the scaffold later does an unconditional `rmSync(projectDir, {
|
|
552
|
+
// recursive: true })` before writing, so "confirm then proceed" would
|
|
553
|
+
// still mean deleting whatever was there first. If you want to scaffold
|
|
554
|
+
// into that directory, empty or remove it yourself first.
|
|
555
|
+
if (fs.existsSync(projectDir) && fs.readdirSync(projectDir).length > 0) {
|
|
556
|
+
fail(
|
|
557
|
+
`${projectDir} already exists and is not empty — refusing to overwrite it.`,
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
return projectDir;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function validateSchemaSource(value) {
|
|
564
|
+
if (!value) return "Schema source is required";
|
|
565
|
+
if (!isRemoteSchemaSource(value) && !fs.existsSync(value)) {
|
|
566
|
+
return "Schema file not found";
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Resolves the custom schema source, or undefined to use the bundled example. */
|
|
571
|
+
async function resolveSchemaPath(args) {
|
|
572
|
+
if (args.example || args.schema || args.yes) return args.schema;
|
|
573
|
+
|
|
574
|
+
const schemaChoice = unlessCancelled(
|
|
575
|
+
await prompts.select({
|
|
576
|
+
message: "How would you like to provide your GraphQL schema?",
|
|
577
|
+
options: [
|
|
578
|
+
{
|
|
579
|
+
value: "example",
|
|
580
|
+
label: "Use example schema (recommended for first-time)",
|
|
581
|
+
},
|
|
582
|
+
{ value: "existing", label: "Use an existing schema file" },
|
|
583
|
+
],
|
|
584
|
+
}),
|
|
585
|
+
);
|
|
586
|
+
if (schemaChoice !== "existing") return undefined;
|
|
587
|
+
|
|
588
|
+
return unlessCancelled(
|
|
589
|
+
await prompts.text({
|
|
590
|
+
message:
|
|
591
|
+
"Path or URL to your GraphQL schema (local file, introspection endpoint, git:/github: ref):",
|
|
592
|
+
validate: validateSchemaSource,
|
|
593
|
+
}),
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** Validates a local schema and detects the loader it needs. */
|
|
598
|
+
async function resolveLoader(schemaPath) {
|
|
599
|
+
// Validate a local schema file's syntax (skipped for remote sources —
|
|
600
|
+
// fetching one just to lint it isn't worth the network round trip here;
|
|
601
|
+
// `nuxi generate` will surface a real error if it's actually invalid).
|
|
602
|
+
if (schemaPath && !isRemoteSchemaSource(schemaPath)) {
|
|
603
|
+
const isValid = await validateGraphQLSchema(schemaPath);
|
|
604
|
+
if (!isValid) {
|
|
605
|
+
prompts.log.warn(
|
|
606
|
+
`${schemaPath} did not parse as a valid GraphQL schema — continuing anyway, but double-check it.`,
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// Every schema source needs the matching graphql-tools loader — detect it
|
|
612
|
+
// from the source and report the choice.
|
|
613
|
+
const loader = detectLoader(schemaPath ?? "schema/example.graphql");
|
|
614
|
+
if (schemaPath && !loader.isDefault) {
|
|
615
|
+
prompts.log.info(
|
|
616
|
+
`Detected schema source needs ${loader.package} (${loader.className}) — adding it as a dependency.`,
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
return loader;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
async function resolvePackageManager(args) {
|
|
623
|
+
if (args.pm) return args.pm;
|
|
624
|
+
const detected = await detectPackageManager({ cwd: process.cwd() });
|
|
625
|
+
if (detected?.name) return detected.name;
|
|
626
|
+
if (args.yes) return "npm";
|
|
627
|
+
return unlessCancelled(
|
|
628
|
+
await prompts.select({
|
|
629
|
+
message: "Which package manager would you like to use?",
|
|
630
|
+
options: [
|
|
631
|
+
{ value: "npm", label: "npm" },
|
|
632
|
+
{ value: "pnpm", label: "pnpm" },
|
|
633
|
+
{ value: "yarn", label: "yarn" },
|
|
634
|
+
{ value: "bun", label: "bun" },
|
|
635
|
+
],
|
|
636
|
+
}),
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Asks for a value; a cancelled or empty answer yields `fallback`. */
|
|
641
|
+
async function askOptional(options, fallback) {
|
|
642
|
+
const answer = await prompts.text(options);
|
|
643
|
+
return !prompts.isCancel(answer) && answer ? answer : fallback;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** Warns when --color is passed to a framework that ignores it. */
|
|
647
|
+
function initialColor(args, isDocusaurus) {
|
|
648
|
+
const color = args.color ?? "";
|
|
649
|
+
if (isDocusaurus && color) {
|
|
650
|
+
prompts.log.warn(
|
|
651
|
+
"--color only applies to the Nuxt template — ignoring it for Docusaurus.",
|
|
652
|
+
);
|
|
653
|
+
return "";
|
|
654
|
+
}
|
|
655
|
+
return color;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/** Whether the user wants to customize title/color interactively. */
|
|
659
|
+
async function wantsCustomization() {
|
|
660
|
+
const answer = await prompts.confirm({
|
|
661
|
+
message: "Would you like to customize the site title and appearance?",
|
|
662
|
+
initialValue: false,
|
|
663
|
+
});
|
|
664
|
+
return !prompts.isCancel(answer) && Boolean(answer);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** Optional title and color customization. */
|
|
668
|
+
async function promptCustomization(args, isDocusaurus) {
|
|
669
|
+
let title = args.title ?? "";
|
|
670
|
+
let color = initialColor(args, isDocusaurus);
|
|
671
|
+
if (args.yes || !(await wantsCustomization())) return { title, color };
|
|
672
|
+
|
|
673
|
+
if (!args.title) {
|
|
674
|
+
title = await askOptional(
|
|
675
|
+
{ message: "Site title:", defaultValue: "My API" },
|
|
676
|
+
title,
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
if (!isDocusaurus && !color) {
|
|
680
|
+
color = await askOptional(
|
|
681
|
+
{
|
|
682
|
+
message:
|
|
683
|
+
"Primary color (any Nuxt UI / Tailwind color name, e.g. violet, blue, emerald):",
|
|
684
|
+
},
|
|
685
|
+
color,
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
return { title, color };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** Copies a local schema into the scaffold (or drops the example for remote ones). */
|
|
692
|
+
function placeSchema(tempDir, schemaPath) {
|
|
693
|
+
const templateExamplePath = path.join(tempDir, "schema", "example.graphql");
|
|
694
|
+
if (!schemaPath) return "./schema/example.graphql";
|
|
695
|
+
|
|
696
|
+
if (isRemoteSchemaSource(schemaPath)) {
|
|
697
|
+
// Nothing to copy — the bundled example is unused, drop it so it
|
|
698
|
+
// doesn't sit there implying it's still what gets generated.
|
|
699
|
+
fs.rmSync(templateExamplePath, { force: true });
|
|
700
|
+
return schemaPath;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const destName = `schema${path.extname(schemaPath) || ".graphql"}`;
|
|
704
|
+
const destSchema = path.join(tempDir, "schema", destName);
|
|
705
|
+
if (destSchema !== templateExamplePath) {
|
|
706
|
+
fs.rmSync(templateExamplePath, { force: true });
|
|
707
|
+
}
|
|
708
|
+
fs.copyFileSync(schemaPath, destSchema);
|
|
709
|
+
return `./schema/${destName}`;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** Phase 3: copy the template and apply all rewrites. */
|
|
713
|
+
function applyTemplate(tempDir, ctx) {
|
|
714
|
+
const { framework, projectDir, schemaPath, loader, title, color } = ctx;
|
|
715
|
+
const isDocusaurus = framework === "docusaurus";
|
|
716
|
+
|
|
717
|
+
copyDirRecursive(path.join(templatesRoot, framework), tempDir, [
|
|
718
|
+
/^node_modules$/,
|
|
719
|
+
/^\.nuxt$/,
|
|
720
|
+
/^\.output$/,
|
|
721
|
+
]);
|
|
722
|
+
|
|
723
|
+
const schemaRef = placeSchema(tempDir, schemaPath);
|
|
724
|
+
|
|
725
|
+
if (isDocusaurus) {
|
|
726
|
+
writeDocusaurusConfig(tempDir, title);
|
|
727
|
+
writeGraphqlrc(tempDir, schemaRef, loader);
|
|
728
|
+
} else {
|
|
729
|
+
writeAppConfig(tempDir, title, color);
|
|
730
|
+
writeGenerateDocs(tempDir, schemaRef, loader);
|
|
731
|
+
writeNuxtConfig(tempDir, schemaRef, isRemoteSchemaSource(schemaRef));
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
writePackageJson(tempDir, projectDir, loader);
|
|
735
|
+
|
|
736
|
+
// The Docusaurus README already documents editing .graphqlrc generically.
|
|
737
|
+
if (!isDocusaurus) {
|
|
738
|
+
writeReadme(tempDir, schemaPath, schemaRef, loader);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function moveIntoPlace(tempDir, projectDir) {
|
|
743
|
+
if (fs.existsSync(projectDir)) {
|
|
744
|
+
fs.rmSync(projectDir, { recursive: true, force: true });
|
|
745
|
+
}
|
|
746
|
+
try {
|
|
747
|
+
fs.renameSync(tempDir, projectDir);
|
|
748
|
+
} catch (err) {
|
|
749
|
+
if (err.code !== "EXDEV") throw err;
|
|
750
|
+
// temp dir is on another filesystem; the caller removes it afterwards
|
|
751
|
+
fs.cpSync(tempDir, projectDir, { recursive: true });
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/** Runs `action` immediately with --yes, otherwise only after a confirmed prompt. */
|
|
756
|
+
async function confirmThen(isYes, message, action) {
|
|
757
|
+
if (isYes) return action();
|
|
758
|
+
const confirmed = await prompts.confirm({ message, initialValue: true });
|
|
759
|
+
if (!prompts.isCancel(confirmed) && confirmed) return action();
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** Phase 4: install dependencies, init git, print summary. */
|
|
763
|
+
async function finalize(args, ctx) {
|
|
764
|
+
const { projectDir, packageManager, framework } = ctx;
|
|
765
|
+
const isYes = Boolean(args.yes);
|
|
766
|
+
|
|
767
|
+
if (!args["no-install"]) {
|
|
768
|
+
await confirmThen(isYes, "Install dependencies now?", () =>
|
|
769
|
+
installDependencies(packageManager, projectDir),
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
if (!args["no-git"]) {
|
|
773
|
+
await confirmThen(isYes, "Initialize a git repository?", () =>
|
|
774
|
+
initGitRepo(projectDir),
|
|
775
|
+
);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
const nextSteps =
|
|
779
|
+
framework === "docusaurus"
|
|
780
|
+
? ` 2. ${packageManager} run doc\n 3. ${packageManager} start`
|
|
781
|
+
: ` 2. ${packageManager} run dev`;
|
|
782
|
+
prompts.outro(`
|
|
783
|
+
Next steps:
|
|
784
|
+
1. cd ${projectDir}
|
|
785
|
+
${nextSteps}
|
|
786
|
+
|
|
787
|
+
Documentation: https://graphql-markdown.dev
|
|
788
|
+
`);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
async function scaffold(args, tempDir) {
|
|
792
|
+
const framework = await resolveFramework(args);
|
|
793
|
+
const projectDir = await resolveProjectDir(args);
|
|
794
|
+
const schemaPath = await resolveSchemaPath(args);
|
|
795
|
+
const loader = await resolveLoader(schemaPath);
|
|
796
|
+
const packageManager = await resolvePackageManager(args);
|
|
797
|
+
const { title, color } = await promptCustomization(
|
|
798
|
+
args,
|
|
799
|
+
framework === "docusaurus",
|
|
800
|
+
);
|
|
801
|
+
|
|
802
|
+
applyTemplate(tempDir, {
|
|
803
|
+
framework,
|
|
804
|
+
projectDir,
|
|
805
|
+
schemaPath,
|
|
806
|
+
loader,
|
|
807
|
+
title,
|
|
808
|
+
color,
|
|
809
|
+
});
|
|
810
|
+
moveIntoPlace(tempDir, projectDir);
|
|
811
|
+
prompts.log.success("Project created successfully!");
|
|
812
|
+
|
|
813
|
+
await finalize(args, { projectDir, packageManager, framework });
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* Run the scaffolder; resolves to the process exit code (never exits itself).
|
|
818
|
+
*/
|
|
819
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
820
|
+
prompts.intro(`✨ Welcome to GraphQL Markdown Docs`);
|
|
821
|
+
const args = parseCliArgs(argv);
|
|
822
|
+
|
|
823
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "gqlmd-"));
|
|
824
|
+
try {
|
|
825
|
+
await scaffold(args, tempDir);
|
|
826
|
+
return 0;
|
|
827
|
+
} catch (error) {
|
|
828
|
+
if (error instanceof CliExit) return error.code;
|
|
829
|
+
throw error;
|
|
830
|
+
} finally {
|
|
831
|
+
if (fs.existsSync(tempDir)) {
|
|
832
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** Run main(), converting unexpected errors into a logged exit code of 1. */
|
|
838
|
+
export async function run(argv = process.argv.slice(2)) {
|
|
839
|
+
try {
|
|
840
|
+
return await main(argv);
|
|
841
|
+
} catch (error) {
|
|
842
|
+
prompts.log.error(error.message);
|
|
843
|
+
return 1;
|
|
844
|
+
}
|
|
845
|
+
}
|