@metamask-previews/platform-api-docs 0.0.0-preview-e15374a5d → 0.0.0-preview-a3545aef8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +6 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.mjs +7 -2
- package/dist/cli.mjs.map +1 -1
- package/dist/generate.cjs +29 -8
- package/dist/generate.cjs.map +1 -1
- package/dist/generate.d.cts +9 -0
- package/dist/generate.d.cts.map +1 -1
- package/dist/generate.d.mts +9 -0
- package/dist/generate.d.mts.map +1 -1
- package/dist/generate.mjs +27 -7
- package/dist/generate.mjs.map +1 -1
- package/package.json +1 -1
- package/site/docusaurus.config.ts +7 -2
package/dist/cli.cjs
CHANGED
|
@@ -49,7 +49,8 @@ function resolveDocusaurus() {
|
|
|
49
49
|
* @param command - The docusaurus command (start, build, serve).
|
|
50
50
|
* @param cwd - The site directory.
|
|
51
51
|
* @param extraEnv - Extra environment variables passed through to the
|
|
52
|
-
* Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA
|
|
52
|
+
* Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`,
|
|
53
|
+
* `DOCS_REPO_URL`).
|
|
53
54
|
*/
|
|
54
55
|
async function runDocusaurus(command, cwd, extraEnv = {}) {
|
|
55
56
|
await (0, execa_1.default)(resolveDocusaurus(), [command], {
|
|
@@ -167,6 +168,7 @@ async function main() {
|
|
|
167
168
|
? argv['project-label']
|
|
168
169
|
: null;
|
|
169
170
|
const commitSha = await resolveCommitSha(resolvedProjectPath);
|
|
171
|
+
const repoUrl = await (0, generate_1.resolveRepoUrl)(resolvedProjectPath);
|
|
170
172
|
// Step 1: Generate docs
|
|
171
173
|
await (0, generate_1.generate)({
|
|
172
174
|
projectPath: resolvedProjectPath,
|
|
@@ -189,6 +191,9 @@ async function main() {
|
|
|
189
191
|
if (commitSha) {
|
|
190
192
|
docusaurusEnv.DOCS_COMMIT_SHA = commitSha;
|
|
191
193
|
}
|
|
194
|
+
if (repoUrl) {
|
|
195
|
+
docusaurusEnv.DOCS_REPO_URL = repoUrl;
|
|
196
|
+
}
|
|
192
197
|
if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {
|
|
193
198
|
docusaurusEnv.DOCS_URL = argv['site-url'];
|
|
194
199
|
}
|
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.cjs","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,2DAA0B;AAC1B,qDAAuC;AACvC,gDAAkC;AAClC,0DAAiC;AACjC,kDAA0B;AAE1B,6CAAsC;AAEtC;;;;;;GAMG;AACH,SAAS,iBAAiB;IACxB,OAAO,IAAA,mBAAQ,EAAC,SAAS,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,aAAa,CAC1B,OAAe,EACf,GAAW,EACX,WAAmC,EAAE;IAErC,MAAM,IAAA,eAAK,EAAC,iBAAiB,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE;QAC1C,GAAG;QACH,KAAK,EAAE,SAAS;QAChB,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,QAAQ,EAAE;KACrC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;;GASG;AACH,KAAK,UAAU,SAAS,CAAC,MAAc;IACrC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACtD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC,CAAC;IAEhE,OAAO,CAAC,GAAG,CAAC,mCAAmC,MAAM,KAAK,CAAC,CAAC;IAE5D,uEAA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,CAAC;QAC5C,CAAC;QACD,IAAI,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxE,aAAa,CAAC,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;QAC5C,CAAC;QACD,IACE,OAAO,IAAI,CAAC,eAAe,CAAC,KAAK,QAAQ;YACzC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,GAAG,CAAC,EAChC,CAAC;YACD,aAAa,CAAC,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;QACtD,CAAC;QAED,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;YACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;QACjE,CAAC;aAAM,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;YACzC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YAE/D,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;gBACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YACjE,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACrB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport execa from 'execa';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport npmWhich from 'npm-which';\nimport yargs from 'yargs';\n\nimport { generate } from './generate';\n\n/**\n * Locate the Docusaurus binary in this package's `node_modules/.bin`. Using\n * `npm-which` lets the lookup track wherever the installed Docusaurus puts\n * its binary, so a future Docusaurus upgrade can't break this path.\n *\n * @returns Absolute path to the `docusaurus` executable.\n */\nfunction resolveDocusaurus(): string {\n return npmWhich(__dirname).sync('docusaurus');\n}\n\n/**\n * Run a Docusaurus command.\n *\n * @param command - The docusaurus command (start, build, serve).\n * @param cwd - The site directory.\n * @param extraEnv - Extra environment variables passed through to the\n * Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`).\n */\nasync function runDocusaurus(\n command: string,\n cwd: string,\n extraEnv: Record<string, string> = {},\n): Promise<void> {\n await execa(resolveDocusaurus(), [command], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, ...extraEnv },\n });\n}\n\n/**\n * Copy site files into the output directory, skipping `node_modules`, `docs`,\n * and `tsconfig.json`. `docs` is owned by the doc generator and shouldn't be\n * carried over from the source `site/` directory. `tsconfig.json` extends the\n * monorepo's `tsconfig.base.json` via a relative path that only resolves from\n * the source location — it's there for IDE / lint inheritance, not for\n * Docusaurus, which uses `jiti` and doesn't consult the tsconfig at runtime.\n *\n * @param outDir - The output directory to set up.\n */\nasync function setupSite(outDir: string): Promise<void> {\n const siteDir = path.resolve(__dirname, '..', 'site');\n const skip = new Set(['node_modules', 'docs', 'tsconfig.json']);\n\n console.log(`\\nSetting up Docusaurus site in ${outDir}...`);\n\n // `fs.cp` has been available since Node 16.7 and only got the \"stable\"\n // marker in 22.3 — it's functional throughout our supported Node range\n // (`^18.18 || >=20`), even though the linter flags the older versions.\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n await fs.cp(siteDir, outDir, {\n recursive: true,\n filter: (source) => !skip.has(path.basename(source)),\n });\n\n // Write a minimal package.json so Docusaurus doesn't warn about a missing one\n const pkgJsonPath = path.join(outDir, 'package.json');\n try {\n await fs.access(pkgJsonPath);\n } catch {\n await fs.writeFile(\n pkgJsonPath,\n JSON.stringify(\n { name: 'platform-api-docs-site', private: true },\n null,\n 2,\n ),\n );\n }\n}\n\n/**\n * Resolve the short Git commit SHA the docs are being generated from.\n * Returns null when the project isn't a git repo or git isn't available.\n *\n * @param projectPath - The project root path.\n * @returns The short SHA, or null on failure.\n */\nasync function resolveCommitSha(projectPath: string): Promise<string | null> {\n try {\n const { stdout } = await execa('git', ['rev-parse', '--short', 'HEAD'], {\n cwd: projectPath,\n });\n const trimmed = stdout.trim();\n return trimmed.length > 0 ? trimmed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Main CLI entry point.\n */\nasync function main(): Promise<void> {\n const argv = await yargs(process.argv.slice(2))\n .command(\n '$0 [project-path]',\n 'Produces documentation for the platform API, the set of actions and events available in clients through the message bus.',\n (yargsInstance) => {\n yargsInstance.positional('project-path', {\n type: 'string',\n description: 'Path to the project to scan',\n default: '.',\n });\n },\n )\n .option('build', {\n type: 'boolean',\n description:\n 'Generate platform API docs and build a production-ready site',\n default: false,\n })\n .option('serve', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a production-ready site',\n default: false,\n })\n .option('dev', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a development-only site',\n default: false,\n })\n .option('scan-dir', {\n type: 'string',\n array: true,\n description:\n 'Additional directories within the project to scan for messenger actions and events (note: may be specified multiple times)',\n default: [] as string[],\n })\n .option('output', {\n type: 'string',\n description: 'Output directory',\n })\n .option('project-label', {\n type: 'string',\n description:\n 'Short label identifying the project (e.g. \"Core\", \"Extension\") — stamped on the site title and headings',\n })\n .option('site-url', {\n type: 'string',\n description:\n 'Absolute URL the built site will be served from, e.g. https://metamask.github.io',\n })\n .option('site-base-url', {\n type: 'string',\n description:\n 'Path prefix the built site will be served under, e.g. /core/platform-api/',\n })\n .help().argv;\n\n const projectPathArg = argv['project-path'];\n const resolvedProjectPath = path.resolve(\n typeof projectPathArg === 'string' ? projectPathArg : '.',\n );\n const resolvedOutputDir = path.resolve(\n argv.output ?? path.join(resolvedProjectPath, '.platform-api-docs'),\n );\n const scanDirs = ['src', ...argv['scan-dir']].filter(\n (dir, index, dirs) => dirs.indexOf(dir) === index,\n );\n const projectLabel =\n typeof argv['project-label'] === 'string' &&\n argv['project-label'].length > 0\n ? argv['project-label']\n : null;\n const commitSha = await resolveCommitSha(resolvedProjectPath);\n\n // Step 1: Generate docs\n await generate({\n projectPath: resolvedProjectPath,\n outputDir: resolvedOutputDir,\n scanDirs,\n projectLabel,\n commitSha,\n });\n\n // Step 2: If --build, --serve, or --dev, set up and run Docusaurus\n if (argv.build || argv.serve || argv.dev) {\n await setupSite(resolvedOutputDir);\n\n // Translate CLI flags into the environment variables Docusaurus's\n // config reads. Keeping the CLI surface flag-only means consumers\n // (workflow files, package.json scripts) don't have to know how the\n // values are plumbed through to Docusaurus.\n const docusaurusEnv: Record<string, string> = {};\n if (projectLabel) {\n docusaurusEnv.DOCS_PROJECT_LABEL = projectLabel;\n }\n if (commitSha) {\n docusaurusEnv.DOCS_COMMIT_SHA = commitSha;\n }\n if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {\n docusaurusEnv.DOCS_URL = argv['site-url'];\n }\n if (\n typeof argv['site-base-url'] === 'string' &&\n argv['site-base-url'].length > 0\n ) {\n docusaurusEnv.DOCS_BASE_URL = argv['site-base-url'];\n }\n\n if (argv.dev) {\n console.log('\\nStarting dev server...');\n await runDocusaurus('start', resolvedOutputDir, docusaurusEnv);\n } else if (argv.build || argv.serve) {\n console.log('\\nBuilding static site...');\n await runDocusaurus('build', resolvedOutputDir, docusaurusEnv);\n\n if (argv.serve) {\n console.log('\\nServing static site...');\n await runDocusaurus('serve', resolvedOutputDir, docusaurusEnv);\n }\n }\n }\n}\n\nmain().catch((error) => {\n console.error(error);\n process.exitCode = 1;\n});\n"]}
|
|
1
|
+
{"version":3,"file":"cli.cjs","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;;;;;;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E,OAAO,IAAI,CAAC,eAAe,CAAC,KAAK,QAAQ;YACzC,IAAI,CAAC,eAAe,CAAC,CAAC,MAAM,GAAG,CAAC,EAChC,CAAC;YACD,aAAa,CAAC,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;QACtD,CAAC;QAED,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;YACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;QACjE,CAAC;aAAM,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;YACzC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YAE/D,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;gBACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YACjE,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACrB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport execa from 'execa';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport npmWhich from 'npm-which';\nimport yargs from 'yargs';\n\nimport { generate, resolveRepoUrl } from './generate';\n\n/**\n * Locate the Docusaurus binary in this package's `node_modules/.bin`. Using\n * `npm-which` lets the lookup track wherever the installed Docusaurus puts\n * its binary, so a future Docusaurus upgrade can't break this path.\n *\n * @returns Absolute path to the `docusaurus` executable.\n */\nfunction resolveDocusaurus(): string {\n return npmWhich(__dirname).sync('docusaurus');\n}\n\n/**\n * Run a Docusaurus command.\n *\n * @param command - The docusaurus command (start, build, serve).\n * @param cwd - The site directory.\n * @param extraEnv - Extra environment variables passed through to the\n * Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`,\n * `DOCS_REPO_URL`).\n */\nasync function runDocusaurus(\n command: string,\n cwd: string,\n extraEnv: Record<string, string> = {},\n): Promise<void> {\n await execa(resolveDocusaurus(), [command], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, ...extraEnv },\n });\n}\n\n/**\n * Copy site files into the output directory, skipping `node_modules`, `docs`,\n * and `tsconfig.json`. `docs` is owned by the doc generator and shouldn't be\n * carried over from the source `site/` directory. `tsconfig.json` extends the\n * monorepo's `tsconfig.base.json` via a relative path that only resolves from\n * the source location — it's there for IDE / lint inheritance, not for\n * Docusaurus, which uses `jiti` and doesn't consult the tsconfig at runtime.\n *\n * @param outDir - The output directory to set up.\n */\nasync function setupSite(outDir: string): Promise<void> {\n const siteDir = path.resolve(__dirname, '..', 'site');\n const skip = new Set(['node_modules', 'docs', 'tsconfig.json']);\n\n console.log(`\\nSetting up Docusaurus site in ${outDir}...`);\n\n // `fs.cp` has been available since Node 16.7 and only got the \"stable\"\n // marker in 22.3 — it's functional throughout our supported Node range\n // (`^18.18 || >=20`), even though the linter flags the older versions.\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n await fs.cp(siteDir, outDir, {\n recursive: true,\n filter: (source) => !skip.has(path.basename(source)),\n });\n\n // Write a minimal package.json so Docusaurus doesn't warn about a missing one\n const pkgJsonPath = path.join(outDir, 'package.json');\n try {\n await fs.access(pkgJsonPath);\n } catch {\n await fs.writeFile(\n pkgJsonPath,\n JSON.stringify(\n { name: 'platform-api-docs-site', private: true },\n null,\n 2,\n ),\n );\n }\n}\n\n/**\n * Resolve the short Git commit SHA the docs are being generated from.\n * Returns null when the project isn't a git repo or git isn't available.\n *\n * @param projectPath - The project root path.\n * @returns The short SHA, or null on failure.\n */\nasync function resolveCommitSha(projectPath: string): Promise<string | null> {\n try {\n const { stdout } = await execa('git', ['rev-parse', '--short', 'HEAD'], {\n cwd: projectPath,\n });\n const trimmed = stdout.trim();\n return trimmed.length > 0 ? trimmed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Main CLI entry point.\n */\nasync function main(): Promise<void> {\n const argv = await yargs(process.argv.slice(2))\n .command(\n '$0 [project-path]',\n 'Produces documentation for the platform API, the set of actions and events available in clients through the message bus.',\n (yargsInstance) => {\n yargsInstance.positional('project-path', {\n type: 'string',\n description: 'Path to the project to scan',\n default: '.',\n });\n },\n )\n .option('build', {\n type: 'boolean',\n description:\n 'Generate platform API docs and build a production-ready site',\n default: false,\n })\n .option('serve', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a production-ready site',\n default: false,\n })\n .option('dev', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a development-only site',\n default: false,\n })\n .option('scan-dir', {\n type: 'string',\n array: true,\n description:\n 'Additional directories within the project to scan for messenger actions and events (note: may be specified multiple times)',\n default: [] as string[],\n })\n .option('output', {\n type: 'string',\n description: 'Output directory',\n })\n .option('project-label', {\n type: 'string',\n description:\n 'Short label identifying the project (e.g. \"Core\", \"Extension\") — stamped on the site title and headings',\n })\n .option('site-url', {\n type: 'string',\n description:\n 'Absolute URL the built site will be served from, e.g. https://metamask.github.io',\n })\n .option('site-base-url', {\n type: 'string',\n description:\n 'Path prefix the built site will be served under, e.g. /core/platform-api/',\n })\n .help().argv;\n\n const projectPathArg = argv['project-path'];\n const resolvedProjectPath = path.resolve(\n typeof projectPathArg === 'string' ? projectPathArg : '.',\n );\n const resolvedOutputDir = path.resolve(\n argv.output ?? path.join(resolvedProjectPath, '.platform-api-docs'),\n );\n const scanDirs = ['src', ...argv['scan-dir']].filter(\n (dir, index, dirs) => dirs.indexOf(dir) === index,\n );\n const projectLabel =\n typeof argv['project-label'] === 'string' &&\n argv['project-label'].length > 0\n ? argv['project-label']\n : null;\n const commitSha = await resolveCommitSha(resolvedProjectPath);\n const repoUrl = await resolveRepoUrl(resolvedProjectPath);\n\n // Step 1: Generate docs\n await generate({\n projectPath: resolvedProjectPath,\n outputDir: resolvedOutputDir,\n scanDirs,\n projectLabel,\n commitSha,\n });\n\n // Step 2: If --build, --serve, or --dev, set up and run Docusaurus\n if (argv.build || argv.serve || argv.dev) {\n await setupSite(resolvedOutputDir);\n\n // Translate CLI flags into the environment variables Docusaurus's\n // config reads. Keeping the CLI surface flag-only means consumers\n // (workflow files, package.json scripts) don't have to know how the\n // values are plumbed through to Docusaurus.\n const docusaurusEnv: Record<string, string> = {};\n if (projectLabel) {\n docusaurusEnv.DOCS_PROJECT_LABEL = projectLabel;\n }\n if (commitSha) {\n docusaurusEnv.DOCS_COMMIT_SHA = commitSha;\n }\n if (repoUrl) {\n docusaurusEnv.DOCS_REPO_URL = repoUrl;\n }\n if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {\n docusaurusEnv.DOCS_URL = argv['site-url'];\n }\n if (\n typeof argv['site-base-url'] === 'string' &&\n argv['site-base-url'].length > 0\n ) {\n docusaurusEnv.DOCS_BASE_URL = argv['site-base-url'];\n }\n\n if (argv.dev) {\n console.log('\\nStarting dev server...');\n await runDocusaurus('start', resolvedOutputDir, docusaurusEnv);\n } else if (argv.build || argv.serve) {\n console.log('\\nBuilding static site...');\n await runDocusaurus('build', resolvedOutputDir, docusaurusEnv);\n\n if (argv.serve) {\n console.log('\\nServing static site...');\n await runDocusaurus('serve', resolvedOutputDir, docusaurusEnv);\n }\n }\n }\n}\n\nmain().catch((error) => {\n console.error(error);\n process.exitCode = 1;\n});\n"]}
|
package/dist/cli.mjs
CHANGED
|
@@ -30,7 +30,7 @@ import * as path from "node:path";
|
|
|
30
30
|
import $npmWhich from "npm-which";
|
|
31
31
|
const npmWhich = $importDefault($npmWhich);
|
|
32
32
|
import yargs from "yargs";
|
|
33
|
-
import { generate } from "./generate.mjs";
|
|
33
|
+
import { generate, resolveRepoUrl } from "./generate.mjs";
|
|
34
34
|
/**
|
|
35
35
|
* Locate the Docusaurus binary in this package's `node_modules/.bin`. Using
|
|
36
36
|
* `npm-which` lets the lookup track wherever the installed Docusaurus puts
|
|
@@ -47,7 +47,8 @@ function resolveDocusaurus() {
|
|
|
47
47
|
* @param command - The docusaurus command (start, build, serve).
|
|
48
48
|
* @param cwd - The site directory.
|
|
49
49
|
* @param extraEnv - Extra environment variables passed through to the
|
|
50
|
-
* Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA
|
|
50
|
+
* Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`,
|
|
51
|
+
* `DOCS_REPO_URL`).
|
|
51
52
|
*/
|
|
52
53
|
async function runDocusaurus(command, cwd, extraEnv = {}) {
|
|
53
54
|
await execa(resolveDocusaurus(), [command], {
|
|
@@ -165,6 +166,7 @@ async function main() {
|
|
|
165
166
|
? argv['project-label']
|
|
166
167
|
: null;
|
|
167
168
|
const commitSha = await resolveCommitSha(resolvedProjectPath);
|
|
169
|
+
const repoUrl = await resolveRepoUrl(resolvedProjectPath);
|
|
168
170
|
// Step 1: Generate docs
|
|
169
171
|
await generate({
|
|
170
172
|
projectPath: resolvedProjectPath,
|
|
@@ -187,6 +189,9 @@ async function main() {
|
|
|
187
189
|
if (commitSha) {
|
|
188
190
|
docusaurusEnv.DOCS_COMMIT_SHA = commitSha;
|
|
189
191
|
}
|
|
192
|
+
if (repoUrl) {
|
|
193
|
+
docusaurusEnv.DOCS_REPO_URL = repoUrl;
|
|
194
|
+
}
|
|
190
195
|
if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {
|
|
191
196
|
docusaurusEnv.DOCS_URL = argv['site-url'];
|
|
192
197
|
}
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"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,EAChC,CAAC;YACD,aAAa,CAAC,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;QACtD,CAAC;QAED,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;YACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;QACjE,CAAC;aAAM,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;YACzC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YAE/D,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;gBACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YACjE,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACrB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport execa from 'execa';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport npmWhich from 'npm-which';\nimport yargs from 'yargs';\n\nimport { generate } from './generate';\n\n/**\n * Locate the Docusaurus binary in this package's `node_modules/.bin`. Using\n * `npm-which` lets the lookup track wherever the installed Docusaurus puts\n * its binary, so a future Docusaurus upgrade can't break this path.\n *\n * @returns Absolute path to the `docusaurus` executable.\n */\nfunction resolveDocusaurus(): string {\n return npmWhich(__dirname).sync('docusaurus');\n}\n\n/**\n * Run a Docusaurus command.\n *\n * @param command - The docusaurus command (start, build, serve).\n * @param cwd - The site directory.\n * @param extraEnv - Extra environment variables passed through to the\n * Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`).\n */\nasync function runDocusaurus(\n command: string,\n cwd: string,\n extraEnv: Record<string, string> = {},\n): Promise<void> {\n await execa(resolveDocusaurus(), [command], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, ...extraEnv },\n });\n}\n\n/**\n * Copy site files into the output directory, skipping `node_modules`, `docs`,\n * and `tsconfig.json`. `docs` is owned by the doc generator and shouldn't be\n * carried over from the source `site/` directory. `tsconfig.json` extends the\n * monorepo's `tsconfig.base.json` via a relative path that only resolves from\n * the source location — it's there for IDE / lint inheritance, not for\n * Docusaurus, which uses `jiti` and doesn't consult the tsconfig at runtime.\n *\n * @param outDir - The output directory to set up.\n */\nasync function setupSite(outDir: string): Promise<void> {\n const siteDir = path.resolve(__dirname, '..', 'site');\n const skip = new Set(['node_modules', 'docs', 'tsconfig.json']);\n\n console.log(`\\nSetting up Docusaurus site in ${outDir}...`);\n\n // `fs.cp` has been available since Node 16.7 and only got the \"stable\"\n // marker in 22.3 — it's functional throughout our supported Node range\n // (`^18.18 || >=20`), even though the linter flags the older versions.\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n await fs.cp(siteDir, outDir, {\n recursive: true,\n filter: (source) => !skip.has(path.basename(source)),\n });\n\n // Write a minimal package.json so Docusaurus doesn't warn about a missing one\n const pkgJsonPath = path.join(outDir, 'package.json');\n try {\n await fs.access(pkgJsonPath);\n } catch {\n await fs.writeFile(\n pkgJsonPath,\n JSON.stringify(\n { name: 'platform-api-docs-site', private: true },\n null,\n 2,\n ),\n );\n }\n}\n\n/**\n * Resolve the short Git commit SHA the docs are being generated from.\n * Returns null when the project isn't a git repo or git isn't available.\n *\n * @param projectPath - The project root path.\n * @returns The short SHA, or null on failure.\n */\nasync function resolveCommitSha(projectPath: string): Promise<string | null> {\n try {\n const { stdout } = await execa('git', ['rev-parse', '--short', 'HEAD'], {\n cwd: projectPath,\n });\n const trimmed = stdout.trim();\n return trimmed.length > 0 ? trimmed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Main CLI entry point.\n */\nasync function main(): Promise<void> {\n const argv = await yargs(process.argv.slice(2))\n .command(\n '$0 [project-path]',\n 'Produces documentation for the platform API, the set of actions and events available in clients through the message bus.',\n (yargsInstance) => {\n yargsInstance.positional('project-path', {\n type: 'string',\n description: 'Path to the project to scan',\n default: '.',\n });\n },\n )\n .option('build', {\n type: 'boolean',\n description:\n 'Generate platform API docs and build a production-ready site',\n default: false,\n })\n .option('serve', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a production-ready site',\n default: false,\n })\n .option('dev', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a development-only site',\n default: false,\n })\n .option('scan-dir', {\n type: 'string',\n array: true,\n description:\n 'Additional directories within the project to scan for messenger actions and events (note: may be specified multiple times)',\n default: [] as string[],\n })\n .option('output', {\n type: 'string',\n description: 'Output directory',\n })\n .option('project-label', {\n type: 'string',\n description:\n 'Short label identifying the project (e.g. \"Core\", \"Extension\") — stamped on the site title and headings',\n })\n .option('site-url', {\n type: 'string',\n description:\n 'Absolute URL the built site will be served from, e.g. https://metamask.github.io',\n })\n .option('site-base-url', {\n type: 'string',\n description:\n 'Path prefix the built site will be served under, e.g. /core/platform-api/',\n })\n .help().argv;\n\n const projectPathArg = argv['project-path'];\n const resolvedProjectPath = path.resolve(\n typeof projectPathArg === 'string' ? projectPathArg : '.',\n );\n const resolvedOutputDir = path.resolve(\n argv.output ?? path.join(resolvedProjectPath, '.platform-api-docs'),\n );\n const scanDirs = ['src', ...argv['scan-dir']].filter(\n (dir, index, dirs) => dirs.indexOf(dir) === index,\n );\n const projectLabel =\n typeof argv['project-label'] === 'string' &&\n argv['project-label'].length > 0\n ? argv['project-label']\n : null;\n const commitSha = await resolveCommitSha(resolvedProjectPath);\n\n // Step 1: Generate docs\n await generate({\n projectPath: resolvedProjectPath,\n outputDir: resolvedOutputDir,\n scanDirs,\n projectLabel,\n commitSha,\n });\n\n // Step 2: If --build, --serve, or --dev, set up and run Docusaurus\n if (argv.build || argv.serve || argv.dev) {\n await setupSite(resolvedOutputDir);\n\n // Translate CLI flags into the environment variables Docusaurus's\n // config reads. Keeping the CLI surface flag-only means consumers\n // (workflow files, package.json scripts) don't have to know how the\n // values are plumbed through to Docusaurus.\n const docusaurusEnv: Record<string, string> = {};\n if (projectLabel) {\n docusaurusEnv.DOCS_PROJECT_LABEL = projectLabel;\n }\n if (commitSha) {\n docusaurusEnv.DOCS_COMMIT_SHA = commitSha;\n }\n if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {\n docusaurusEnv.DOCS_URL = argv['site-url'];\n }\n if (\n typeof argv['site-base-url'] === 'string' &&\n argv['site-base-url'].length > 0\n ) {\n docusaurusEnv.DOCS_BASE_URL = argv['site-base-url'];\n }\n\n if (argv.dev) {\n console.log('\\nStarting dev server...');\n await runDocusaurus('start', resolvedOutputDir, docusaurusEnv);\n } else if (argv.build || argv.serve) {\n console.log('\\nBuilding static site...');\n await runDocusaurus('build', resolvedOutputDir, docusaurusEnv);\n\n if (argv.serve) {\n console.log('\\nServing static site...');\n await runDocusaurus('serve', resolvedOutputDir, docusaurusEnv);\n }\n }\n }\n}\n\nmain().catch((error) => {\n console.error(error);\n process.exitCode = 1;\n});\n"]}
|
|
1
|
+
{"version":3,"file":"cli.mjs","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,MAAK,uBAAc;;AAC1B,OAAO,KAAK,EAAE,yBAAyB;AACvC,OAAO,KAAK,IAAI,kBAAkB;AAClC,OAAO,SAAQ,kBAAkB;;AACjC,OAAO,KAAK,cAAc;AAE1B,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,uBAAmB;AAEtD;;;;;;GAMG;AACH,SAAS,iBAAiB;IACxB,OAAO,QAAQ,6BAAW,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAChD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,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;QACjE,CAAC;aAAM,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;YACzC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YAE/D,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;gBACxC,MAAM,aAAa,CAAC,OAAO,EAAE,iBAAiB,EAAE,aAAa,CAAC,CAAC;YACjE,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACrB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport execa from 'execa';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport npmWhich from 'npm-which';\nimport yargs from 'yargs';\n\nimport { generate, resolveRepoUrl } from './generate';\n\n/**\n * Locate the Docusaurus binary in this package's `node_modules/.bin`. Using\n * `npm-which` lets the lookup track wherever the installed Docusaurus puts\n * its binary, so a future Docusaurus upgrade can't break this path.\n *\n * @returns Absolute path to the `docusaurus` executable.\n */\nfunction resolveDocusaurus(): string {\n return npmWhich(__dirname).sync('docusaurus');\n}\n\n/**\n * Run a Docusaurus command.\n *\n * @param command - The docusaurus command (start, build, serve).\n * @param cwd - The site directory.\n * @param extraEnv - Extra environment variables passed through to the\n * Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`,\n * `DOCS_REPO_URL`).\n */\nasync function runDocusaurus(\n command: string,\n cwd: string,\n extraEnv: Record<string, string> = {},\n): Promise<void> {\n await execa(resolveDocusaurus(), [command], {\n cwd,\n stdio: 'inherit',\n env: { ...process.env, ...extraEnv },\n });\n}\n\n/**\n * Copy site files into the output directory, skipping `node_modules`, `docs`,\n * and `tsconfig.json`. `docs` is owned by the doc generator and shouldn't be\n * carried over from the source `site/` directory. `tsconfig.json` extends the\n * monorepo's `tsconfig.base.json` via a relative path that only resolves from\n * the source location — it's there for IDE / lint inheritance, not for\n * Docusaurus, which uses `jiti` and doesn't consult the tsconfig at runtime.\n *\n * @param outDir - The output directory to set up.\n */\nasync function setupSite(outDir: string): Promise<void> {\n const siteDir = path.resolve(__dirname, '..', 'site');\n const skip = new Set(['node_modules', 'docs', 'tsconfig.json']);\n\n console.log(`\\nSetting up Docusaurus site in ${outDir}...`);\n\n // `fs.cp` has been available since Node 16.7 and only got the \"stable\"\n // marker in 22.3 — it's functional throughout our supported Node range\n // (`^18.18 || >=20`), even though the linter flags the older versions.\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n await fs.cp(siteDir, outDir, {\n recursive: true,\n filter: (source) => !skip.has(path.basename(source)),\n });\n\n // Write a minimal package.json so Docusaurus doesn't warn about a missing one\n const pkgJsonPath = path.join(outDir, 'package.json');\n try {\n await fs.access(pkgJsonPath);\n } catch {\n await fs.writeFile(\n pkgJsonPath,\n JSON.stringify(\n { name: 'platform-api-docs-site', private: true },\n null,\n 2,\n ),\n );\n }\n}\n\n/**\n * Resolve the short Git commit SHA the docs are being generated from.\n * Returns null when the project isn't a git repo or git isn't available.\n *\n * @param projectPath - The project root path.\n * @returns The short SHA, or null on failure.\n */\nasync function resolveCommitSha(projectPath: string): Promise<string | null> {\n try {\n const { stdout } = await execa('git', ['rev-parse', '--short', 'HEAD'], {\n cwd: projectPath,\n });\n const trimmed = stdout.trim();\n return trimmed.length > 0 ? trimmed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Main CLI entry point.\n */\nasync function main(): Promise<void> {\n const argv = await yargs(process.argv.slice(2))\n .command(\n '$0 [project-path]',\n 'Produces documentation for the platform API, the set of actions and events available in clients through the message bus.',\n (yargsInstance) => {\n yargsInstance.positional('project-path', {\n type: 'string',\n description: 'Path to the project to scan',\n default: '.',\n });\n },\n )\n .option('build', {\n type: 'boolean',\n description:\n 'Generate platform API docs and build a production-ready site',\n default: false,\n })\n .option('serve', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a production-ready site',\n default: false,\n })\n .option('dev', {\n type: 'boolean',\n description:\n 'Generate platform API docs and serve a development-only site',\n default: false,\n })\n .option('scan-dir', {\n type: 'string',\n array: true,\n description:\n 'Additional directories within the project to scan for messenger actions and events (note: may be specified multiple times)',\n default: [] as string[],\n })\n .option('output', {\n type: 'string',\n description: 'Output directory',\n })\n .option('project-label', {\n type: 'string',\n description:\n 'Short label identifying the project (e.g. \"Core\", \"Extension\") — stamped on the site title and headings',\n })\n .option('site-url', {\n type: 'string',\n description:\n 'Absolute URL the built site will be served from, e.g. https://metamask.github.io',\n })\n .option('site-base-url', {\n type: 'string',\n description:\n 'Path prefix the built site will be served under, e.g. /core/platform-api/',\n })\n .help().argv;\n\n const projectPathArg = argv['project-path'];\n const resolvedProjectPath = path.resolve(\n typeof projectPathArg === 'string' ? projectPathArg : '.',\n );\n const resolvedOutputDir = path.resolve(\n argv.output ?? path.join(resolvedProjectPath, '.platform-api-docs'),\n );\n const scanDirs = ['src', ...argv['scan-dir']].filter(\n (dir, index, dirs) => dirs.indexOf(dir) === index,\n );\n const projectLabel =\n typeof argv['project-label'] === 'string' &&\n argv['project-label'].length > 0\n ? argv['project-label']\n : null;\n const commitSha = await resolveCommitSha(resolvedProjectPath);\n const repoUrl = await resolveRepoUrl(resolvedProjectPath);\n\n // Step 1: Generate docs\n await generate({\n projectPath: resolvedProjectPath,\n outputDir: resolvedOutputDir,\n scanDirs,\n projectLabel,\n commitSha,\n });\n\n // Step 2: If --build, --serve, or --dev, set up and run Docusaurus\n if (argv.build || argv.serve || argv.dev) {\n await setupSite(resolvedOutputDir);\n\n // Translate CLI flags into the environment variables Docusaurus's\n // config reads. Keeping the CLI surface flag-only means consumers\n // (workflow files, package.json scripts) don't have to know how the\n // values are plumbed through to Docusaurus.\n const docusaurusEnv: Record<string, string> = {};\n if (projectLabel) {\n docusaurusEnv.DOCS_PROJECT_LABEL = projectLabel;\n }\n if (commitSha) {\n docusaurusEnv.DOCS_COMMIT_SHA = commitSha;\n }\n if (repoUrl) {\n docusaurusEnv.DOCS_REPO_URL = repoUrl;\n }\n if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {\n docusaurusEnv.DOCS_URL = argv['site-url'];\n }\n if (\n typeof argv['site-base-url'] === 'string' &&\n argv['site-base-url'].length > 0\n ) {\n docusaurusEnv.DOCS_BASE_URL = argv['site-base-url'];\n }\n\n if (argv.dev) {\n console.log('\\nStarting dev server...');\n await runDocusaurus('start', resolvedOutputDir, docusaurusEnv);\n } else if (argv.build || argv.serve) {\n console.log('\\nBuilding static site...');\n await runDocusaurus('build', resolvedOutputDir, docusaurusEnv);\n\n if (argv.serve) {\n console.log('\\nServing static site...');\n await runDocusaurus('serve', resolvedOutputDir, docusaurusEnv);\n }\n }\n }\n}\n\nmain().catch((error) => {\n console.error(error);\n process.exitCode = 1;\n});\n"]}
|
package/dist/generate.cjs
CHANGED
|
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.generate = void 0;
|
|
26
|
+
exports.generate = exports.resolveRepoUrl = void 0;
|
|
27
27
|
const node_1 = require("@metamask/utils/node");
|
|
28
28
|
const node_child_process_1 = require("node:child_process");
|
|
29
29
|
const fs = __importStar(require("node:fs/promises"));
|
|
@@ -78,13 +78,14 @@ async function resolveDefaultBranch(projectPath) {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
/**
|
|
81
|
-
* Resolve the GitHub
|
|
82
|
-
*
|
|
81
|
+
* Resolve the bare GitHub repository URL for a project by reading its
|
|
82
|
+
* `origin` remote.
|
|
83
83
|
*
|
|
84
84
|
* @param projectPath - Absolute path to the project root.
|
|
85
|
-
* @returns A
|
|
85
|
+
* @returns A URL like "https://github.com/Owner/Repo" or null when the remote
|
|
86
|
+
* isn't a GitHub URL or can't be read.
|
|
86
87
|
*/
|
|
87
|
-
async function
|
|
88
|
+
async function resolveRepoUrl(projectPath) {
|
|
88
89
|
try {
|
|
89
90
|
const { stdout: remoteRaw } = await execFileAsync('git', ['remote', 'get-url', 'origin'], { cwd: projectPath });
|
|
90
91
|
const remote = remoteRaw.trim();
|
|
@@ -94,13 +95,33 @@ async function resolveRepoBaseUrl(projectPath) {
|
|
|
94
95
|
if (!match) {
|
|
95
96
|
return null;
|
|
96
97
|
}
|
|
97
|
-
|
|
98
|
-
return `https://github.com/${match[1]}/blob/${branch}/`;
|
|
98
|
+
return `https://github.com/${match[1]}`;
|
|
99
99
|
}
|
|
100
100
|
catch {
|
|
101
101
|
return null;
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
+
exports.resolveRepoUrl = resolveRepoUrl;
|
|
105
|
+
/**
|
|
106
|
+
* Resolve the GitHub blob base URL used for per-line source links.
|
|
107
|
+
*
|
|
108
|
+
* Prefers the documented commit SHA when one is available so the links point
|
|
109
|
+
* at the exact revision the docs were generated from; falls back to the
|
|
110
|
+
* default branch otherwise.
|
|
111
|
+
*
|
|
112
|
+
* @param projectPath - Absolute path to the project root.
|
|
113
|
+
* @param commitSha - Optional commit SHA to use as the ref. When null, the
|
|
114
|
+
* default branch is used instead.
|
|
115
|
+
* @returns A base URL like "https://github.com/Owner/Repo/blob/<ref>/" or null.
|
|
116
|
+
*/
|
|
117
|
+
async function resolveRepoBaseUrl(projectPath, commitSha) {
|
|
118
|
+
const repoUrl = await resolveRepoUrl(projectPath);
|
|
119
|
+
if (!repoUrl) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
const ref = commitSha ?? (await resolveDefaultBranch(projectPath));
|
|
123
|
+
return `${repoUrl}/blob/${ref}/`;
|
|
124
|
+
}
|
|
104
125
|
/**
|
|
105
126
|
* Discover which configured source locations actually exist on disk.
|
|
106
127
|
*
|
|
@@ -352,7 +373,7 @@ async function generate(options) {
|
|
|
352
373
|
const allItems = await scanSources(projectPath, sources);
|
|
353
374
|
console.log(`Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`);
|
|
354
375
|
const namespaces = groupByNamespace(allItems);
|
|
355
|
-
const repoBaseUrl = await resolveRepoBaseUrl(projectPath);
|
|
376
|
+
const repoBaseUrl = await resolveRepoBaseUrl(projectPath, commitSha ?? null);
|
|
356
377
|
await writeOutput(namespaces, outputDir, repoBaseUrl, {
|
|
357
378
|
projectLabel,
|
|
358
379
|
commitSha,
|
package/dist/generate.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.cjs","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAuD;AACvD,2DAA8C;AAC9C,qDAAuC;AACvC,gDAAkC;AAClC,yCAAsC;AAGtC,+CAAwD;AACxD,iDAA8E;AAC9E,6CAIoB;AAGpB;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,IAA+B;IACzD,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,MAAM,eAAe,GAAG,IAAI,CAAC,UAAU;SACpC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;SACb,OAAO,CAAC,0BAA0B,EAAE,EAAE,CAAC;SACvC,WAAW,EAAE,CAAC;IACjB,MAAM,SAAS,GACb,eAAe,CAAC,MAAM,GAAG,CAAC;QAC1B,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,eAAe,CAAC;QACrD,CAAC,CAAC,CAAC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M,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,GAAG,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,cAAc,YAAY,EAAE,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAExD,OAAO;QACL,UAAU,EAAE,UAAU,CAAC,MAAM;QAC7B,OAAO,EAAE,YAAY;QACrB,MAAM,EAAE,WAAW;KACpB,CAAC;AACJ,CAAC;AAnDD,4BAmDC","sourcesContent":["import { directoryExists } from '@metamask/utils/node';\nimport { execFile } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Project } from 'ts-morph';\n\nimport { findDtsFiles, findTsFiles } from './discovery';\nimport { createExtractionProject, extractFromSourceFile } from './extraction';\nimport {\n generateIndexPage,\n generateNamespacePage,\n generateSidebars,\n} from './markdown';\nimport type { MessengerCapabilityPacket, NamespaceGroup } from './types';\n\n/**\n * Compute a deduplication score for a messenger item, preferring items with\n * JSDoc and from the \"home\" package whose name matches the namespace.\n *\n * @param item - The messenger item to score.\n * @returns A numeric score (higher is better).\n */\nfunction deduplicationScore(item: MessengerCapabilityPacket): number {\n const jsDocScore = item.jsDoc ? 2 : 0;\n const namespacePrefix = item.typeString\n .split(':')[0]\n .replace(/(?:Controller|Service)$/u, '')\n .toLowerCase();\n const homeScore =\n namespacePrefix.length > 0 &&\n item.sourceFile.toLowerCase().includes(namespacePrefix)\n ? 1\n : 0;\n return jsDocScore + homeScore;\n}\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Resolve the default branch of a project's `origin` remote by reading the\n * symbolic ref `refs/remotes/origin/HEAD`. Falls back to `main` if the\n * symbolic ref isn't set (e.g. in shallow CI clones).\n *\n * @param projectPath - Absolute path to the project root.\n * @returns The default branch name (e.g. \"main\", \"master\", \"develop\").\n */\nasync function resolveDefaultBranch(projectPath: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'],\n { cwd: projectPath },\n );\n // stdout looks like \"origin/main\"; strip the leading \"origin/\".\n const trimmed = stdout.trim();\n const slash = trimmed.indexOf('/');\n return slash === -1\n ? // istanbul ignore next: defensive — `symbolic-ref --short` always\n // returns `origin/<branch>` when the symbolic ref is set; this\n // fallback only matters if git's output format ever changes.\n trimmed || 'main'\n : trimmed.slice(slash + 1);\n } catch {\n return 'main';\n }\n}\n\n/**\n * Resolve the GitHub blob base URL for a project by reading its git remote\n * and default branch.\n *\n * @param projectPath - Absolute path to the project root.\n * @returns A base URL like \"https://github.com/Owner/Repo/blob/<branch>/\" or null.\n */\nasync function resolveRepoBaseUrl(projectPath: string): Promise<string | null> {\n try {\n const { stdout: remoteRaw } = await execFileAsync(\n 'git',\n ['remote', 'get-url', 'origin'],\n { cwd: projectPath },\n );\n\n const remote = remoteRaw.trim();\n\n // Parse owner/repo from SSH or HTTPS remote URLs\n // Handles aliases like github.com-Org used in SSH configs\n const match = remote.match(\n /github\\.com[^:/]*[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/u,\n );\n if (!match) {\n return null;\n }\n\n const branch = await resolveDefaultBranch(projectPath);\n return `https://github.com/${match[1]}/blob/${branch}/`;\n } catch {\n return null;\n }\n}\n\n/**\n * Options for the generate function.\n */\nexport type GenerateOptions = {\n /** Absolute path to the project to scan. */\n projectPath: string;\n /** Absolute path to the output directory for generated docs. */\n outputDir: string;\n /** Directories (relative to projectPath) to scan for .ts source files. */\n scanDirs: string[];\n /**\n * Short label identifying the project the docs were generated from (e.g.\n * \"Core\", \"Extension\"). Stamped in the index page title.\n */\n projectLabel?: string | null;\n /**\n * Git commit SHA the docs were generated from. Stamped in the index page\n * intro so engineers know how current the site is.\n */\n commitSha?: string | null;\n};\n\n/**\n * Result returned by the generate function.\n */\nexport type GenerateResult = {\n namespaces: number;\n actions: number;\n events: number;\n};\n\n/**\n * The set of directories available to scan for messenger types, resolved from\n * the project's filesystem layout.\n */\ntype ScanSources = {\n /** User-configured scan dirs that exist on disk (relative to projectPath). */\n scanDirs: string[];\n /** Absolute path to `packages/` if it exists, otherwise null. */\n packagesDir: string | null;\n /** Absolute path to `node_modules/@metamask/` if it exists, otherwise null. */\n nodeModulesDir: string | null;\n};\n\n/**\n * Discover which configured source locations actually exist on disk.\n *\n * @param projectPath - The project root path.\n * @param scanDirs - User-configured scan directories relative to projectPath.\n * @returns A ScanSources object describing the locations to scan.\n */\nasync function discoverScanSources(\n projectPath: string,\n scanDirs: string[],\n): Promise<ScanSources> {\n const existingScanDirs: string[] = [];\n for (const dir of scanDirs) {\n if (await directoryExists(path.join(projectPath, dir))) {\n existingScanDirs.push(dir);\n }\n }\n\n const packagesDir = path.join(projectPath, 'packages');\n const nodeModulesDir = path.join(projectPath, 'node_modules', '@metamask');\n\n return {\n scanDirs: existingScanDirs,\n packagesDir: (await directoryExists(packagesDir)) ? packagesDir : null,\n nodeModulesDir: (await directoryExists(nodeModulesDir))\n ? nodeModulesDir\n : null,\n };\n}\n\n/**\n * Log a human-readable description of which source locations will be scanned.\n *\n * @param sources - The resolved scan sources.\n */\nfunction logScanPlan(sources: ScanSources): void {\n const summary: string[] = [];\n for (const dir of sources.scanDirs) {\n summary.push(`${dir}/ (.ts)`);\n }\n if (sources.packagesDir) {\n summary.push('packages/*/src (.ts)');\n }\n if (sources.nodeModulesDir) {\n summary.push('node_modules/@metamask/*/dist (.d.cts)');\n }\n console.log(\n `Scanning ${summary.join(', ')} for Messenger action/event types...`,\n );\n}\n\n/**\n * Run extraction against every file in a single directory, logging and\n * swallowing per-file failures. All files are added to the shared `project`\n * up front so the type checker can resolve cross-file references when the\n * walker descends into imported types.\n *\n * @param project - The shared ts-morph project.\n * @param directory - The directory to scan.\n * @param projectPath - The project root, used for relative path display.\n * @param findFiles - The function used to enumerate files in the directory.\n * @returns The list of extracted messenger items.\n */\nasync function extractFromDirectory(\n project: Project,\n directory: string,\n projectPath: string,\n findFiles: (dir: string) => Promise<string[]>,\n): Promise<MessengerCapabilityPacket[]> {\n const items: MessengerCapabilityPacket[] = [];\n const files = await findFiles(directory);\n for (const file of files) {\n try {\n const sourceFile =\n project.getSourceFile(file) ?? project.addSourceFileAtPath(file);\n items.push(...extractFromSourceFile(sourceFile, projectPath));\n } catch (error) {\n console.warn(\n `Warning: failed to parse ${path.relative(projectPath, file)}`,\n );\n console.warn(error);\n }\n }\n return items;\n}\n\n/**\n * Enumerate the subdirectories of a parent directory that match the expected\n * layout (e.g., `packages/*/src` or `node_modules/@metamask/*/dist`), keeping\n * only those that actually exist.\n *\n * @param parentDir - The parent directory to enumerate.\n * @param subPath - The trailing path component appended to each entry.\n * @param includeSymlinks - Whether to include symbolic links (true for\n * node_modules where workspaces are symlinked).\n * @returns The list of absolute paths to existing target subdirectories.\n */\nasync function listTargetSubdirectories(\n parentDir: string,\n subPath: string,\n includeSymlinks: boolean,\n): Promise<string[]> {\n const entries = await fs.readdir(parentDir, { withFileTypes: true });\n const candidates = entries\n .filter(\n (entry) =>\n entry.isDirectory() || (includeSymlinks && entry.isSymbolicLink()),\n )\n .map((entry) => path.join(parentDir, entry.name, subPath));\n\n const existing: string[] = [];\n for (const candidate of candidates) {\n if (await directoryExists(candidate)) {\n existing.push(candidate);\n }\n }\n return existing;\n}\n\n/**\n * Scan every source location described by `sources` and return all extracted\n * messenger items. A single ts-morph Project is shared across every file so\n * the type checker can resolve cross-file references (e.g. a `*Messenger`\n * declaration in one file walking through an imported umbrella union into\n * an auto-generated `*-method-action-types.ts` sibling).\n *\n * @param projectPath - The project root path.\n * @param sources - The set of source locations to scan.\n * @returns A flat list of all extracted messenger items.\n */\nasync function scanSources(\n projectPath: string,\n sources: ScanSources,\n): Promise<MessengerCapabilityPacket[]> {\n const project = createExtractionProject();\n const allItems: MessengerCapabilityPacket[] = [];\n\n for (const dir of sources.scanDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n path.join(projectPath, dir),\n projectPath,\n findTsFiles,\n )),\n );\n }\n\n if (sources.packagesDir) {\n const srcDirs = await listTargetSubdirectories(\n sources.packagesDir,\n 'src',\n false,\n );\n for (const srcDir of srcDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n srcDir,\n projectPath,\n findTsFiles,\n )),\n );\n }\n }\n\n if (sources.nodeModulesDir) {\n const distDirs = await listTargetSubdirectories(\n sources.nodeModulesDir,\n 'dist',\n true,\n );\n for (const distDir of distDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n distDir,\n projectPath,\n findDtsFiles,\n )),\n );\n }\n }\n\n return allItems;\n}\n\n/**\n * Replace a previously-seen item in its existing namespace group with a\n * higher-scoring duplicate. Handles the case where the duplicate is a\n * different kind (action vs event) by moving it between lists.\n *\n * @param byNamespace - Map of namespace to its group.\n * @param previous - The previously stored item.\n * @param replacement - The new item to replace it with.\n */\nfunction replaceDuplicateInGroup(\n byNamespace: Map<string, NamespaceGroup>,\n previous: MessengerCapabilityPacket,\n replacement: MessengerCapabilityPacket,\n): void {\n const namespace = replacement.typeString.split(':')[0];\n const group = byNamespace.get(namespace);\n // istanbul ignore next: `previous` and `replacement` have the same\n // typeString, so they share a namespace, and we always insert the\n // namespace into `byNamespace` before recording the original entry.\n if (!group) {\n return;\n }\n const previousList =\n previous.kind === 'action' ? group.actions : group.events;\n const index = previousList.indexOf(previous);\n // istanbul ignore next: `previous` was added to its kind's list by\n // `groupByNamespace` before being recorded in `seen`, so it is always\n // present when we look it up here.\n if (index === -1) {\n return;\n }\n if (previous.kind === replacement.kind) {\n previousList[index] = replacement;\n } else {\n previousList.splice(index, 1);\n const newList =\n replacement.kind === 'action' ? group.actions : group.events;\n newList.push(replacement);\n }\n}\n\n/**\n * Group items by namespace, deduplicating duplicate typeStrings using\n * `deduplicationScore`. Returns groups sorted alphabetically by namespace,\n * with each group's items sorted alphabetically by typeString.\n *\n * @param items - The full list of extracted items.\n * @returns The deduplicated and sorted namespace groups.\n */\nfunction groupByNamespace(\n items: MessengerCapabilityPacket[],\n): NamespaceGroup[] {\n const byNamespace = new Map<string, NamespaceGroup>();\n const seen = new Map<string, MessengerCapabilityPacket>();\n\n for (const item of items) {\n const existing = seen.get(item.typeString);\n if (existing) {\n if (deduplicationScore(item) <= deduplicationScore(existing)) {\n continue;\n }\n replaceDuplicateInGroup(byNamespace, existing, item);\n seen.set(item.typeString, item);\n continue;\n }\n\n seen.set(item.typeString, item);\n const namespace = item.typeString.split(':')[0];\n let group = byNamespace.get(namespace);\n if (!group) {\n group = { namespace, actions: [], events: [] };\n byNamespace.set(namespace, group);\n }\n if (item.kind === 'action') {\n group.actions.push(item);\n } else {\n group.events.push(item);\n }\n }\n\n const namespaces = Array.from(byNamespace.values()).sort((a, b) =>\n a.namespace.localeCompare(b.namespace),\n );\n\n for (const ns of namespaces) {\n ns.actions.sort((a, b) => a.typeString.localeCompare(b.typeString));\n ns.events.sort((a, b) => a.typeString.localeCompare(b.typeString));\n }\n\n return namespaces;\n}\n\n/**\n * Write generated docs (namespace pages, index page, sidebars) to disk,\n * replacing any existing `docs/` directory.\n *\n * @param namespaces - The grouped namespaces to render.\n * @param outputDir - The root output directory.\n * @param repoBaseUrl - GitHub blob base URL for source links, or null.\n * @param indexOptions - Options stamped on the index page header.\n * @param indexOptions.projectLabel - Short label identifying the project.\n * @param indexOptions.commitSha - Git commit SHA the docs were generated from.\n * @returns Promise that resolves once all files are written.\n */\nasync function writeOutput(\n namespaces: NamespaceGroup[],\n outputDir: string,\n repoBaseUrl: string | null,\n indexOptions: {\n projectLabel?: string | null;\n commitSha?: string | null;\n },\n): Promise<void> {\n const docsDir = path.join(outputDir, 'docs');\n\n if (await directoryExists(docsDir)) {\n await fs.rm(docsDir, { recursive: true });\n }\n await fs.mkdir(docsDir, { recursive: true });\n\n for (const ns of namespaces) {\n const nsDir = path.join(docsDir, ns.namespace);\n await fs.mkdir(nsDir, { recursive: true });\n\n if (ns.actions.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'actions.md'),\n generateNamespacePage(ns, 'action', repoBaseUrl),\n );\n }\n\n if (ns.events.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'events.md'),\n generateNamespacePage(ns, 'event', repoBaseUrl),\n );\n }\n }\n\n await fs.writeFile(\n path.join(docsDir, 'index.md'),\n generateIndexPage(namespaces, indexOptions),\n );\n\n await fs.writeFile(\n path.join(outputDir, 'sidebars.ts'),\n generateSidebars(namespaces),\n );\n}\n\n/**\n * Scan a project for messenger action/event types and generate documentation.\n *\n * @param options - Generation options.\n * @returns A promise resolving to counts of generated namespaces, actions, and events.\n */\nexport async function generate(\n options: GenerateOptions,\n): Promise<GenerateResult> {\n const { projectPath, outputDir, scanDirs, projectLabel, commitSha } = options;\n\n const sources = await discoverScanSources(projectPath, scanDirs);\n\n if (\n sources.scanDirs.length === 0 &&\n !sources.packagesDir &&\n !sources.nodeModulesDir\n ) {\n throw new Error(\n `No scannable directories found in ${projectPath}. ` +\n `Looked for: ${scanDirs.join(', ')}, packages/, node_modules/@metamask/`,\n );\n }\n\n logScanPlan(sources);\n\n const allItems = await scanSources(projectPath, sources);\n console.log(\n `Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`,\n );\n\n const namespaces = groupByNamespace(allItems);\n const repoBaseUrl = await resolveRepoBaseUrl(projectPath);\n\n await writeOutput(namespaces, outputDir, repoBaseUrl, {\n projectLabel,\n commitSha,\n });\n\n const totalActions = namespaces.reduce(\n (sum, ns) => sum + ns.actions.length,\n 0,\n );\n const totalEvents = namespaces.reduce((sum, ns) => sum + ns.events.length, 0);\n\n console.log(\n `Generated docs for ${namespaces.length} ${namespaces.length === 1 ? 'namespace' : 'namespaces'}.`,\n );\n console.log(` Actions: ${totalActions}`);\n console.log(` Events: ${totalEvents}`);\n console.log(`Output: ${path.join(outputDir, 'docs')}/`);\n\n return {\n namespaces: namespaces.length,\n actions: totalActions,\n events: totalEvents,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generate.cjs","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAuD;AACvD,2DAA8C;AAC9C,qDAAuC;AACvC,gDAAkC;AAClC,yCAAsC;AAGtC,+CAAwD;AACxD,iDAA8E;AAC9E,6CAIoB;AAGpB;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,IAA+B;IACzD,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtC,MAAM,eAAe,GAAG,IAAI,CAAC,UAAU;SACpC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;SACb,OAAO,CAAC,0BAA0B,EAAE,EAAE,CAAC;SACvC,WAAW,EAAE,CAAC;IACjB,MAAM,SAAS,GACb,eAAe,CAAC,MAAM,GAAG,CAAC;QAC1B,IAAI,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,eAAe,CAAC;QACrD,CAAC,CAAC,CAAC;QACH,CAAC,CAAC,CAAC,CAAC;IACR,OAAO,UAAU,GAAG,SAAS,CAAC;AAChC,CAAC;AAED,MAAM,aAAa,GAAG,IAAA,qBAAS,EAAC,6BAAQ,CAAC,CAAC;AAE1C;;;;;;;GAOG;AACH,KAAK,UAAU,oBAAoB,CAAC,WAAmB;IACrD,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,aAAa,CACpC,KAAK,EACL,CAAC,cAAc,EAAE,SAAS,EAAE,0BAA0B,CAAC,EACvD,EAAE,GAAG,EAAE,WAAW,EAAE,CACrB,CAAC;QACF,gEAAgE;QAChE,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;QAC9B,MAAM,KAAK,GAAG,OAAO,CAAC,O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G,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAExD,OAAO;QACL,UAAU,EAAE,UAAU,CAAC,MAAM;QAC7B,OAAO,EAAE,YAAY;QACrB,MAAM,EAAE,WAAW;KACpB,CAAC;AACJ,CAAC;AAnDD,4BAmDC","sourcesContent":["import { directoryExists } from '@metamask/utils/node';\nimport { execFile } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Project } from 'ts-morph';\n\nimport { findDtsFiles, findTsFiles } from './discovery';\nimport { createExtractionProject, extractFromSourceFile } from './extraction';\nimport {\n generateIndexPage,\n generateNamespacePage,\n generateSidebars,\n} from './markdown';\nimport type { MessengerCapabilityPacket, NamespaceGroup } from './types';\n\n/**\n * Compute a deduplication score for a messenger item, preferring items with\n * JSDoc and from the \"home\" package whose name matches the namespace.\n *\n * @param item - The messenger item to score.\n * @returns A numeric score (higher is better).\n */\nfunction deduplicationScore(item: MessengerCapabilityPacket): number {\n const jsDocScore = item.jsDoc ? 2 : 0;\n const namespacePrefix = item.typeString\n .split(':')[0]\n .replace(/(?:Controller|Service)$/u, '')\n .toLowerCase();\n const homeScore =\n namespacePrefix.length > 0 &&\n item.sourceFile.toLowerCase().includes(namespacePrefix)\n ? 1\n : 0;\n return jsDocScore + homeScore;\n}\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Resolve the default branch of a project's `origin` remote by reading the\n * symbolic ref `refs/remotes/origin/HEAD`. Falls back to `main` if the\n * symbolic ref isn't set (e.g. in shallow CI clones).\n *\n * @param projectPath - Absolute path to the project root.\n * @returns The default branch name (e.g. \"main\", \"master\", \"develop\").\n */\nasync function resolveDefaultBranch(projectPath: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'],\n { cwd: projectPath },\n );\n // stdout looks like \"origin/main\"; strip the leading \"origin/\".\n const trimmed = stdout.trim();\n const slash = trimmed.indexOf('/');\n return slash === -1\n ? // istanbul ignore next: defensive — `symbolic-ref --short` always\n // returns `origin/<branch>` when the symbolic ref is set; this\n // fallback only matters if git's output format ever changes.\n trimmed || 'main'\n : trimmed.slice(slash + 1);\n } catch {\n return 'main';\n }\n}\n\n/**\n * Resolve the bare GitHub repository URL for a project by reading its\n * `origin` remote.\n *\n * @param projectPath - Absolute path to the project root.\n * @returns A URL like \"https://github.com/Owner/Repo\" or null when the remote\n * isn't a GitHub URL or can't be read.\n */\nexport async function resolveRepoUrl(\n projectPath: string,\n): Promise<string | null> {\n try {\n const { stdout: remoteRaw } = await execFileAsync(\n 'git',\n ['remote', 'get-url', 'origin'],\n { cwd: projectPath },\n );\n\n const remote = remoteRaw.trim();\n\n // Parse owner/repo from SSH or HTTPS remote URLs\n // Handles aliases like github.com-Org used in SSH configs\n const match = remote.match(\n /github\\.com[^:/]*[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/u,\n );\n if (!match) {\n return null;\n }\n\n return `https://github.com/${match[1]}`;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the GitHub blob base URL used for per-line source links.\n *\n * Prefers the documented commit SHA when one is available so the links point\n * at the exact revision the docs were generated from; falls back to the\n * default branch otherwise.\n *\n * @param projectPath - Absolute path to the project root.\n * @param commitSha - Optional commit SHA to use as the ref. When null, the\n * default branch is used instead.\n * @returns A base URL like \"https://github.com/Owner/Repo/blob/<ref>/\" or null.\n */\nasync function resolveRepoBaseUrl(\n projectPath: string,\n commitSha: string | null,\n): Promise<string | null> {\n const repoUrl = await resolveRepoUrl(projectPath);\n if (!repoUrl) {\n return null;\n }\n const ref = commitSha ?? (await resolveDefaultBranch(projectPath));\n return `${repoUrl}/blob/${ref}/`;\n}\n\n/**\n * Options for the generate function.\n */\nexport type GenerateOptions = {\n /** Absolute path to the project to scan. */\n projectPath: string;\n /** Absolute path to the output directory for generated docs. */\n outputDir: string;\n /** Directories (relative to projectPath) to scan for .ts source files. */\n scanDirs: string[];\n /**\n * Short label identifying the project the docs were generated from (e.g.\n * \"Core\", \"Extension\"). Stamped in the index page title.\n */\n projectLabel?: string | null;\n /**\n * Git commit SHA the docs were generated from. Stamped in the index page\n * intro so engineers know how current the site is.\n */\n commitSha?: string | null;\n};\n\n/**\n * Result returned by the generate function.\n */\nexport type GenerateResult = {\n namespaces: number;\n actions: number;\n events: number;\n};\n\n/**\n * The set of directories available to scan for messenger types, resolved from\n * the project's filesystem layout.\n */\ntype ScanSources = {\n /** User-configured scan dirs that exist on disk (relative to projectPath). */\n scanDirs: string[];\n /** Absolute path to `packages/` if it exists, otherwise null. */\n packagesDir: string | null;\n /** Absolute path to `node_modules/@metamask/` if it exists, otherwise null. */\n nodeModulesDir: string | null;\n};\n\n/**\n * Discover which configured source locations actually exist on disk.\n *\n * @param projectPath - The project root path.\n * @param scanDirs - User-configured scan directories relative to projectPath.\n * @returns A ScanSources object describing the locations to scan.\n */\nasync function discoverScanSources(\n projectPath: string,\n scanDirs: string[],\n): Promise<ScanSources> {\n const existingScanDirs: string[] = [];\n for (const dir of scanDirs) {\n if (await directoryExists(path.join(projectPath, dir))) {\n existingScanDirs.push(dir);\n }\n }\n\n const packagesDir = path.join(projectPath, 'packages');\n const nodeModulesDir = path.join(projectPath, 'node_modules', '@metamask');\n\n return {\n scanDirs: existingScanDirs,\n packagesDir: (await directoryExists(packagesDir)) ? packagesDir : null,\n nodeModulesDir: (await directoryExists(nodeModulesDir))\n ? nodeModulesDir\n : null,\n };\n}\n\n/**\n * Log a human-readable description of which source locations will be scanned.\n *\n * @param sources - The resolved scan sources.\n */\nfunction logScanPlan(sources: ScanSources): void {\n const summary: string[] = [];\n for (const dir of sources.scanDirs) {\n summary.push(`${dir}/ (.ts)`);\n }\n if (sources.packagesDir) {\n summary.push('packages/*/src (.ts)');\n }\n if (sources.nodeModulesDir) {\n summary.push('node_modules/@metamask/*/dist (.d.cts)');\n }\n console.log(\n `Scanning ${summary.join(', ')} for Messenger action/event types...`,\n );\n}\n\n/**\n * Run extraction against every file in a single directory, logging and\n * swallowing per-file failures. All files are added to the shared `project`\n * up front so the type checker can resolve cross-file references when the\n * walker descends into imported types.\n *\n * @param project - The shared ts-morph project.\n * @param directory - The directory to scan.\n * @param projectPath - The project root, used for relative path display.\n * @param findFiles - The function used to enumerate files in the directory.\n * @returns The list of extracted messenger items.\n */\nasync function extractFromDirectory(\n project: Project,\n directory: string,\n projectPath: string,\n findFiles: (dir: string) => Promise<string[]>,\n): Promise<MessengerCapabilityPacket[]> {\n const items: MessengerCapabilityPacket[] = [];\n const files = await findFiles(directory);\n for (const file of files) {\n try {\n const sourceFile =\n project.getSourceFile(file) ?? project.addSourceFileAtPath(file);\n items.push(...extractFromSourceFile(sourceFile, projectPath));\n } catch (error) {\n console.warn(\n `Warning: failed to parse ${path.relative(projectPath, file)}`,\n );\n console.warn(error);\n }\n }\n return items;\n}\n\n/**\n * Enumerate the subdirectories of a parent directory that match the expected\n * layout (e.g., `packages/*/src` or `node_modules/@metamask/*/dist`), keeping\n * only those that actually exist.\n *\n * @param parentDir - The parent directory to enumerate.\n * @param subPath - The trailing path component appended to each entry.\n * @param includeSymlinks - Whether to include symbolic links (true for\n * node_modules where workspaces are symlinked).\n * @returns The list of absolute paths to existing target subdirectories.\n */\nasync function listTargetSubdirectories(\n parentDir: string,\n subPath: string,\n includeSymlinks: boolean,\n): Promise<string[]> {\n const entries = await fs.readdir(parentDir, { withFileTypes: true });\n const candidates = entries\n .filter(\n (entry) =>\n entry.isDirectory() || (includeSymlinks && entry.isSymbolicLink()),\n )\n .map((entry) => path.join(parentDir, entry.name, subPath));\n\n const existing: string[] = [];\n for (const candidate of candidates) {\n if (await directoryExists(candidate)) {\n existing.push(candidate);\n }\n }\n return existing;\n}\n\n/**\n * Scan every source location described by `sources` and return all extracted\n * messenger items. A single ts-morph Project is shared across every file so\n * the type checker can resolve cross-file references (e.g. a `*Messenger`\n * declaration in one file walking through an imported umbrella union into\n * an auto-generated `*-method-action-types.ts` sibling).\n *\n * @param projectPath - The project root path.\n * @param sources - The set of source locations to scan.\n * @returns A flat list of all extracted messenger items.\n */\nasync function scanSources(\n projectPath: string,\n sources: ScanSources,\n): Promise<MessengerCapabilityPacket[]> {\n const project = createExtractionProject();\n const allItems: MessengerCapabilityPacket[] = [];\n\n for (const dir of sources.scanDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n path.join(projectPath, dir),\n projectPath,\n findTsFiles,\n )),\n );\n }\n\n if (sources.packagesDir) {\n const srcDirs = await listTargetSubdirectories(\n sources.packagesDir,\n 'src',\n false,\n );\n for (const srcDir of srcDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n srcDir,\n projectPath,\n findTsFiles,\n )),\n );\n }\n }\n\n if (sources.nodeModulesDir) {\n const distDirs = await listTargetSubdirectories(\n sources.nodeModulesDir,\n 'dist',\n true,\n );\n for (const distDir of distDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n distDir,\n projectPath,\n findDtsFiles,\n )),\n );\n }\n }\n\n return allItems;\n}\n\n/**\n * Replace a previously-seen item in its existing namespace group with a\n * higher-scoring duplicate. Handles the case where the duplicate is a\n * different kind (action vs event) by moving it between lists.\n *\n * @param byNamespace - Map of namespace to its group.\n * @param previous - The previously stored item.\n * @param replacement - The new item to replace it with.\n */\nfunction replaceDuplicateInGroup(\n byNamespace: Map<string, NamespaceGroup>,\n previous: MessengerCapabilityPacket,\n replacement: MessengerCapabilityPacket,\n): void {\n const namespace = replacement.typeString.split(':')[0];\n const group = byNamespace.get(namespace);\n // istanbul ignore next: `previous` and `replacement` have the same\n // typeString, so they share a namespace, and we always insert the\n // namespace into `byNamespace` before recording the original entry.\n if (!group) {\n return;\n }\n const previousList =\n previous.kind === 'action' ? group.actions : group.events;\n const index = previousList.indexOf(previous);\n // istanbul ignore next: `previous` was added to its kind's list by\n // `groupByNamespace` before being recorded in `seen`, so it is always\n // present when we look it up here.\n if (index === -1) {\n return;\n }\n if (previous.kind === replacement.kind) {\n previousList[index] = replacement;\n } else {\n previousList.splice(index, 1);\n const newList =\n replacement.kind === 'action' ? group.actions : group.events;\n newList.push(replacement);\n }\n}\n\n/**\n * Group items by namespace, deduplicating duplicate typeStrings using\n * `deduplicationScore`. Returns groups sorted alphabetically by namespace,\n * with each group's items sorted alphabetically by typeString.\n *\n * @param items - The full list of extracted items.\n * @returns The deduplicated and sorted namespace groups.\n */\nfunction groupByNamespace(\n items: MessengerCapabilityPacket[],\n): NamespaceGroup[] {\n const byNamespace = new Map<string, NamespaceGroup>();\n const seen = new Map<string, MessengerCapabilityPacket>();\n\n for (const item of items) {\n const existing = seen.get(item.typeString);\n if (existing) {\n if (deduplicationScore(item) <= deduplicationScore(existing)) {\n continue;\n }\n replaceDuplicateInGroup(byNamespace, existing, item);\n seen.set(item.typeString, item);\n continue;\n }\n\n seen.set(item.typeString, item);\n const namespace = item.typeString.split(':')[0];\n let group = byNamespace.get(namespace);\n if (!group) {\n group = { namespace, actions: [], events: [] };\n byNamespace.set(namespace, group);\n }\n if (item.kind === 'action') {\n group.actions.push(item);\n } else {\n group.events.push(item);\n }\n }\n\n const namespaces = Array.from(byNamespace.values()).sort((a, b) =>\n a.namespace.localeCompare(b.namespace),\n );\n\n for (const ns of namespaces) {\n ns.actions.sort((a, b) => a.typeString.localeCompare(b.typeString));\n ns.events.sort((a, b) => a.typeString.localeCompare(b.typeString));\n }\n\n return namespaces;\n}\n\n/**\n * Write generated docs (namespace pages, index page, sidebars) to disk,\n * replacing any existing `docs/` directory.\n *\n * @param namespaces - The grouped namespaces to render.\n * @param outputDir - The root output directory.\n * @param repoBaseUrl - GitHub blob base URL for source links, or null.\n * @param indexOptions - Options stamped on the index page header.\n * @param indexOptions.projectLabel - Short label identifying the project.\n * @param indexOptions.commitSha - Git commit SHA the docs were generated from.\n * @returns Promise that resolves once all files are written.\n */\nasync function writeOutput(\n namespaces: NamespaceGroup[],\n outputDir: string,\n repoBaseUrl: string | null,\n indexOptions: {\n projectLabel?: string | null;\n commitSha?: string | null;\n },\n): Promise<void> {\n const docsDir = path.join(outputDir, 'docs');\n\n if (await directoryExists(docsDir)) {\n await fs.rm(docsDir, { recursive: true });\n }\n await fs.mkdir(docsDir, { recursive: true });\n\n for (const ns of namespaces) {\n const nsDir = path.join(docsDir, ns.namespace);\n await fs.mkdir(nsDir, { recursive: true });\n\n if (ns.actions.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'actions.md'),\n generateNamespacePage(ns, 'action', repoBaseUrl),\n );\n }\n\n if (ns.events.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'events.md'),\n generateNamespacePage(ns, 'event', repoBaseUrl),\n );\n }\n }\n\n await fs.writeFile(\n path.join(docsDir, 'index.md'),\n generateIndexPage(namespaces, indexOptions),\n );\n\n await fs.writeFile(\n path.join(outputDir, 'sidebars.ts'),\n generateSidebars(namespaces),\n );\n}\n\n/**\n * Scan a project for messenger action/event types and generate documentation.\n *\n * @param options - Generation options.\n * @returns A promise resolving to counts of generated namespaces, actions, and events.\n */\nexport async function generate(\n options: GenerateOptions,\n): Promise<GenerateResult> {\n const { projectPath, outputDir, scanDirs, projectLabel, commitSha } = options;\n\n const sources = await discoverScanSources(projectPath, scanDirs);\n\n if (\n sources.scanDirs.length === 0 &&\n !sources.packagesDir &&\n !sources.nodeModulesDir\n ) {\n throw new Error(\n `No scannable directories found in ${projectPath}. ` +\n `Looked for: ${scanDirs.join(', ')}, packages/, node_modules/@metamask/`,\n );\n }\n\n logScanPlan(sources);\n\n const allItems = await scanSources(projectPath, sources);\n console.log(\n `Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`,\n );\n\n const namespaces = groupByNamespace(allItems);\n const repoBaseUrl = await resolveRepoBaseUrl(projectPath, commitSha ?? null);\n\n await writeOutput(namespaces, outputDir, repoBaseUrl, {\n projectLabel,\n commitSha,\n });\n\n const totalActions = namespaces.reduce(\n (sum, ns) => sum + ns.actions.length,\n 0,\n );\n const totalEvents = namespaces.reduce((sum, ns) => sum + ns.events.length, 0);\n\n console.log(\n `Generated docs for ${namespaces.length} ${namespaces.length === 1 ? 'namespace' : 'namespaces'}.`,\n );\n console.log(` Actions: ${totalActions}`);\n console.log(` Events: ${totalEvents}`);\n console.log(`Output: ${path.join(outputDir, 'docs')}/`);\n\n return {\n namespaces: namespaces.length,\n actions: totalActions,\n events: totalEvents,\n };\n}\n"]}
|
package/dist/generate.d.cts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve the bare GitHub repository URL for a project by reading its
|
|
3
|
+
* `origin` remote.
|
|
4
|
+
*
|
|
5
|
+
* @param projectPath - Absolute path to the project root.
|
|
6
|
+
* @returns A URL like "https://github.com/Owner/Repo" or null when the remote
|
|
7
|
+
* isn't a GitHub URL or can't be read.
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolveRepoUrl(projectPath: string): Promise<string | null>;
|
|
1
10
|
/**
|
|
2
11
|
* Options for the generate function.
|
|
3
12
|
*/
|
package/dist/generate.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.d.cts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"generate.d.cts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAoEA;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAuBxB;AA0BD;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB,0EAA0E;IAC1E,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAgWF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,cAAc,CAAC,CAiDzB"}
|
package/dist/generate.d.mts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve the bare GitHub repository URL for a project by reading its
|
|
3
|
+
* `origin` remote.
|
|
4
|
+
*
|
|
5
|
+
* @param projectPath - Absolute path to the project root.
|
|
6
|
+
* @returns A URL like "https://github.com/Owner/Repo" or null when the remote
|
|
7
|
+
* isn't a GitHub URL or can't be read.
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolveRepoUrl(projectPath: string): Promise<string | null>;
|
|
1
10
|
/**
|
|
2
11
|
* Options for the generate function.
|
|
3
12
|
*/
|
package/dist/generate.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.d.mts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"generate.d.mts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAoEA;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAuBxB;AA0BD;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB,0EAA0E;IAC1E,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAgWF;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,cAAc,CAAC,CAiDzB"}
|
package/dist/generate.mjs
CHANGED
|
@@ -52,13 +52,14 @@ async function resolveDefaultBranch(projectPath) {
|
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
54
|
/**
|
|
55
|
-
* Resolve the GitHub
|
|
56
|
-
*
|
|
55
|
+
* Resolve the bare GitHub repository URL for a project by reading its
|
|
56
|
+
* `origin` remote.
|
|
57
57
|
*
|
|
58
58
|
* @param projectPath - Absolute path to the project root.
|
|
59
|
-
* @returns A
|
|
59
|
+
* @returns A URL like "https://github.com/Owner/Repo" or null when the remote
|
|
60
|
+
* isn't a GitHub URL or can't be read.
|
|
60
61
|
*/
|
|
61
|
-
async function
|
|
62
|
+
export async function resolveRepoUrl(projectPath) {
|
|
62
63
|
try {
|
|
63
64
|
const { stdout: remoteRaw } = await execFileAsync('git', ['remote', 'get-url', 'origin'], { cwd: projectPath });
|
|
64
65
|
const remote = remoteRaw.trim();
|
|
@@ -68,13 +69,32 @@ async function resolveRepoBaseUrl(projectPath) {
|
|
|
68
69
|
if (!match) {
|
|
69
70
|
return null;
|
|
70
71
|
}
|
|
71
|
-
|
|
72
|
-
return `https://github.com/${match[1]}/blob/${branch}/`;
|
|
72
|
+
return `https://github.com/${match[1]}`;
|
|
73
73
|
}
|
|
74
74
|
catch {
|
|
75
75
|
return null;
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Resolve the GitHub blob base URL used for per-line source links.
|
|
80
|
+
*
|
|
81
|
+
* Prefers the documented commit SHA when one is available so the links point
|
|
82
|
+
* at the exact revision the docs were generated from; falls back to the
|
|
83
|
+
* default branch otherwise.
|
|
84
|
+
*
|
|
85
|
+
* @param projectPath - Absolute path to the project root.
|
|
86
|
+
* @param commitSha - Optional commit SHA to use as the ref. When null, the
|
|
87
|
+
* default branch is used instead.
|
|
88
|
+
* @returns A base URL like "https://github.com/Owner/Repo/blob/<ref>/" or null.
|
|
89
|
+
*/
|
|
90
|
+
async function resolveRepoBaseUrl(projectPath, commitSha) {
|
|
91
|
+
const repoUrl = await resolveRepoUrl(projectPath);
|
|
92
|
+
if (!repoUrl) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
const ref = commitSha ?? (await resolveDefaultBranch(projectPath));
|
|
96
|
+
return `${repoUrl}/blob/${ref}/`;
|
|
97
|
+
}
|
|
78
98
|
/**
|
|
79
99
|
* Discover which configured source locations actually exist on disk.
|
|
80
100
|
*
|
|
@@ -326,7 +346,7 @@ export async function generate(options) {
|
|
|
326
346
|
const allItems = await scanSources(projectPath, sources);
|
|
327
347
|
console.log(`Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`);
|
|
328
348
|
const namespaces = groupByNamespace(allItems);
|
|
329
|
-
const repoBaseUrl = await resolveRepoBaseUrl(projectPath);
|
|
349
|
+
const repoBaseUrl = await resolveRepoBaseUrl(projectPath, commitSha ?? null);
|
|
330
350
|
await writeOutput(namespaces, outputDir, repoBaseUrl, {
|
|
331
351
|
projectLabel,
|
|
332
352
|
commitSha,
|
package/dist/generate.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.mjs","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,6BAA6B;AACvD,OAAO,EAAE,QAAQ,EAAE,2BAA2B;AAC9C,OAA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CAAC,CAAC,CAAC,OAAO,SAAS,CACxF,CAAC;IAEF,MAAM,UAAU,GAAG,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,WAAW,GAAG,MAAM,kBAAkB,CAAC,WAAW,CAAC,CAAC;IAE1D,MAAM,WAAW,CAAC,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE;QACpD,YAAY;QACZ,SAAS;KACV,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,UAAU,CAAC,MAAM,CACpC,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,EACpC,CAAC,CACF,CAAC;IACF,MAAM,WAAW,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAE9E,OAAO,CAAC,GAAG,CACT,sBAAsB,UAAU,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,GAAG,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,cAAc,YAAY,EAAE,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAExD,OAAO;QACL,UAAU,EAAE,UAAU,CAAC,MAAM;QAC7B,OAAO,EAAE,YAAY;QACrB,MAAM,EAAE,WAAW;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { directoryExists } from '@metamask/utils/node';\nimport { execFile } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Project } from 'ts-morph';\n\nimport { findDtsFiles, findTsFiles } from './discovery';\nimport { createExtractionProject, extractFromSourceFile } from './extraction';\nimport {\n generateIndexPage,\n generateNamespacePage,\n generateSidebars,\n} from './markdown';\nimport type { MessengerCapabilityPacket, NamespaceGroup } from './types';\n\n/**\n * Compute a deduplication score for a messenger item, preferring items with\n * JSDoc and from the \"home\" package whose name matches the namespace.\n *\n * @param item - The messenger item to score.\n * @returns A numeric score (higher is better).\n */\nfunction deduplicationScore(item: MessengerCapabilityPacket): number {\n const jsDocScore = item.jsDoc ? 2 : 0;\n const namespacePrefix = item.typeString\n .split(':')[0]\n .replace(/(?:Controller|Service)$/u, '')\n .toLowerCase();\n const homeScore =\n namespacePrefix.length > 0 &&\n item.sourceFile.toLowerCase().includes(namespacePrefix)\n ? 1\n : 0;\n return jsDocScore + homeScore;\n}\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Resolve the default branch of a project's `origin` remote by reading the\n * symbolic ref `refs/remotes/origin/HEAD`. Falls back to `main` if the\n * symbolic ref isn't set (e.g. in shallow CI clones).\n *\n * @param projectPath - Absolute path to the project root.\n * @returns The default branch name (e.g. \"main\", \"master\", \"develop\").\n */\nasync function resolveDefaultBranch(projectPath: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'],\n { cwd: projectPath },\n );\n // stdout looks like \"origin/main\"; strip the leading \"origin/\".\n const trimmed = stdout.trim();\n const slash = trimmed.indexOf('/');\n return slash === -1\n ? // istanbul ignore next: defensive — `symbolic-ref --short` always\n // returns `origin/<branch>` when the symbolic ref is set; this\n // fallback only matters if git's output format ever changes.\n trimmed || 'main'\n : trimmed.slice(slash + 1);\n } catch {\n return 'main';\n }\n}\n\n/**\n * Resolve the GitHub blob base URL for a project by reading its git remote\n * and default branch.\n *\n * @param projectPath - Absolute path to the project root.\n * @returns A base URL like \"https://github.com/Owner/Repo/blob/<branch>/\" or null.\n */\nasync function resolveRepoBaseUrl(projectPath: string): Promise<string | null> {\n try {\n const { stdout: remoteRaw } = await execFileAsync(\n 'git',\n ['remote', 'get-url', 'origin'],\n { cwd: projectPath },\n );\n\n const remote = remoteRaw.trim();\n\n // Parse owner/repo from SSH or HTTPS remote URLs\n // Handles aliases like github.com-Org used in SSH configs\n const match = remote.match(\n /github\\.com[^:/]*[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/u,\n );\n if (!match) {\n return null;\n }\n\n const branch = await resolveDefaultBranch(projectPath);\n return `https://github.com/${match[1]}/blob/${branch}/`;\n } catch {\n return null;\n }\n}\n\n/**\n * Options for the generate function.\n */\nexport type GenerateOptions = {\n /** Absolute path to the project to scan. */\n projectPath: string;\n /** Absolute path to the output directory for generated docs. */\n outputDir: string;\n /** Directories (relative to projectPath) to scan for .ts source files. */\n scanDirs: string[];\n /**\n * Short label identifying the project the docs were generated from (e.g.\n * \"Core\", \"Extension\"). Stamped in the index page title.\n */\n projectLabel?: string | null;\n /**\n * Git commit SHA the docs were generated from. Stamped in the index page\n * intro so engineers know how current the site is.\n */\n commitSha?: string | null;\n};\n\n/**\n * Result returned by the generate function.\n */\nexport type GenerateResult = {\n namespaces: number;\n actions: number;\n events: number;\n};\n\n/**\n * The set of directories available to scan for messenger types, resolved from\n * the project's filesystem layout.\n */\ntype ScanSources = {\n /** User-configured scan dirs that exist on disk (relative to projectPath). */\n scanDirs: string[];\n /** Absolute path to `packages/` if it exists, otherwise null. */\n packagesDir: string | null;\n /** Absolute path to `node_modules/@metamask/` if it exists, otherwise null. */\n nodeModulesDir: string | null;\n};\n\n/**\n * Discover which configured source locations actually exist on disk.\n *\n * @param projectPath - The project root path.\n * @param scanDirs - User-configured scan directories relative to projectPath.\n * @returns A ScanSources object describing the locations to scan.\n */\nasync function discoverScanSources(\n projectPath: string,\n scanDirs: string[],\n): Promise<ScanSources> {\n const existingScanDirs: string[] = [];\n for (const dir of scanDirs) {\n if (await directoryExists(path.join(projectPath, dir))) {\n existingScanDirs.push(dir);\n }\n }\n\n const packagesDir = path.join(projectPath, 'packages');\n const nodeModulesDir = path.join(projectPath, 'node_modules', '@metamask');\n\n return {\n scanDirs: existingScanDirs,\n packagesDir: (await directoryExists(packagesDir)) ? packagesDir : null,\n nodeModulesDir: (await directoryExists(nodeModulesDir))\n ? nodeModulesDir\n : null,\n };\n}\n\n/**\n * Log a human-readable description of which source locations will be scanned.\n *\n * @param sources - The resolved scan sources.\n */\nfunction logScanPlan(sources: ScanSources): void {\n const summary: string[] = [];\n for (const dir of sources.scanDirs) {\n summary.push(`${dir}/ (.ts)`);\n }\n if (sources.packagesDir) {\n summary.push('packages/*/src (.ts)');\n }\n if (sources.nodeModulesDir) {\n summary.push('node_modules/@metamask/*/dist (.d.cts)');\n }\n console.log(\n `Scanning ${summary.join(', ')} for Messenger action/event types...`,\n );\n}\n\n/**\n * Run extraction against every file in a single directory, logging and\n * swallowing per-file failures. All files are added to the shared `project`\n * up front so the type checker can resolve cross-file references when the\n * walker descends into imported types.\n *\n * @param project - The shared ts-morph project.\n * @param directory - The directory to scan.\n * @param projectPath - The project root, used for relative path display.\n * @param findFiles - The function used to enumerate files in the directory.\n * @returns The list of extracted messenger items.\n */\nasync function extractFromDirectory(\n project: Project,\n directory: string,\n projectPath: string,\n findFiles: (dir: string) => Promise<string[]>,\n): Promise<MessengerCapabilityPacket[]> {\n const items: MessengerCapabilityPacket[] = [];\n const files = await findFiles(directory);\n for (const file of files) {\n try {\n const sourceFile =\n project.getSourceFile(file) ?? project.addSourceFileAtPath(file);\n items.push(...extractFromSourceFile(sourceFile, projectPath));\n } catch (error) {\n console.warn(\n `Warning: failed to parse ${path.relative(projectPath, file)}`,\n );\n console.warn(error);\n }\n }\n return items;\n}\n\n/**\n * Enumerate the subdirectories of a parent directory that match the expected\n * layout (e.g., `packages/*/src` or `node_modules/@metamask/*/dist`), keeping\n * only those that actually exist.\n *\n * @param parentDir - The parent directory to enumerate.\n * @param subPath - The trailing path component appended to each entry.\n * @param includeSymlinks - Whether to include symbolic links (true for\n * node_modules where workspaces are symlinked).\n * @returns The list of absolute paths to existing target subdirectories.\n */\nasync function listTargetSubdirectories(\n parentDir: string,\n subPath: string,\n includeSymlinks: boolean,\n): Promise<string[]> {\n const entries = await fs.readdir(parentDir, { withFileTypes: true });\n const candidates = entries\n .filter(\n (entry) =>\n entry.isDirectory() || (includeSymlinks && entry.isSymbolicLink()),\n )\n .map((entry) => path.join(parentDir, entry.name, subPath));\n\n const existing: string[] = [];\n for (const candidate of candidates) {\n if (await directoryExists(candidate)) {\n existing.push(candidate);\n }\n }\n return existing;\n}\n\n/**\n * Scan every source location described by `sources` and return all extracted\n * messenger items. A single ts-morph Project is shared across every file so\n * the type checker can resolve cross-file references (e.g. a `*Messenger`\n * declaration in one file walking through an imported umbrella union into\n * an auto-generated `*-method-action-types.ts` sibling).\n *\n * @param projectPath - The project root path.\n * @param sources - The set of source locations to scan.\n * @returns A flat list of all extracted messenger items.\n */\nasync function scanSources(\n projectPath: string,\n sources: ScanSources,\n): Promise<MessengerCapabilityPacket[]> {\n const project = createExtractionProject();\n const allItems: MessengerCapabilityPacket[] = [];\n\n for (const dir of sources.scanDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n path.join(projectPath, dir),\n projectPath,\n findTsFiles,\n )),\n );\n }\n\n if (sources.packagesDir) {\n const srcDirs = await listTargetSubdirectories(\n sources.packagesDir,\n 'src',\n false,\n );\n for (const srcDir of srcDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n srcDir,\n projectPath,\n findTsFiles,\n )),\n );\n }\n }\n\n if (sources.nodeModulesDir) {\n const distDirs = await listTargetSubdirectories(\n sources.nodeModulesDir,\n 'dist',\n true,\n );\n for (const distDir of distDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n distDir,\n projectPath,\n findDtsFiles,\n )),\n );\n }\n }\n\n return allItems;\n}\n\n/**\n * Replace a previously-seen item in its existing namespace group with a\n * higher-scoring duplicate. Handles the case where the duplicate is a\n * different kind (action vs event) by moving it between lists.\n *\n * @param byNamespace - Map of namespace to its group.\n * @param previous - The previously stored item.\n * @param replacement - The new item to replace it with.\n */\nfunction replaceDuplicateInGroup(\n byNamespace: Map<string, NamespaceGroup>,\n previous: MessengerCapabilityPacket,\n replacement: MessengerCapabilityPacket,\n): void {\n const namespace = replacement.typeString.split(':')[0];\n const group = byNamespace.get(namespace);\n // istanbul ignore next: `previous` and `replacement` have the same\n // typeString, so they share a namespace, and we always insert the\n // namespace into `byNamespace` before recording the original entry.\n if (!group) {\n return;\n }\n const previousList =\n previous.kind === 'action' ? group.actions : group.events;\n const index = previousList.indexOf(previous);\n // istanbul ignore next: `previous` was added to its kind's list by\n // `groupByNamespace` before being recorded in `seen`, so it is always\n // present when we look it up here.\n if (index === -1) {\n return;\n }\n if (previous.kind === replacement.kind) {\n previousList[index] = replacement;\n } else {\n previousList.splice(index, 1);\n const newList =\n replacement.kind === 'action' ? group.actions : group.events;\n newList.push(replacement);\n }\n}\n\n/**\n * Group items by namespace, deduplicating duplicate typeStrings using\n * `deduplicationScore`. Returns groups sorted alphabetically by namespace,\n * with each group's items sorted alphabetically by typeString.\n *\n * @param items - The full list of extracted items.\n * @returns The deduplicated and sorted namespace groups.\n */\nfunction groupByNamespace(\n items: MessengerCapabilityPacket[],\n): NamespaceGroup[] {\n const byNamespace = new Map<string, NamespaceGroup>();\n const seen = new Map<string, MessengerCapabilityPacket>();\n\n for (const item of items) {\n const existing = seen.get(item.typeString);\n if (existing) {\n if (deduplicationScore(item) <= deduplicationScore(existing)) {\n continue;\n }\n replaceDuplicateInGroup(byNamespace, existing, item);\n seen.set(item.typeString, item);\n continue;\n }\n\n seen.set(item.typeString, item);\n const namespace = item.typeString.split(':')[0];\n let group = byNamespace.get(namespace);\n if (!group) {\n group = { namespace, actions: [], events: [] };\n byNamespace.set(namespace, group);\n }\n if (item.kind === 'action') {\n group.actions.push(item);\n } else {\n group.events.push(item);\n }\n }\n\n const namespaces = Array.from(byNamespace.values()).sort((a, b) =>\n a.namespace.localeCompare(b.namespace),\n );\n\n for (const ns of namespaces) {\n ns.actions.sort((a, b) => a.typeString.localeCompare(b.typeString));\n ns.events.sort((a, b) => a.typeString.localeCompare(b.typeString));\n }\n\n return namespaces;\n}\n\n/**\n * Write generated docs (namespace pages, index page, sidebars) to disk,\n * replacing any existing `docs/` directory.\n *\n * @param namespaces - The grouped namespaces to render.\n * @param outputDir - The root output directory.\n * @param repoBaseUrl - GitHub blob base URL for source links, or null.\n * @param indexOptions - Options stamped on the index page header.\n * @param indexOptions.projectLabel - Short label identifying the project.\n * @param indexOptions.commitSha - Git commit SHA the docs were generated from.\n * @returns Promise that resolves once all files are written.\n */\nasync function writeOutput(\n namespaces: NamespaceGroup[],\n outputDir: string,\n repoBaseUrl: string | null,\n indexOptions: {\n projectLabel?: string | null;\n commitSha?: string | null;\n },\n): Promise<void> {\n const docsDir = path.join(outputDir, 'docs');\n\n if (await directoryExists(docsDir)) {\n await fs.rm(docsDir, { recursive: true });\n }\n await fs.mkdir(docsDir, { recursive: true });\n\n for (const ns of namespaces) {\n const nsDir = path.join(docsDir, ns.namespace);\n await fs.mkdir(nsDir, { recursive: true });\n\n if (ns.actions.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'actions.md'),\n generateNamespacePage(ns, 'action', repoBaseUrl),\n );\n }\n\n if (ns.events.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'events.md'),\n generateNamespacePage(ns, 'event', repoBaseUrl),\n );\n }\n }\n\n await fs.writeFile(\n path.join(docsDir, 'index.md'),\n generateIndexPage(namespaces, indexOptions),\n );\n\n await fs.writeFile(\n path.join(outputDir, 'sidebars.ts'),\n generateSidebars(namespaces),\n );\n}\n\n/**\n * Scan a project for messenger action/event types and generate documentation.\n *\n * @param options - Generation options.\n * @returns A promise resolving to counts of generated namespaces, actions, and events.\n */\nexport async function generate(\n options: GenerateOptions,\n): Promise<GenerateResult> {\n const { projectPath, outputDir, scanDirs, projectLabel, commitSha } = options;\n\n const sources = await discoverScanSources(projectPath, scanDirs);\n\n if (\n sources.scanDirs.length === 0 &&\n !sources.packagesDir &&\n !sources.nodeModulesDir\n ) {\n throw new Error(\n `No scannable directories found in ${projectPath}. ` +\n `Looked for: ${scanDirs.join(', ')}, packages/, node_modules/@metamask/`,\n );\n }\n\n logScanPlan(sources);\n\n const allItems = await scanSources(projectPath, sources);\n console.log(\n `Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`,\n );\n\n const namespaces = groupByNamespace(allItems);\n const repoBaseUrl = await resolveRepoBaseUrl(projectPath);\n\n await writeOutput(namespaces, outputDir, repoBaseUrl, {\n projectLabel,\n commitSha,\n });\n\n const totalActions = namespaces.reduce(\n (sum, ns) => sum + ns.actions.length,\n 0,\n );\n const totalEvents = namespaces.reduce((sum, ns) => sum + ns.events.length, 0);\n\n console.log(\n `Generated docs for ${namespaces.length} ${namespaces.length === 1 ? 'namespace' : 'namespaces'}.`,\n );\n console.log(` Actions: ${totalActions}`);\n console.log(` Events: ${totalEvents}`);\n console.log(`Output: ${path.join(outputDir, 'docs')}/`);\n\n return {\n namespaces: namespaces.length,\n actions: totalActions,\n events: totalEvents,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generate.mjs","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,6BAA6B;AACvD,OAAO,EAAE,QAAQ,EAAE,2BAA2B;AAC9C,OAAO,KAAK,EAAE,yBAAyB;AACvC,OAAO,KAAK,IAAI,kBAAkB;AAClC,OAAO,EAAE,SAAS,EAAE,kBAAkB;AAGtC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,wBAAoB;AACxD,OAAO,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,yBAAqB;AAC9E,OAAO,EACL,iBAAiB,EACjB,qBAAqB,EACrB,gBAAgB,EACjB,uBAAmB;AAGpB;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,IAA+B;IACzD,MAAM,UAAU,GAAG,IAAI,CAA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BAAgB,CAAC,QAAQ,CAAC,CAAC;IAC9C,MAAM,WAAW,GAAG,MAAM,kBAAkB,CAAC,WAAW,EAAE,SAAS,IAAI,IAAI,CAAC,CAAC;IAE7E,MAAM,WAAW,CAAC,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE;QACpD,YAAY;QACZ,SAAS;KACV,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,UAAU,CAAC,MAAM,CACpC,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,EACpC,CAAC,CACF,CAAC;IACF,MAAM,WAAW,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAE9E,OAAO,CAAC,GAAG,CACT,sBAAsB,UAAU,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,GAAG,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,cAAc,YAAY,EAAE,CAAC,CAAC;IAC1C,OAAO,CAAC,GAAG,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAExD,OAAO;QACL,UAAU,EAAE,UAAU,CAAC,MAAM;QAC7B,OAAO,EAAE,YAAY;QACrB,MAAM,EAAE,WAAW;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { directoryExists } from '@metamask/utils/node';\nimport { execFile } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Project } from 'ts-morph';\n\nimport { findDtsFiles, findTsFiles } from './discovery';\nimport { createExtractionProject, extractFromSourceFile } from './extraction';\nimport {\n generateIndexPage,\n generateNamespacePage,\n generateSidebars,\n} from './markdown';\nimport type { MessengerCapabilityPacket, NamespaceGroup } from './types';\n\n/**\n * Compute a deduplication score for a messenger item, preferring items with\n * JSDoc and from the \"home\" package whose name matches the namespace.\n *\n * @param item - The messenger item to score.\n * @returns A numeric score (higher is better).\n */\nfunction deduplicationScore(item: MessengerCapabilityPacket): number {\n const jsDocScore = item.jsDoc ? 2 : 0;\n const namespacePrefix = item.typeString\n .split(':')[0]\n .replace(/(?:Controller|Service)$/u, '')\n .toLowerCase();\n const homeScore =\n namespacePrefix.length > 0 &&\n item.sourceFile.toLowerCase().includes(namespacePrefix)\n ? 1\n : 0;\n return jsDocScore + homeScore;\n}\n\nconst execFileAsync = promisify(execFile);\n\n/**\n * Resolve the default branch of a project's `origin` remote by reading the\n * symbolic ref `refs/remotes/origin/HEAD`. Falls back to `main` if the\n * symbolic ref isn't set (e.g. in shallow CI clones).\n *\n * @param projectPath - Absolute path to the project root.\n * @returns The default branch name (e.g. \"main\", \"master\", \"develop\").\n */\nasync function resolveDefaultBranch(projectPath: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'],\n { cwd: projectPath },\n );\n // stdout looks like \"origin/main\"; strip the leading \"origin/\".\n const trimmed = stdout.trim();\n const slash = trimmed.indexOf('/');\n return slash === -1\n ? // istanbul ignore next: defensive — `symbolic-ref --short` always\n // returns `origin/<branch>` when the symbolic ref is set; this\n // fallback only matters if git's output format ever changes.\n trimmed || 'main'\n : trimmed.slice(slash + 1);\n } catch {\n return 'main';\n }\n}\n\n/**\n * Resolve the bare GitHub repository URL for a project by reading its\n * `origin` remote.\n *\n * @param projectPath - Absolute path to the project root.\n * @returns A URL like \"https://github.com/Owner/Repo\" or null when the remote\n * isn't a GitHub URL or can't be read.\n */\nexport async function resolveRepoUrl(\n projectPath: string,\n): Promise<string | null> {\n try {\n const { stdout: remoteRaw } = await execFileAsync(\n 'git',\n ['remote', 'get-url', 'origin'],\n { cwd: projectPath },\n );\n\n const remote = remoteRaw.trim();\n\n // Parse owner/repo from SSH or HTTPS remote URLs\n // Handles aliases like github.com-Org used in SSH configs\n const match = remote.match(\n /github\\.com[^:/]*[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/u,\n );\n if (!match) {\n return null;\n }\n\n return `https://github.com/${match[1]}`;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the GitHub blob base URL used for per-line source links.\n *\n * Prefers the documented commit SHA when one is available so the links point\n * at the exact revision the docs were generated from; falls back to the\n * default branch otherwise.\n *\n * @param projectPath - Absolute path to the project root.\n * @param commitSha - Optional commit SHA to use as the ref. When null, the\n * default branch is used instead.\n * @returns A base URL like \"https://github.com/Owner/Repo/blob/<ref>/\" or null.\n */\nasync function resolveRepoBaseUrl(\n projectPath: string,\n commitSha: string | null,\n): Promise<string | null> {\n const repoUrl = await resolveRepoUrl(projectPath);\n if (!repoUrl) {\n return null;\n }\n const ref = commitSha ?? (await resolveDefaultBranch(projectPath));\n return `${repoUrl}/blob/${ref}/`;\n}\n\n/**\n * Options for the generate function.\n */\nexport type GenerateOptions = {\n /** Absolute path to the project to scan. */\n projectPath: string;\n /** Absolute path to the output directory for generated docs. */\n outputDir: string;\n /** Directories (relative to projectPath) to scan for .ts source files. */\n scanDirs: string[];\n /**\n * Short label identifying the project the docs were generated from (e.g.\n * \"Core\", \"Extension\"). Stamped in the index page title.\n */\n projectLabel?: string | null;\n /**\n * Git commit SHA the docs were generated from. Stamped in the index page\n * intro so engineers know how current the site is.\n */\n commitSha?: string | null;\n};\n\n/**\n * Result returned by the generate function.\n */\nexport type GenerateResult = {\n namespaces: number;\n actions: number;\n events: number;\n};\n\n/**\n * The set of directories available to scan for messenger types, resolved from\n * the project's filesystem layout.\n */\ntype ScanSources = {\n /** User-configured scan dirs that exist on disk (relative to projectPath). */\n scanDirs: string[];\n /** Absolute path to `packages/` if it exists, otherwise null. */\n packagesDir: string | null;\n /** Absolute path to `node_modules/@metamask/` if it exists, otherwise null. */\n nodeModulesDir: string | null;\n};\n\n/**\n * Discover which configured source locations actually exist on disk.\n *\n * @param projectPath - The project root path.\n * @param scanDirs - User-configured scan directories relative to projectPath.\n * @returns A ScanSources object describing the locations to scan.\n */\nasync function discoverScanSources(\n projectPath: string,\n scanDirs: string[],\n): Promise<ScanSources> {\n const existingScanDirs: string[] = [];\n for (const dir of scanDirs) {\n if (await directoryExists(path.join(projectPath, dir))) {\n existingScanDirs.push(dir);\n }\n }\n\n const packagesDir = path.join(projectPath, 'packages');\n const nodeModulesDir = path.join(projectPath, 'node_modules', '@metamask');\n\n return {\n scanDirs: existingScanDirs,\n packagesDir: (await directoryExists(packagesDir)) ? packagesDir : null,\n nodeModulesDir: (await directoryExists(nodeModulesDir))\n ? nodeModulesDir\n : null,\n };\n}\n\n/**\n * Log a human-readable description of which source locations will be scanned.\n *\n * @param sources - The resolved scan sources.\n */\nfunction logScanPlan(sources: ScanSources): void {\n const summary: string[] = [];\n for (const dir of sources.scanDirs) {\n summary.push(`${dir}/ (.ts)`);\n }\n if (sources.packagesDir) {\n summary.push('packages/*/src (.ts)');\n }\n if (sources.nodeModulesDir) {\n summary.push('node_modules/@metamask/*/dist (.d.cts)');\n }\n console.log(\n `Scanning ${summary.join(', ')} for Messenger action/event types...`,\n );\n}\n\n/**\n * Run extraction against every file in a single directory, logging and\n * swallowing per-file failures. All files are added to the shared `project`\n * up front so the type checker can resolve cross-file references when the\n * walker descends into imported types.\n *\n * @param project - The shared ts-morph project.\n * @param directory - The directory to scan.\n * @param projectPath - The project root, used for relative path display.\n * @param findFiles - The function used to enumerate files in the directory.\n * @returns The list of extracted messenger items.\n */\nasync function extractFromDirectory(\n project: Project,\n directory: string,\n projectPath: string,\n findFiles: (dir: string) => Promise<string[]>,\n): Promise<MessengerCapabilityPacket[]> {\n const items: MessengerCapabilityPacket[] = [];\n const files = await findFiles(directory);\n for (const file of files) {\n try {\n const sourceFile =\n project.getSourceFile(file) ?? project.addSourceFileAtPath(file);\n items.push(...extractFromSourceFile(sourceFile, projectPath));\n } catch (error) {\n console.warn(\n `Warning: failed to parse ${path.relative(projectPath, file)}`,\n );\n console.warn(error);\n }\n }\n return items;\n}\n\n/**\n * Enumerate the subdirectories of a parent directory that match the expected\n * layout (e.g., `packages/*/src` or `node_modules/@metamask/*/dist`), keeping\n * only those that actually exist.\n *\n * @param parentDir - The parent directory to enumerate.\n * @param subPath - The trailing path component appended to each entry.\n * @param includeSymlinks - Whether to include symbolic links (true for\n * node_modules where workspaces are symlinked).\n * @returns The list of absolute paths to existing target subdirectories.\n */\nasync function listTargetSubdirectories(\n parentDir: string,\n subPath: string,\n includeSymlinks: boolean,\n): Promise<string[]> {\n const entries = await fs.readdir(parentDir, { withFileTypes: true });\n const candidates = entries\n .filter(\n (entry) =>\n entry.isDirectory() || (includeSymlinks && entry.isSymbolicLink()),\n )\n .map((entry) => path.join(parentDir, entry.name, subPath));\n\n const existing: string[] = [];\n for (const candidate of candidates) {\n if (await directoryExists(candidate)) {\n existing.push(candidate);\n }\n }\n return existing;\n}\n\n/**\n * Scan every source location described by `sources` and return all extracted\n * messenger items. A single ts-morph Project is shared across every file so\n * the type checker can resolve cross-file references (e.g. a `*Messenger`\n * declaration in one file walking through an imported umbrella union into\n * an auto-generated `*-method-action-types.ts` sibling).\n *\n * @param projectPath - The project root path.\n * @param sources - The set of source locations to scan.\n * @returns A flat list of all extracted messenger items.\n */\nasync function scanSources(\n projectPath: string,\n sources: ScanSources,\n): Promise<MessengerCapabilityPacket[]> {\n const project = createExtractionProject();\n const allItems: MessengerCapabilityPacket[] = [];\n\n for (const dir of sources.scanDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n path.join(projectPath, dir),\n projectPath,\n findTsFiles,\n )),\n );\n }\n\n if (sources.packagesDir) {\n const srcDirs = await listTargetSubdirectories(\n sources.packagesDir,\n 'src',\n false,\n );\n for (const srcDir of srcDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n srcDir,\n projectPath,\n findTsFiles,\n )),\n );\n }\n }\n\n if (sources.nodeModulesDir) {\n const distDirs = await listTargetSubdirectories(\n sources.nodeModulesDir,\n 'dist',\n true,\n );\n for (const distDir of distDirs) {\n allItems.push(\n ...(await extractFromDirectory(\n project,\n distDir,\n projectPath,\n findDtsFiles,\n )),\n );\n }\n }\n\n return allItems;\n}\n\n/**\n * Replace a previously-seen item in its existing namespace group with a\n * higher-scoring duplicate. Handles the case where the duplicate is a\n * different kind (action vs event) by moving it between lists.\n *\n * @param byNamespace - Map of namespace to its group.\n * @param previous - The previously stored item.\n * @param replacement - The new item to replace it with.\n */\nfunction replaceDuplicateInGroup(\n byNamespace: Map<string, NamespaceGroup>,\n previous: MessengerCapabilityPacket,\n replacement: MessengerCapabilityPacket,\n): void {\n const namespace = replacement.typeString.split(':')[0];\n const group = byNamespace.get(namespace);\n // istanbul ignore next: `previous` and `replacement` have the same\n // typeString, so they share a namespace, and we always insert the\n // namespace into `byNamespace` before recording the original entry.\n if (!group) {\n return;\n }\n const previousList =\n previous.kind === 'action' ? group.actions : group.events;\n const index = previousList.indexOf(previous);\n // istanbul ignore next: `previous` was added to its kind's list by\n // `groupByNamespace` before being recorded in `seen`, so it is always\n // present when we look it up here.\n if (index === -1) {\n return;\n }\n if (previous.kind === replacement.kind) {\n previousList[index] = replacement;\n } else {\n previousList.splice(index, 1);\n const newList =\n replacement.kind === 'action' ? group.actions : group.events;\n newList.push(replacement);\n }\n}\n\n/**\n * Group items by namespace, deduplicating duplicate typeStrings using\n * `deduplicationScore`. Returns groups sorted alphabetically by namespace,\n * with each group's items sorted alphabetically by typeString.\n *\n * @param items - The full list of extracted items.\n * @returns The deduplicated and sorted namespace groups.\n */\nfunction groupByNamespace(\n items: MessengerCapabilityPacket[],\n): NamespaceGroup[] {\n const byNamespace = new Map<string, NamespaceGroup>();\n const seen = new Map<string, MessengerCapabilityPacket>();\n\n for (const item of items) {\n const existing = seen.get(item.typeString);\n if (existing) {\n if (deduplicationScore(item) <= deduplicationScore(existing)) {\n continue;\n }\n replaceDuplicateInGroup(byNamespace, existing, item);\n seen.set(item.typeString, item);\n continue;\n }\n\n seen.set(item.typeString, item);\n const namespace = item.typeString.split(':')[0];\n let group = byNamespace.get(namespace);\n if (!group) {\n group = { namespace, actions: [], events: [] };\n byNamespace.set(namespace, group);\n }\n if (item.kind === 'action') {\n group.actions.push(item);\n } else {\n group.events.push(item);\n }\n }\n\n const namespaces = Array.from(byNamespace.values()).sort((a, b) =>\n a.namespace.localeCompare(b.namespace),\n );\n\n for (const ns of namespaces) {\n ns.actions.sort((a, b) => a.typeString.localeCompare(b.typeString));\n ns.events.sort((a, b) => a.typeString.localeCompare(b.typeString));\n }\n\n return namespaces;\n}\n\n/**\n * Write generated docs (namespace pages, index page, sidebars) to disk,\n * replacing any existing `docs/` directory.\n *\n * @param namespaces - The grouped namespaces to render.\n * @param outputDir - The root output directory.\n * @param repoBaseUrl - GitHub blob base URL for source links, or null.\n * @param indexOptions - Options stamped on the index page header.\n * @param indexOptions.projectLabel - Short label identifying the project.\n * @param indexOptions.commitSha - Git commit SHA the docs were generated from.\n * @returns Promise that resolves once all files are written.\n */\nasync function writeOutput(\n namespaces: NamespaceGroup[],\n outputDir: string,\n repoBaseUrl: string | null,\n indexOptions: {\n projectLabel?: string | null;\n commitSha?: string | null;\n },\n): Promise<void> {\n const docsDir = path.join(outputDir, 'docs');\n\n if (await directoryExists(docsDir)) {\n await fs.rm(docsDir, { recursive: true });\n }\n await fs.mkdir(docsDir, { recursive: true });\n\n for (const ns of namespaces) {\n const nsDir = path.join(docsDir, ns.namespace);\n await fs.mkdir(nsDir, { recursive: true });\n\n if (ns.actions.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'actions.md'),\n generateNamespacePage(ns, 'action', repoBaseUrl),\n );\n }\n\n if (ns.events.length > 0) {\n await fs.writeFile(\n path.join(nsDir, 'events.md'),\n generateNamespacePage(ns, 'event', repoBaseUrl),\n );\n }\n }\n\n await fs.writeFile(\n path.join(docsDir, 'index.md'),\n generateIndexPage(namespaces, indexOptions),\n );\n\n await fs.writeFile(\n path.join(outputDir, 'sidebars.ts'),\n generateSidebars(namespaces),\n );\n}\n\n/**\n * Scan a project for messenger action/event types and generate documentation.\n *\n * @param options - Generation options.\n * @returns A promise resolving to counts of generated namespaces, actions, and events.\n */\nexport async function generate(\n options: GenerateOptions,\n): Promise<GenerateResult> {\n const { projectPath, outputDir, scanDirs, projectLabel, commitSha } = options;\n\n const sources = await discoverScanSources(projectPath, scanDirs);\n\n if (\n sources.scanDirs.length === 0 &&\n !sources.packagesDir &&\n !sources.nodeModulesDir\n ) {\n throw new Error(\n `No scannable directories found in ${projectPath}. ` +\n `Looked for: ${scanDirs.join(', ')}, packages/, node_modules/@metamask/`,\n );\n }\n\n logScanPlan(sources);\n\n const allItems = await scanSources(projectPath, sources);\n console.log(\n `Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`,\n );\n\n const namespaces = groupByNamespace(allItems);\n const repoBaseUrl = await resolveRepoBaseUrl(projectPath, commitSha ?? null);\n\n await writeOutput(namespaces, outputDir, repoBaseUrl, {\n projectLabel,\n commitSha,\n });\n\n const totalActions = namespaces.reduce(\n (sum, ns) => sum + ns.actions.length,\n 0,\n );\n const totalEvents = namespaces.reduce((sum, ns) => sum + ns.events.length, 0);\n\n console.log(\n `Generated docs for ${namespaces.length} ${namespaces.length === 1 ? 'namespace' : 'namespaces'}.`,\n );\n console.log(` Actions: ${totalActions}`);\n console.log(` Events: ${totalEvents}`);\n console.log(`Output: ${path.join(outputDir, 'docs')}/`);\n\n return {\n namespaces: namespaces.length,\n actions: totalActions,\n events: totalEvents,\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/platform-api-docs",
|
|
3
|
-
"version": "0.0.0-preview-
|
|
3
|
+
"version": "0.0.0-preview-a3545aef8",
|
|
4
4
|
"description": "Produces documentation for the platform API, the set of actions and events available in the clients through the message bus",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -6,6 +6,11 @@ const codeTheme = themes.dracula;
|
|
|
6
6
|
|
|
7
7
|
const projectLabel = process.env.DOCS_PROJECT_LABEL;
|
|
8
8
|
const commitSha = process.env.DOCS_COMMIT_SHA;
|
|
9
|
+
// The CLI discovers the project's `origin` remote and passes it through so
|
|
10
|
+
// navbar links point at the actual repo the docs were generated from, not
|
|
11
|
+
// hardcoded MetaMask/core. Falls back to MetaMask/core when running outside a
|
|
12
|
+
// git checkout (e.g. local smoke tests).
|
|
13
|
+
const repoUrl = process.env.DOCS_REPO_URL ?? 'https://github.com/MetaMask/core';
|
|
9
14
|
const projectSuffix = projectLabel ? ` (${projectLabel})` : '';
|
|
10
15
|
|
|
11
16
|
const config: Config = {
|
|
@@ -76,12 +81,12 @@ const config: Config = {
|
|
|
76
81
|
{
|
|
77
82
|
label: `commit ${commitSha}`,
|
|
78
83
|
position: 'right' as const,
|
|
79
|
-
href:
|
|
84
|
+
href: `${repoUrl}/commit/${commitSha}`,
|
|
80
85
|
},
|
|
81
86
|
]
|
|
82
87
|
: []),
|
|
83
88
|
{
|
|
84
|
-
href:
|
|
89
|
+
href: repoUrl,
|
|
85
90
|
label: 'GitHub',
|
|
86
91
|
position: 'right',
|
|
87
92
|
},
|