create-graphql-markdown-docs 0.1.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -26
- package/lib/create.mjs +525 -670
- package/lib/frameworks/docusaurus.mjs +66 -0
- package/lib/frameworks/index.mjs +66 -0
- package/lib/frameworks/links.mjs +102 -0
- package/lib/frameworks/markdown.mjs +75 -0
- package/lib/frameworks/nuxt.mjs +266 -0
- package/lib/frameworks/presets.mjs +133 -0
- package/lib/helpers.mjs +83 -0
- package/lib/project.mjs +137 -0
- package/lib/rewrites/graphqlrc.mjs +61 -0
- package/lib/rewrites/lines.mjs +18 -0
- package/lib/schema.mjs +102 -0
- package/lib/target.mjs +95 -0
- package/lib/tasks.mjs +146 -0
- package/lib/telemetry.mjs +46 -0
- package/lib/wire/deps.mjs +38 -0
- package/lib/wire/plan.mjs +259 -0
- package/lib/wire/steps.mjs +359 -0
- package/lib/wire/yaml.mjs +93 -0
- package/package.json +5 -4
- package/templates/docusaurus/gitignore +20 -0
- package/templates/docusaurus/package.json +1 -1
- package/templates/markdown/.graphqlrc +9 -0
- package/templates/markdown/README.md +13 -0
- package/templates/markdown/docs/.gitkeep +0 -0
- package/templates/markdown/gitignore +1 -0
- package/templates/markdown/package.json +13 -0
- package/templates/markdown/schema/example.graphql +55 -0
- package/templates/nuxt/gitignore +30 -0
- package/templates/nuxt/package.json +2 -2
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire-only framework descriptors (no `scaffold` key): these presets are
|
|
3
|
+
* referenced by the wire mode but are not scaffolded by this package.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Astro Starlight preset. */
|
|
7
|
+
export const starlight = {
|
|
8
|
+
id: "starlight",
|
|
9
|
+
name: "Astro Starlight",
|
|
10
|
+
label: "Astro Starlight",
|
|
11
|
+
formatter: "@graphql-markdown/formatters/starlight",
|
|
12
|
+
createCommand: "npm create astro@latest -- --template starlight",
|
|
13
|
+
detect: ["@astrojs/starlight"],
|
|
14
|
+
links: "absolute",
|
|
15
|
+
contentRoot: "src/content/docs",
|
|
16
|
+
contentRoute: "/",
|
|
17
|
+
outputHint: "Astro Starlight reads content from src/content/docs/",
|
|
18
|
+
nextSteps: ({ outputDir }) =>
|
|
19
|
+
`Add a sidebar group in astro.config.*: { label: 'API', autogenerate: { directory: '${outputDir}' } }.`,
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** Fumadocs preset. */
|
|
23
|
+
export const fumadocs = {
|
|
24
|
+
id: "fumadocs",
|
|
25
|
+
name: "Fumadocs",
|
|
26
|
+
label: "Fumadocs",
|
|
27
|
+
formatter: "@graphql-markdown/formatters/fumadocs",
|
|
28
|
+
createCommand: "npm create fumadocs-app@latest",
|
|
29
|
+
detect: ["fumadocs-core", "fumadocs-ui"],
|
|
30
|
+
links: "router",
|
|
31
|
+
contentRoot: "content/docs",
|
|
32
|
+
contentRoute: "/docs",
|
|
33
|
+
outputHint: "Fumadocs reads content from content/docs/",
|
|
34
|
+
nextSteps: ({ outputDir }) =>
|
|
35
|
+
`Add the folder to \`pages\` in the parent meta.json of \`${outputDir}\` (or let Fumadocs list it).`,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Vocs preset. */
|
|
39
|
+
export const vocs = {
|
|
40
|
+
id: "vocs",
|
|
41
|
+
name: "Vocs",
|
|
42
|
+
label: "Vocs",
|
|
43
|
+
formatter: "@graphql-markdown/formatters/vocs",
|
|
44
|
+
createCommand: "npm create vocs@latest",
|
|
45
|
+
detect: ["vocs"],
|
|
46
|
+
links: "router",
|
|
47
|
+
contentRoot: "docs/pages",
|
|
48
|
+
contentRoute: "/",
|
|
49
|
+
outputHint: "Vocs reads content from docs/pages/",
|
|
50
|
+
nextSteps: ({ route }) =>
|
|
51
|
+
`Add a sidebar entry in vocs.config.* linking to \`${route}\`.`,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** HonKit preset. */
|
|
55
|
+
export const honkit = {
|
|
56
|
+
id: "honkit",
|
|
57
|
+
name: "HonKit",
|
|
58
|
+
label: "HonKit",
|
|
59
|
+
formatter: "@graphql-markdown/formatters/honkit",
|
|
60
|
+
createCommand: "npx honkit init",
|
|
61
|
+
detect: ["honkit"],
|
|
62
|
+
links: "absolute",
|
|
63
|
+
contentRoot: ".",
|
|
64
|
+
contentRoute: "/",
|
|
65
|
+
outputHint: "HonKit reads content from the project root",
|
|
66
|
+
nextSteps: () => "List the generated pages in SUMMARY.md.",
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Hugo preset. */
|
|
70
|
+
export const hugo = {
|
|
71
|
+
id: "hugo",
|
|
72
|
+
name: "Hugo",
|
|
73
|
+
label: "Hugo",
|
|
74
|
+
formatter: "@graphql-markdown/formatters/hugo",
|
|
75
|
+
createCommand: "hugo new site <dir>",
|
|
76
|
+
detect: ["hugo-bin", "hugo-extended"],
|
|
77
|
+
links: "absolute",
|
|
78
|
+
contentRoot: "content",
|
|
79
|
+
contentRoute: "/",
|
|
80
|
+
outputHint: "Hugo reads content from content/",
|
|
81
|
+
nextSteps: ({ route }) =>
|
|
82
|
+
`Add a menu entry in your Hugo config pointing to \`${route}\`.`,
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/** MkDocs preset. */
|
|
86
|
+
export const mkdocs = {
|
|
87
|
+
id: "mkdocs",
|
|
88
|
+
name: "MkDocs",
|
|
89
|
+
label: "MkDocs",
|
|
90
|
+
formatter: "@graphql-markdown/formatters/mkdocs",
|
|
91
|
+
createCommand: "mkdocs new <dir>",
|
|
92
|
+
links: "relative",
|
|
93
|
+
contentRoot: "docs",
|
|
94
|
+
outputHint: "MkDocs reads content from docs/",
|
|
95
|
+
nextSteps: ({ outputDir }) =>
|
|
96
|
+
`Add \`${outputDir}\` to \`nav\` in mkdocs.yml (or omit \`nav\` to list pages automatically).`,
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** DocFX preset. */
|
|
100
|
+
export const docfx = {
|
|
101
|
+
id: "docfx",
|
|
102
|
+
name: "DocFX",
|
|
103
|
+
label: "DocFX",
|
|
104
|
+
formatter: "@graphql-markdown/formatters/docfx",
|
|
105
|
+
createCommand: "docfx init",
|
|
106
|
+
links: "relative",
|
|
107
|
+
contentRoot: "docs",
|
|
108
|
+
outputHint: "DocFX reads content from docs/",
|
|
109
|
+
nextSteps: ({ outputDir }) => `Add \`${outputDir}\` to toc.yml.`,
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** mdBook preset. */
|
|
113
|
+
export const mdbook = {
|
|
114
|
+
id: "mdbook",
|
|
115
|
+
name: "mdBook",
|
|
116
|
+
label: "mdBook",
|
|
117
|
+
formatter: "@graphql-markdown/formatters/mdbook",
|
|
118
|
+
createCommand: "mdbook init <dir>",
|
|
119
|
+
links: "relative",
|
|
120
|
+
contentRoot: "src",
|
|
121
|
+
outputHint: "mdBook reads content from src/",
|
|
122
|
+
nextSteps: () =>
|
|
123
|
+
"List the generated pages in src/SUMMARY.md — mdBook only builds listed pages.",
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** Generic Markdown fallback (no formatter preset). */
|
|
127
|
+
export const generic = {
|
|
128
|
+
id: "generic",
|
|
129
|
+
name: "Other / generic Markdown",
|
|
130
|
+
label: "Other / generic Markdown",
|
|
131
|
+
nextSteps: ({ outputDir }) =>
|
|
132
|
+
`Point your site navigation at \`${outputDir}\`. Manual wiring guide: https://graphql-markdown.dev`,
|
|
133
|
+
};
|
package/lib/helpers.mjs
ADDED
|
@@ -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 { SUPPORTED_PACKAGE_MANAGERS } 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();
|
|
66
|
+
if (agent && SUPPORTED_PACKAGE_MANAGERS.includes(agent)) return agent;
|
|
67
|
+
const detected = await detectPackageManager({ cwd });
|
|
68
|
+
if (detected?.name && SUPPORTED_PACKAGE_MANAGERS.includes(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
|
+
}
|
package/lib/project.mjs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
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(
|
|
103
|
+
path.join(templatesRoot, fw.scaffold.template ?? framework),
|
|
104
|
+
tempDir,
|
|
105
|
+
[/^node_modules$/, ...fw.scaffold.copyExcludes],
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
// npm strips `.gitignore` from published tarballs, so templates ship it as
|
|
109
|
+
// `gitignore` and it is renamed back here.
|
|
110
|
+
const gitignore = path.join(tempDir, "gitignore");
|
|
111
|
+
if (fs.existsSync(gitignore)) {
|
|
112
|
+
fs.renameSync(gitignore, path.join(tempDir, ".gitignore"));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const schemaRef = placeSchema(tempDir, projectDir, schemaPath);
|
|
116
|
+
|
|
117
|
+
fw.scaffold.apply(tempDir, { schemaRef, schemaPath, loader, title, color });
|
|
118
|
+
|
|
119
|
+
writePackageJson(tempDir, projectDir, loader);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function moveIntoPlace(tempDir, projectDir) {
|
|
123
|
+
if (fs.existsSync(projectDir)) {
|
|
124
|
+
// Existing (empty) target, possibly the cwd: copy into it rather than
|
|
125
|
+
// replacing it, so the directory itself (and its inode) is preserved.
|
|
126
|
+
fs.cpSync(tempDir, projectDir, { recursive: true });
|
|
127
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
fs.renameSync(tempDir, projectDir);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
if (err.code !== "EXDEV") throw err;
|
|
134
|
+
// temp dir is on another filesystem; the caller removes it afterwards
|
|
135
|
+
fs.cpSync(tempDir, projectDir, { recursive: true });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -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
|
+
}
|