@metamask-previews/platform-api-docs 0.0.0-preview-4f4c98e → 0.0.0-preview-eb263b0ee

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.
Files changed (70) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/README.md +1 -34
  3. package/dist/cli.cjs +241 -0
  4. package/dist/cli.cjs.map +1 -0
  5. package/dist/cli.d.cts +3 -0
  6. package/dist/cli.d.cts.map +1 -0
  7. package/dist/cli.d.mts +3 -0
  8. package/dist/cli.d.mts.map +1 -0
  9. package/dist/{cli.js → cli.mjs} +57 -114
  10. package/dist/cli.mjs.map +1 -0
  11. package/dist/discovery.cjs +53 -0
  12. package/dist/discovery.cjs.map +1 -0
  13. package/dist/{discovery.d.ts → discovery.d.cts} +1 -1
  14. package/dist/discovery.d.cts.map +1 -0
  15. package/dist/discovery.d.mts +22 -0
  16. package/dist/discovery.d.mts.map +1 -0
  17. package/dist/{discovery.js → discovery.mjs} +2 -2
  18. package/dist/discovery.mjs.map +1 -0
  19. package/dist/extraction.cjs +754 -0
  20. package/dist/extraction.cjs.map +1 -0
  21. package/dist/extraction.d.cts +27 -0
  22. package/dist/extraction.d.cts.map +1 -0
  23. package/dist/extraction.d.mts +27 -0
  24. package/dist/extraction.d.mts.map +1 -0
  25. package/dist/{extraction.js → extraction.mjs} +47 -71
  26. package/dist/extraction.mjs.map +1 -0
  27. package/dist/generate.cjs +394 -0
  28. package/dist/generate.cjs.map +1 -0
  29. package/dist/{generate.d.ts → generate.d.cts} +11 -35
  30. package/dist/generate.d.cts.map +1 -0
  31. package/dist/generate.d.mts +46 -0
  32. package/dist/generate.d.mts.map +1 -0
  33. package/dist/{generate.js → generate.mjs} +15 -83
  34. package/dist/generate.mjs.map +1 -0
  35. package/dist/markdown.cjs +239 -0
  36. package/dist/markdown.cjs.map +1 -0
  37. package/dist/{markdown.d.ts → markdown.d.cts} +2 -2
  38. package/dist/markdown.d.cts.map +1 -0
  39. package/dist/markdown.d.mts +52 -0
  40. package/dist/markdown.d.mts.map +1 -0
  41. package/dist/{markdown.js → markdown.mjs} +1 -1
  42. package/dist/markdown.mjs.map +1 -0
  43. package/dist/types.cjs +3 -0
  44. package/dist/types.cjs.map +1 -0
  45. package/dist/{types.d.ts → types.d.cts} +1 -1
  46. package/dist/types.d.cts.map +1 -0
  47. package/dist/types.d.mts +47 -0
  48. package/dist/types.d.mts.map +1 -0
  49. package/dist/types.mjs +2 -0
  50. package/dist/types.mjs.map +1 -0
  51. package/package.json +8 -12
  52. package/dist/cli.d.ts +0 -3
  53. package/dist/cli.d.ts.map +0 -1
  54. package/dist/cli.js.map +0 -1
  55. package/dist/discovery.d.ts.map +0 -1
  56. package/dist/discovery.js.map +0 -1
  57. package/dist/extraction.d.ts +0 -83
  58. package/dist/extraction.d.ts.map +0 -1
  59. package/dist/extraction.js.map +0 -1
  60. package/dist/generate.d.ts.map +0 -1
  61. package/dist/generate.js.map +0 -1
  62. package/dist/markdown.d.ts.map +0 -1
  63. package/dist/markdown.js.map +0 -1
  64. package/dist/root-messenger-discovery.d.ts +0 -61
  65. package/dist/root-messenger-discovery.d.ts.map +0 -1
  66. package/dist/root-messenger-discovery.js +0 -352
  67. package/dist/root-messenger-discovery.js.map +0 -1
  68. package/dist/types.d.ts.map +0 -1
  69. package/dist/types.js +0 -2
  70. package/dist/types.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -9,6 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
- - Initial release of the platform-api-docs package ([#8012](https://github.com/MetaMask/core/pull/8012), [#9913](https://github.com/MetaMask/core/pull/9913))
12
+ - Initial release of the platform-api-docs package ([#8012](https://github.com/MetaMask/core/pull/8012))
13
13
 
14
14
  [Unreleased]: https://github.com/MetaMask/core/
package/README.md CHANGED
@@ -35,45 +35,12 @@ Options:
35
35
  --build Generate docs and build static site
36
36
  --serve Generate docs, build, and serve static site
37
37
  --dev Generate docs and start dev server with hot reload
38
- --strategy <name> How to find actions and events: "scan" (default) or
39
- "root-messenger" (see below)
40
- --scan-dir <dir> Extra source directory to scan (repeatable; --strategy scan only)
41
- --root-actions <ref> Type aliasing the union of every action, as "<file>#<TypeName>"
42
- (required with --strategy root-messenger)
43
- --root-events <ref> Type aliasing the union of every event, as "<file>#<TypeName>"
44
- (required with --strategy root-messenger)
38
+ --scan-dir <dir> Extra source directory to scan (repeatable)
45
39
  --output <dir> Output directory (default: <project-path>/.platform-api-docs)
46
40
  --project-label <label> Short label identifying the project (e.g. "Core", "Extension")
47
41
  --help Show this help message
48
42
  ```
49
43
 
50
- ## Strategies
51
-
52
- Which strategy to use depends on whether the project has a single messenger carrying every action and event.
53
-
54
- ### `scan` (default)
55
-
56
- Parses every TypeScript source and declaration file it can find — the scan directories, `packages/*/src`, and `node_modules/@metamask/*/dist` — and reads every `*Messenger` type alias it encounters.
57
-
58
- Use this when no single messenger aggregates every capability, as in a monorepo of independently published packages.
59
-
60
- ### `root-messenger`
61
-
62
- Resolves the two types the project declares for its root messenger capabilities — the collection of every action and the collection of every event — and lets the TypeScript type checker walk them. Only the files named on the command line are opened.
63
-
64
- Use this when the project has one root messenger carrying every action and event, as a client application built on these packages does. It is substantially faster than `scan`, because it reads what the project already declares instead of re-deriving it, and it documents only what is reachable through that messenger.
65
-
66
- ```
67
- platform-api-docs \
68
- --strategy root-messenger \
69
- --root-actions 'src/messenger.ts#RootActions' \
70
- --root-events 'src/messenger.ts#RootEvents'
71
- ```
72
-
73
- Each reference names a type alias, written by hand or computed — the type checker resolves either.
74
-
75
- The docs contain exactly what the named types contain, so those types should be the ones carrying every capability rather than a narrowed subset. Capability types that can't be documented are reported rather than dropped silently: those declared inline in the capability collection type (with no name or JSDoc to document), and those whose shape can't be read (most often a `type` property that isn't a namespaced string literal).
76
-
77
44
  ## Contributing
78
45
 
79
46
  This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
package/dist/cli.cjs ADDED
@@ -0,0 +1,241 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ var __importDefault = (this && this.__importDefault) || function (mod) {
27
+ return (mod && mod.__esModule) ? mod : { "default": mod };
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ const execa_1 = __importDefault(require("execa/index.js"));
31
+ const fs = __importStar(require("node:fs/promises"));
32
+ const path = __importStar(require("node:path"));
33
+ const npm_which_1 = __importDefault(require("npm-which"));
34
+ const yargs_1 = __importDefault(require("yargs"));
35
+ const generate_js_1 = require("./generate.cjs");
36
+ /**
37
+ * Locate the Docusaurus binary in this package's `node_modules/.bin`. Using
38
+ * `npm-which` lets the lookup track wherever the installed Docusaurus puts
39
+ * its binary, so a future Docusaurus upgrade can't break this path.
40
+ *
41
+ * @returns Absolute path to the `docusaurus` executable.
42
+ */
43
+ function resolveDocusaurus() {
44
+ return (0, npm_which_1.default)(__dirname).sync('docusaurus');
45
+ }
46
+ /**
47
+ * Run a Docusaurus command.
48
+ *
49
+ * @param command - The docusaurus command (start, build, serve).
50
+ * @param cwd - The site directory.
51
+ * @param extraEnv - Extra environment variables passed through to the
52
+ * Docusaurus process (e.g. `DOCS_PROJECT_LABEL`, `DOCS_COMMIT_SHA`,
53
+ * `DOCS_REPO_URL`).
54
+ */
55
+ async function runDocusaurus(command, cwd, extraEnv = {}) {
56
+ await (0, execa_1.default)(resolveDocusaurus(), [command], {
57
+ cwd,
58
+ stdio: 'inherit',
59
+ env: { ...process.env, ...extraEnv },
60
+ });
61
+ }
62
+ /**
63
+ * Copy site files into the output directory, skipping `node_modules`, `docs`,
64
+ * and `tsconfig.json`. `docs` is owned by the doc generator and shouldn't be
65
+ * carried over from the source `site/` directory. `tsconfig.json` extends the
66
+ * monorepo's `tsconfig.base.json` via a relative path that only resolves from
67
+ * the source location — it's there for IDE / lint inheritance, not for
68
+ * Docusaurus, which uses `jiti` and doesn't consult the tsconfig at runtime.
69
+ *
70
+ * @param outDir - The output directory to set up.
71
+ */
72
+ async function setupSite(outDir) {
73
+ const packageDir = path.resolve(__dirname, '..');
74
+ const siteDir = path.join(packageDir, 'site');
75
+ const packageNodeModules = path.join(packageDir, 'node_modules');
76
+ const skip = new Set(['node_modules', 'docs', 'tsconfig.json']);
77
+ console.log(`\nSetting up Docusaurus site in ${outDir}...`);
78
+ // `fs.cp` has been available since Node 16.7 and only got the "stable"
79
+ // marker in 22.3 — it's functional throughout our supported Node range
80
+ // (`^18.18 || >=20`), even though the linter flags the older versions.
81
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
82
+ await fs.cp(siteDir, outDir, {
83
+ recursive: true,
84
+ filter: (source) => !skip.has(path.basename(source)),
85
+ });
86
+ // Symlink this package's `node_modules` into the output so the copied
87
+ // `docusaurus.config.ts` and the rest of Docusaurus's bundling pipeline can
88
+ // resolve their deps the same way they do in the source tree. Without it,
89
+ // Node's resolver walks up from the output and can't reach our nested deps
90
+ // when the package is installed as a regular dependency by an external
91
+ // consumer (e.g. `metamask-extension`, `metamask-mobile`).
92
+ const linkPath = path.join(outDir, 'node_modules');
93
+ try {
94
+ // `'junction'` works cross-platform (POSIX ignores it; Windows uses it
95
+ // without admin) — `'dir'` would require admin on Windows.
96
+ await fs.symlink(packageNodeModules, linkPath, 'junction');
97
+ }
98
+ catch (error) {
99
+ if (error.code !== 'EEXIST') {
100
+ throw error;
101
+ }
102
+ }
103
+ // Write a minimal package.json so Docusaurus doesn't warn about a missing one
104
+ const pkgJsonPath = path.join(outDir, 'package.json');
105
+ try {
106
+ await fs.access(pkgJsonPath);
107
+ }
108
+ catch {
109
+ await fs.writeFile(pkgJsonPath, JSON.stringify({ name: 'platform-api-docs-site', private: true }, null, 2));
110
+ }
111
+ }
112
+ /**
113
+ * Resolve the short Git commit SHA the docs are being generated from.
114
+ * Returns null when the project isn't a git repo or git isn't available.
115
+ *
116
+ * @param projectPath - The project root path.
117
+ * @returns The short SHA, or null on failure.
118
+ */
119
+ async function resolveCommitSha(projectPath) {
120
+ try {
121
+ const { stdout } = await (0, execa_1.default)('git', ['rev-parse', '--short', 'HEAD'], {
122
+ cwd: projectPath,
123
+ });
124
+ const trimmed = stdout.trim();
125
+ return trimmed.length > 0 ? trimmed : null;
126
+ }
127
+ catch {
128
+ return null;
129
+ }
130
+ }
131
+ /**
132
+ * Main CLI entry point.
133
+ */
134
+ async function main() {
135
+ const argv = await (0, yargs_1.default)(process.argv.slice(2))
136
+ .command('$0 [project-path]', 'Produces documentation for the platform API, the set of actions and events available in clients through the message bus.', (yargsInstance) => {
137
+ yargsInstance.positional('project-path', {
138
+ type: 'string',
139
+ description: 'Path to the project to scan',
140
+ default: '.',
141
+ });
142
+ })
143
+ .option('build', {
144
+ type: 'boolean',
145
+ description: 'Generate platform API docs and build a production-ready site',
146
+ default: false,
147
+ })
148
+ .option('serve', {
149
+ type: 'boolean',
150
+ description: 'Generate platform API docs and serve a production-ready site',
151
+ default: false,
152
+ })
153
+ .option('dev', {
154
+ type: 'boolean',
155
+ description: 'Generate platform API docs and serve a development-only site',
156
+ default: false,
157
+ })
158
+ .option('scan-dir', {
159
+ type: 'string',
160
+ array: true,
161
+ description: 'Additional directories within the project to scan for messenger actions and events (note: may be specified multiple times)',
162
+ default: [],
163
+ })
164
+ .option('output', {
165
+ type: 'string',
166
+ description: 'Output directory',
167
+ })
168
+ .option('project-label', {
169
+ type: 'string',
170
+ description: 'Short label identifying the project (e.g. "Core", "Extension") — stamped on the site title and headings',
171
+ })
172
+ .option('site-url', {
173
+ type: 'string',
174
+ description: 'Absolute URL the built site will be served from, e.g. https://metamask.github.io',
175
+ })
176
+ .option('site-base-url', {
177
+ type: 'string',
178
+ description: 'Path prefix the built site will be served under, e.g. /core/platform-api/',
179
+ })
180
+ .help().argv;
181
+ const projectPathArg = argv['project-path'];
182
+ const resolvedProjectPath = path.resolve(typeof projectPathArg === 'string' ? projectPathArg : '.');
183
+ const resolvedOutputDir = path.resolve(argv.output ?? path.join(resolvedProjectPath, '.platform-api-docs'));
184
+ const scanDirs = ['src', ...argv['scan-dir']].filter((dir, index, dirs) => dirs.indexOf(dir) === index);
185
+ const projectLabel = typeof argv['project-label'] === 'string' &&
186
+ argv['project-label'].length > 0
187
+ ? argv['project-label']
188
+ : null;
189
+ const commitSha = await resolveCommitSha(resolvedProjectPath);
190
+ const repoUrl = await (0, generate_js_1.resolveRepoUrl)(resolvedProjectPath);
191
+ // Step 1: Generate docs
192
+ await (0, generate_js_1.generate)({
193
+ projectPath: resolvedProjectPath,
194
+ outputDir: resolvedOutputDir,
195
+ scanDirs,
196
+ projectLabel,
197
+ commitSha,
198
+ });
199
+ // Step 2: If --build, --serve, or --dev, set up and run Docusaurus
200
+ if (argv.build || argv.serve || argv.dev) {
201
+ await setupSite(resolvedOutputDir);
202
+ // Translate CLI flags into the environment variables Docusaurus's
203
+ // config reads. Keeping the CLI surface flag-only means consumers
204
+ // (workflow files, package.json scripts) don't have to know how the
205
+ // values are plumbed through to Docusaurus.
206
+ const docusaurusEnv = {};
207
+ if (projectLabel) {
208
+ docusaurusEnv.DOCS_PROJECT_LABEL = projectLabel;
209
+ }
210
+ if (commitSha) {
211
+ docusaurusEnv.DOCS_COMMIT_SHA = commitSha;
212
+ }
213
+ if (repoUrl) {
214
+ docusaurusEnv.DOCS_REPO_URL = repoUrl;
215
+ }
216
+ if (typeof argv['site-url'] === 'string' && argv['site-url'].length > 0) {
217
+ docusaurusEnv.DOCS_URL = argv['site-url'];
218
+ }
219
+ if (typeof argv['site-base-url'] === 'string' &&
220
+ argv['site-base-url'].length > 0) {
221
+ docusaurusEnv.DOCS_BASE_URL = argv['site-base-url'];
222
+ }
223
+ if (argv.dev) {
224
+ console.log('\nStarting dev server...');
225
+ await runDocusaurus('start', resolvedOutputDir, docusaurusEnv);
226
+ }
227
+ else if (argv.build || argv.serve) {
228
+ console.log('\nBuilding static site...');
229
+ await runDocusaurus('build', resolvedOutputDir, docusaurusEnv);
230
+ if (argv.serve) {
231
+ console.log('\nServing static site...');
232
+ await runDocusaurus('serve', resolvedOutputDir, docusaurusEnv);
233
+ }
234
+ }
235
+ }
236
+ }
237
+ main().catch((error) => {
238
+ console.error(error);
239
+ process.exitCode = 1;
240
+ });
241
+ //# sourceMappingURL=cli.cjs.map
@@ -0,0 +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,gDAAyD;AAEzD;;;;;;GAMG;AACH,SAAS,iBAAiB;IACxB,OAAO,IAAA,mBAAQ,EAAC,SAAS,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;;GAQG;AACH,KAAK,UAAU,aAAa,CAC1B,OAAe,EACf,GAAW,EACX,WAAmC,EAAE;IAErC,MAAM,IAAA,eAAK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as path from 'node:path';\nimport npmWhich from 'npm-which';\nimport yargs from 'yargs';\n\nimport { generate, resolveRepoUrl } from './generate.js';\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 packageDir = path.resolve(__dirname, '..');\n const siteDir = path.join(packageDir, 'site');\n const packageNodeModules = path.join(packageDir, 'node_modules');\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 // Symlink this package's `node_modules` into the output so the copied\n // `docusaurus.config.ts` and the rest of Docusaurus's bundling pipeline can\n // resolve their deps the same way they do in the source tree. Without it,\n // Node's resolver walks up from the output and can't reach our nested deps\n // when the package is installed as a regular dependency by an external\n // consumer (e.g. `metamask-extension`, `metamask-mobile`).\n const linkPath = path.join(outDir, 'node_modules');\n try {\n // `'junction'` works cross-platform (POSIX ignores it; Windows uses it\n // without admin) — `'dir'` would require admin on Windows.\n await fs.symlink(packageNodeModules, linkPath, 'junction');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\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.d.cts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.cts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.d.mts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.mts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
@@ -1,11 +1,36 @@
1
1
  #!/usr/bin/env node
2
- import execa from 'execa';
3
- import * as fs from 'node:fs/promises';
4
- import * as path from 'node:path';
5
- import npmWhich from 'npm-which';
6
- import yargs from 'yargs';
7
- import { generate, resolveRepoUrl } from './generate.js';
8
- import { parseRootCapabilitiesTypeReference } from './root-messenger-discovery.js';
2
+ function $__filename(fileUrl) {
3
+ const url = new URL(fileUrl);
4
+ return url.pathname.replace(/^\/([a-zA-Z]:)/u, "$1");
5
+ }
6
+ function $getDirname(path) {
7
+ const sanitisedPath = path.toString().replace(/\\/gu, "/").replace(/\/$/u, "");
8
+ const index = sanitisedPath.lastIndexOf("/");
9
+ if (index === -1) {
10
+ return path;
11
+ }
12
+ if (index === 0) {
13
+ return "/";
14
+ }
15
+ return sanitisedPath.slice(0, index);
16
+ }
17
+ function $__dirname(url) {
18
+ return $getDirname($__filename(url));
19
+ }
20
+ function $importDefault(module) {
21
+ if (module?.__esModule) {
22
+ return module.default;
23
+ }
24
+ return module;
25
+ }
26
+ import $execa from "execa/index.js";
27
+ const execa = $importDefault($execa);
28
+ import * as fs from "node:fs/promises";
29
+ import * as path from "node:path";
30
+ import $npmWhich from "npm-which";
31
+ const npmWhich = $importDefault($npmWhich);
32
+ import yargs from "yargs";
33
+ import { generate, resolveRepoUrl } from "./generate.mjs";
9
34
  /**
10
35
  * Locate the Docusaurus binary in this package's `node_modules/.bin`. Using
11
36
  * `npm-which` lets the lookup track wherever the installed Docusaurus puts
@@ -14,7 +39,7 @@ import { parseRootCapabilitiesTypeReference } from './root-messenger-discovery.j
14
39
  * @returns Absolute path to the `docusaurus` executable.
15
40
  */
16
41
  function resolveDocusaurus() {
17
- return npmWhich(import.meta.dirname).sync('docusaurus');
42
+ return npmWhich($__dirname(import.meta.url)).sync('docusaurus');
18
43
  }
19
44
  /**
20
45
  * Run a Docusaurus command.
@@ -43,11 +68,15 @@ async function runDocusaurus(command, cwd, extraEnv = {}) {
43
68
  * @param outDir - The output directory to set up.
44
69
  */
45
70
  async function setupSite(outDir) {
46
- const packageDir = path.resolve(import.meta.dirname, '..');
71
+ const packageDir = path.resolve($__dirname(import.meta.url), '..');
47
72
  const siteDir = path.join(packageDir, 'site');
48
73
  const packageNodeModules = path.join(packageDir, 'node_modules');
49
74
  const skip = new Set(['node_modules', 'docs', 'tsconfig.json']);
50
75
  console.log(`\nSetting up Docusaurus site in ${outDir}...`);
76
+ // `fs.cp` has been available since Node 16.7 and only got the "stable"
77
+ // marker in 22.3 — it's functional throughout our supported Node range
78
+ // (`^18.18 || >=20`), even though the linter flags the older versions.
79
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
51
80
  await fs.cp(siteDir, outDir, {
52
81
  recursive: true,
53
82
  filter: (source) => !skip.has(path.basename(source)),
@@ -98,45 +127,10 @@ async function resolveCommitSha(projectPath) {
98
127
  }
99
128
  }
100
129
  /**
101
- * Reject flag combinations that don't make sense, so a mistaken invocation
102
- * fails instead of silently producing docs built the wrong way.
103
- *
104
- * Flags belonging to the strategy that wasn't selected are errors rather than
105
- * ignored. Used as a yargs `.check`, so failures print alongside usage.
106
- *
107
- * @param argv - The parsed arguments.
108
- * @param argv.strategy - The selected discovery strategy.
109
- * @param argv.rootActions - The parsed root actions type reference.
110
- * @param argv.rootEvents - The parsed root events type reference.
111
- * @param argv.scanDir - The additional directories to scan.
112
- * @returns True when the combination is valid.
113
- */
114
- function checkStrategyArgs({ strategy, rootActions, rootEvents, scanDir = [], }) {
115
- if (strategy !== 'root-messenger') {
116
- if (rootActions !== undefined || rootEvents !== undefined) {
117
- throw new Error('--root-actions and --root-events only apply to --strategy root-messenger.');
118
- }
119
- return { strategy: 'scan', scanDir };
120
- }
121
- if (rootActions === undefined || rootEvents === undefined) {
122
- throw new Error('--strategy root-messenger requires both --root-actions and --root-events, ' +
123
- 'each written as "<file>#<TypeName>".');
124
- }
125
- if (scanDir.length > 0) {
126
- throw new Error('--scan-dir only applies to --strategy scan; --strategy root-messenger reads ' +
127
- 'only the files named by --root-actions and --root-events.');
128
- }
129
- return { strategy, rootActions, rootEvents };
130
- }
131
- /**
132
- * Parse and validate CLI arguments.
133
- *
134
- * @param argumentsForParsing - Arguments to parse, excluding the Node and
135
- * script paths.
136
- * @returns Parsed arguments, discriminated by discovery strategy.
130
+ * Main CLI entry point.
137
131
  */
138
- async function parseArguments(argumentsForParsing = process.argv.slice(2)) {
139
- const argv = await yargs(argumentsForParsing)
132
+ async function main() {
133
+ const argv = await yargs(process.argv.slice(2))
140
134
  .command('$0 [project-path]', 'Produces documentation for the platform API, the set of actions and events available in clients through the message bus.', (yargsInstance) => {
141
135
  yargsInstance.positional('project-path', {
142
136
  type: 'string',
@@ -158,26 +152,10 @@ async function parseArguments(argumentsForParsing = process.argv.slice(2)) {
158
152
  type: 'boolean',
159
153
  description: 'Generate platform API docs and serve a development-only site',
160
154
  default: false,
161
- })
162
- .option('strategy', {
163
- type: 'string',
164
- description: 'How to find messenger actions and events. "scan" parses every source and declaration file looking for messenger types. "root-messenger" instead resolves the two types the project declares for its root messenger',
165
- default: 'scan',
166
- })
167
- .choices('strategy', ['scan', 'root-messenger'])
168
- .option('root-actions', {
169
- type: 'string',
170
- coerce: parseRootCapabilitiesTypeReference,
171
- description: 'Type aliasing the union of every action on the root messenger, written as "<file>#<TypeName>" (required with --strategy root-messenger)',
172
- })
173
- .option('root-events', {
174
- type: 'string',
175
- coerce: parseRootCapabilitiesTypeReference,
176
- description: 'Type aliasing the union of every event on the root messenger, written as "<file>#<TypeName>" (required with --strategy root-messenger)',
177
155
  })
178
156
  .option('scan-dir', {
179
- type: 'array',
180
- string: true,
157
+ type: 'string',
158
+ array: true,
181
159
  description: 'Additional directories within the project to scan for messenger actions and events (note: may be specified multiple times)',
182
160
  default: [],
183
161
  })
@@ -197,60 +175,25 @@ async function parseArguments(argumentsForParsing = process.argv.slice(2)) {
197
175
  type: 'string',
198
176
  description: 'Path prefix the built site will be served under, e.g. /core/platform-api/',
199
177
  })
200
- .help()
201
- .parse();
202
- const strategyArguments = checkStrategyArgs(argv);
203
- const projectPath = argv['project-path'];
204
- if (typeof projectPath !== 'string') {
205
- throw new Error('Expected --project-path to be a string.');
206
- }
207
- return {
208
- build: argv.build,
209
- serve: argv.serve,
210
- dev: argv.dev,
211
- 'project-path': projectPath,
212
- output: argv.output,
213
- 'project-label': argv['project-label'],
214
- 'site-url': argv['site-url'],
215
- 'site-base-url': argv['site-base-url'],
216
- ...strategyArguments,
217
- };
218
- }
219
- /**
220
- * Main CLI entry point.
221
- */
222
- async function main() {
223
- const argv = await parseArguments();
224
- const resolvedProjectPath = path.resolve(argv['project-path']);
178
+ .help().argv;
179
+ const projectPathArg = argv['project-path'];
180
+ const resolvedProjectPath = path.resolve(typeof projectPathArg === 'string' ? projectPathArg : '.');
225
181
  const resolvedOutputDir = path.resolve(argv.output ?? path.join(resolvedProjectPath, '.platform-api-docs'));
226
- const projectLabel = argv['project-label'] && argv['project-label'].length > 0
182
+ const scanDirs = ['src', ...argv['scan-dir']].filter((dir, index, dirs) => dirs.indexOf(dir) === index);
183
+ const projectLabel = typeof argv['project-label'] === 'string' &&
184
+ argv['project-label'].length > 0
227
185
  ? argv['project-label']
228
186
  : null;
229
187
  const commitSha = await resolveCommitSha(resolvedProjectPath);
230
188
  const repoUrl = await resolveRepoUrl(resolvedProjectPath);
231
189
  // Step 1: Generate docs
232
- if (argv.strategy === 'root-messenger') {
233
- await generate({
234
- projectPath: resolvedProjectPath,
235
- outputDir: resolvedOutputDir,
236
- projectLabel,
237
- commitSha,
238
- strategy: 'root-messenger',
239
- rootActions: argv.rootActions,
240
- rootEvents: argv.rootEvents,
241
- });
242
- }
243
- else {
244
- const scanDirs = ['src', ...argv.scanDir].filter((dir, index, dirs) => dirs.indexOf(dir) === index);
245
- await generate({
246
- projectPath: resolvedProjectPath,
247
- outputDir: resolvedOutputDir,
248
- projectLabel,
249
- commitSha,
250
- strategy: 'scan',
251
- scanDirs,
252
- });
253
- }
190
+ await generate({
191
+ projectPath: resolvedProjectPath,
192
+ outputDir: resolvedOutputDir,
193
+ scanDirs,
194
+ projectLabel,
195
+ commitSha,
196
+ });
254
197
  // Step 2: If --build, --serve, or --dev, set up and run Docusaurus
255
198
  if (argv.build || argv.serve || argv.dev) {
256
199
  await setupSite(resolvedOutputDir);
@@ -293,4 +236,4 @@ main().catch((error) => {
293
236
  console.error(error);
294
237
  process.exitCode = 1;
295
238
  });
296
- //# sourceMappingURL=cli.js.map
239
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.mjs","sourceRoot":"","sources":["../src/cli.ts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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.js';\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 packageDir = path.resolve(__dirname, '..');\n const siteDir = path.join(packageDir, 'site');\n const packageNodeModules = path.join(packageDir, 'node_modules');\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 // Symlink this package's `node_modules` into the output so the copied\n // `docusaurus.config.ts` and the rest of Docusaurus's bundling pipeline can\n // resolve their deps the same way they do in the source tree. Without it,\n // Node's resolver walks up from the output and can't reach our nested deps\n // when the package is installed as a regular dependency by an external\n // consumer (e.g. `metamask-extension`, `metamask-mobile`).\n const linkPath = path.join(outDir, 'node_modules');\n try {\n // `'junction'` works cross-platform (POSIX ignores it; Windows uses it\n // without admin) — `'dir'` would require admin on Windows.\n await fs.symlink(packageNodeModules, linkPath, 'junction');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error;\n }\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"]}