@metamask-previews/platform-api-docs 0.1.0-preview-abca9bcea → 0.2.0-preview-0a30e47

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 (74) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/dist/cli.d.ts +3 -0
  3. package/dist/cli.d.ts.map +1 -0
  4. package/dist/{cli.mjs → cli.js} +10 -40
  5. package/dist/cli.js.map +1 -0
  6. package/dist/{extraction.d.cts → extraction.d.ts} +3 -3
  7. package/dist/extraction.d.ts.map +1 -0
  8. package/dist/{extraction.mjs → extraction.js} +3 -3
  9. package/dist/extraction.js.map +1 -0
  10. package/dist/{generate.d.cts → generate.d.ts} +2 -2
  11. package/dist/generate.d.ts.map +1 -0
  12. package/dist/{generate.mjs → generate.js} +10 -10
  13. package/dist/generate.js.map +1 -0
  14. package/dist/{markdown.d.cts → markdown.d.ts} +2 -2
  15. package/dist/markdown.d.ts.map +1 -0
  16. package/dist/{markdown.mjs → markdown.js} +1 -1
  17. package/dist/markdown.js.map +1 -0
  18. package/dist/{root-messenger-discovery.d.cts → root-messenger-discovery.d.ts} +2 -2
  19. package/dist/root-messenger-discovery.d.ts.map +1 -0
  20. package/dist/{root-messenger-discovery.mjs → root-messenger-discovery.js} +5 -5
  21. package/dist/root-messenger-discovery.js.map +1 -0
  22. package/dist/{ts-project.d.cts → ts-project.d.ts} +2 -2
  23. package/dist/ts-project.d.ts.map +1 -0
  24. package/dist/{ts-project.mjs → ts-project.js} +2 -2
  25. package/dist/ts-project.js.map +1 -0
  26. package/dist/{types.d.cts → types.d.ts} +1 -1
  27. package/dist/types.d.ts.map +1 -0
  28. package/dist/types.js +2 -0
  29. package/dist/types.js.map +1 -0
  30. package/package.json +12 -8
  31. package/dist/cli.cjs +0 -328
  32. package/dist/cli.cjs.map +0 -1
  33. package/dist/cli.d.cts +0 -3
  34. package/dist/cli.d.cts.map +0 -1
  35. package/dist/cli.d.mts +0 -3
  36. package/dist/cli.d.mts.map +0 -1
  37. package/dist/cli.mjs.map +0 -1
  38. package/dist/extraction.cjs +0 -754
  39. package/dist/extraction.cjs.map +0 -1
  40. package/dist/extraction.d.cts.map +0 -1
  41. package/dist/extraction.d.mts +0 -73
  42. package/dist/extraction.d.mts.map +0 -1
  43. package/dist/extraction.mjs.map +0 -1
  44. package/dist/generate.cjs +0 -505
  45. package/dist/generate.cjs.map +0 -1
  46. package/dist/generate.d.cts.map +0 -1
  47. package/dist/generate.d.mts +0 -70
  48. package/dist/generate.d.mts.map +0 -1
  49. package/dist/generate.mjs.map +0 -1
  50. package/dist/markdown.cjs +0 -239
  51. package/dist/markdown.cjs.map +0 -1
  52. package/dist/markdown.d.cts.map +0 -1
  53. package/dist/markdown.d.mts +0 -52
  54. package/dist/markdown.d.mts.map +0 -1
  55. package/dist/markdown.mjs.map +0 -1
  56. package/dist/root-messenger-discovery.cjs +0 -359
  57. package/dist/root-messenger-discovery.cjs.map +0 -1
  58. package/dist/root-messenger-discovery.d.cts.map +0 -1
  59. package/dist/root-messenger-discovery.d.mts +0 -61
  60. package/dist/root-messenger-discovery.d.mts.map +0 -1
  61. package/dist/root-messenger-discovery.mjs.map +0 -1
  62. package/dist/ts-project.cjs +0 -33
  63. package/dist/ts-project.cjs.map +0 -1
  64. package/dist/ts-project.d.cts.map +0 -1
  65. package/dist/ts-project.d.mts +0 -12
  66. package/dist/ts-project.d.mts.map +0 -1
  67. package/dist/ts-project.mjs.map +0 -1
  68. package/dist/types.cjs +0 -3
  69. package/dist/types.cjs.map +0 -1
  70. package/dist/types.d.cts.map +0 -1
  71. package/dist/types.d.mts +0 -47
  72. package/dist/types.d.mts.map +0 -1
  73. package/dist/types.mjs +0 -2
  74. package/dist/types.mjs.map +0 -1
package/dist/generate.cjs DELETED
@@ -1,505 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.generate = exports.resolveRepoUrl = void 0;
27
- const node_1 = require("@metamask/utils/node");
28
- const node_child_process_1 = require("node:child_process");
29
- const fs = __importStar(require("node:fs/promises"));
30
- const path = __importStar(require("node:path"));
31
- const node_util_1 = require("node:util");
32
- const extraction_js_1 = require("./extraction.cjs");
33
- const markdown_js_1 = require("./markdown.cjs");
34
- const root_messenger_discovery_js_1 = require("./root-messenger-discovery.cjs");
35
- const ts_project_js_1 = require("./ts-project.cjs");
36
- /** How many skipped capability types to name before summarizing the rest. */
37
- const MAX_SKIPPED_SHOWN = 10;
38
- /**
39
- * Compute a deduplication score for a messenger item, preferring items with
40
- * JSDoc and from the "home" package whose name matches the namespace.
41
- *
42
- * @param item - The messenger item to score.
43
- * @returns A numeric score (higher is better).
44
- */
45
- function deduplicationScore(item) {
46
- const jsDocScore = item.jsDoc ? 2 : 0;
47
- const namespacePrefix = item.typeString
48
- .split(':')[0]
49
- .replace(/(?:Controller|Service)$/u, '')
50
- .toLowerCase();
51
- const homeScore = namespacePrefix.length > 0 &&
52
- item.sourceFile.toLowerCase().includes(namespacePrefix)
53
- ? 1
54
- : 0;
55
- return jsDocScore + homeScore;
56
- }
57
- const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
58
- /**
59
- * Resolve the default branch of a project's `origin` remote by reading the
60
- * symbolic ref `refs/remotes/origin/HEAD`. Falls back to `main` if the
61
- * symbolic ref isn't set (e.g. in shallow CI clones).
62
- *
63
- * @param projectPath - Absolute path to the project root.
64
- * @returns The default branch name (e.g. "main", "master", "develop").
65
- */
66
- async function resolveDefaultBranch(projectPath) {
67
- try {
68
- const { stdout } = await execFileAsync('git', ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], { cwd: projectPath });
69
- // stdout looks like "origin/main"; strip the leading "origin/".
70
- const trimmed = stdout.trim();
71
- const slash = trimmed.indexOf('/');
72
- return slash === -1
73
- ? // istanbul ignore next: defensive — `symbolic-ref --short` always
74
- // returns `origin/<branch>` when the symbolic ref is set; this
75
- // fallback only matters if git's output format ever changes.
76
- trimmed || 'main'
77
- : trimmed.slice(slash + 1);
78
- }
79
- catch {
80
- return 'main';
81
- }
82
- }
83
- /**
84
- * Resolve the bare GitHub repository URL for a project by reading its
85
- * `origin` remote.
86
- *
87
- * @param projectPath - Absolute path to the project root.
88
- * @returns A URL like "https://github.com/Owner/Repo" or null when the remote
89
- * isn't a GitHub URL or can't be read.
90
- */
91
- async function resolveRepoUrl(projectPath) {
92
- try {
93
- const { stdout: remoteRaw } = await execFileAsync('git', ['remote', 'get-url', 'origin'], { cwd: projectPath });
94
- const remote = remoteRaw.trim();
95
- // Parse owner/repo from SSH or HTTPS remote URLs
96
- // Handles aliases like github.com-Org used in SSH configs
97
- const match = remote.match(/github\.com[^:/]*[:/]([^/]+\/[^/]+?)(?:\.git)?$/u);
98
- if (!match) {
99
- return null;
100
- }
101
- return `https://github.com/${match[1]}`;
102
- }
103
- catch {
104
- return null;
105
- }
106
- }
107
- exports.resolveRepoUrl = resolveRepoUrl;
108
- /**
109
- * Resolve the GitHub blob base URL used for per-line source links.
110
- *
111
- * Prefers the documented commit SHA when one is available so the links point
112
- * at the exact revision the docs were generated from; falls back to the
113
- * default branch otherwise.
114
- *
115
- * @param projectPath - Absolute path to the project root.
116
- * @param commitSha - Optional commit SHA to use as the ref. When null, the
117
- * default branch is used instead.
118
- * @returns A base URL like "https://github.com/Owner/Repo/blob/<ref>/" or null.
119
- */
120
- async function resolveRepoBaseUrl(projectPath, commitSha) {
121
- const repoUrl = await resolveRepoUrl(projectPath);
122
- if (!repoUrl) {
123
- return null;
124
- }
125
- const ref = commitSha ?? (await resolveDefaultBranch(projectPath));
126
- return `${repoUrl}/blob/${ref}/`;
127
- }
128
- /**
129
- * Discover which configured source locations actually exist on disk.
130
- *
131
- * @param projectPath - The project root path.
132
- * @param scanDirs - User-configured scan directories relative to projectPath.
133
- * @returns A ScanSources object describing the locations to scan.
134
- */
135
- async function discoverScanSources(projectPath, scanDirs) {
136
- const existingScanDirs = [];
137
- for (const dir of scanDirs) {
138
- if (await (0, node_1.directoryExists)(path.join(projectPath, dir))) {
139
- existingScanDirs.push(dir);
140
- }
141
- }
142
- const packagesDir = path.join(projectPath, 'packages');
143
- const nodeModulesDir = path.join(projectPath, 'node_modules', '@metamask');
144
- return {
145
- scanDirs: existingScanDirs,
146
- packagesDir: (await (0, node_1.directoryExists)(packagesDir)) ? packagesDir : null,
147
- nodeModulesDir: (await (0, node_1.directoryExists)(nodeModulesDir))
148
- ? nodeModulesDir
149
- : null,
150
- };
151
- }
152
- /**
153
- * Log a human-readable description of which source locations will be scanned.
154
- *
155
- * @param sources - The resolved scan sources.
156
- */
157
- function logScanPlan(sources) {
158
- const summary = [];
159
- for (const dir of sources.scanDirs) {
160
- summary.push(`${dir}/ (.ts)`);
161
- }
162
- if (sources.packagesDir) {
163
- summary.push('packages/*/src (.ts)');
164
- }
165
- if (sources.nodeModulesDir) {
166
- summary.push('node_modules/@metamask/*/dist (.d.cts)');
167
- }
168
- console.log(`Scanning ${summary.join(', ')} for Messenger action/event types...`);
169
- }
170
- /**
171
- * Patterns excluded when scanning TypeScript sources: build output, tests, and
172
- * declaration files (which are only read under `node_modules/@metamask`, via
173
- * the separate set below).
174
- *
175
- * Every pattern is anchored to `root` rather than written as a bare
176
- * `!**‍/*.test.ts`. A matcher resolves an unanchored negation against the
177
- * process's working directory, not against the pattern it accompanies, so an
178
- * unanchored exclusion silently stops excluding anything the moment the scanned
179
- * path falls outside the working directory — which is the normal case, since
180
- * this runs from wherever the consumer invoked it.
181
- *
182
- * `contentRoot` must be the directory the matched *files* live under, not an
183
- * ancestor of it. Anchoring at `packages/` rather than `packages/*‍/src` would
184
- * make the first path segment a package name, so a workspace package called
185
- * `test` or `dist` would match `test/**` and be dropped whole.
186
- *
187
- * @param contentRoot - Resolved directory, or directory glob, that the matched
188
- * files live directly under.
189
- * @returns The exclusion patterns.
190
- */
191
- function buildTsSourceExclusions(contentRoot) {
192
- return [
193
- 'node_modules/**',
194
- 'dist/**',
195
- '__tests__/**',
196
- 'tests/**',
197
- 'test/**',
198
- '__mocks__/**',
199
- '*.test.ts',
200
- '*.test-d.ts',
201
- '*.spec.ts',
202
- '*.d.ts',
203
- ].map((pattern) => `!${contentRoot}/**/${pattern}`);
204
- }
205
- /**
206
- * Add every file matching a set of glob patterns to the project, in a stable
207
- * order.
208
- *
209
- * ts-morph promises nothing about the order it returns matches in, and
210
- * deduplication downstream keeps the first of two equally-scored items, so an
211
- * unsorted list would let the filesystem decide which source link a capability
212
- * gets.
213
- *
214
- * Ordering is by code unit rather than `localeCompare`, which collates
215
- * differently depending on the locale the process happens to run under.
216
- *
217
- * @param project - The shared ts-morph project.
218
- * @param patterns - Glob patterns to match, including `!` exclusions.
219
- * @returns The added source files, sorted by path.
220
- */
221
- function addSourceFiles(project, patterns) {
222
- return project.addSourceFilesAtPaths(patterns).sort((fileA, fileB) =>
223
- // Subtracting the two comparisons keeps this branchless, so it reads
224
- // the same whichever order the matcher happened to return.
225
- Number(fileA.getFilePath() > fileB.getFilePath()) -
226
- Number(fileA.getFilePath() < fileB.getFilePath()));
227
- }
228
- /**
229
- * Build a glob pattern from a directory path.
230
- *
231
- * Two things have to be true of the result. Glob syntax is always
232
- * forward-slashed, including on Windows, where `path.join` would produce
233
- * backslashes that a matcher reads as escapes. And the path must be fully
234
- * resolved: the matcher does not follow a symlinked *ancestor* of the pattern,
235
- * so a project under `/tmp` or `/var` on macOS (both symlinks) would match
236
- * nothing at all.
237
- *
238
- * @param segments - Path segments to join.
239
- * @returns The joined, resolved path with forward slashes.
240
- */
241
- async function toGlobPath(...segments) {
242
- // Safe to resolve without a fallback: `discoverScanSources` has already
243
- // confirmed every directory reaching this point exists.
244
- const resolved = await fs.realpath(path.join(...segments));
245
- return resolved.replace(/\\/gu, '/');
246
- }
247
- /**
248
- * Scan every source location described by `sources` (scan directories first,
249
- * then workspace packages, then published declaration files) and return all
250
- * extracted messenger items.
251
- *
252
- * A single ts-morph Project is shared across every file so the type checker can
253
- * resolve cross-file references (e.g. a `*Messenger` declaration in one file
254
- * walking through an imported umbrella union into an auto-generated
255
- * `*-method-action-types.ts` sibling).
256
- *
257
- * @param projectPath - The project root path.
258
- * @param sources - The set of source locations to scan.
259
- * @returns A flat list of all extracted messenger items.
260
- */
261
- async function scanSources(projectPath, sources) {
262
- const project = (0, ts_project_js_1.createProject)();
263
- const sourceFiles = [];
264
- for (const dir of sources.scanDirs) {
265
- const root = await toGlobPath(projectPath, dir);
266
- sourceFiles.push(...addSourceFiles(project, [
267
- `${root}/**/*.ts`,
268
- ...buildTsSourceExclusions(root),
269
- ]));
270
- }
271
- if (sources.packagesDir) {
272
- const root = await toGlobPath(sources.packagesDir);
273
- // Anchored at each package's `src`, not at `packages` itself, so a package
274
- // whose name collides with an exclusion (`test`, `dist`) isn't dropped.
275
- const contentRoot = `${root}/*/src`;
276
- sourceFiles.push(...addSourceFiles(project, [
277
- `${contentRoot}/**/*.ts`,
278
- ...buildTsSourceExclusions(contentRoot),
279
- ]));
280
- }
281
- if (sources.nodeModulesDir) {
282
- const root = await toGlobPath(sources.nodeModulesDir);
283
- sourceFiles.push(...addSourceFiles(project, [`${root}/*/dist/**/*.d.cts`]));
284
- }
285
- // Matched paths are fully resolved, so the root they are made relative to
286
- // has to be resolved the same way or every source link becomes a `../..`
287
- // walk out of the project.
288
- const resolvedProjectPath = await fs.realpath(projectPath);
289
- const allItems = [];
290
- for (const sourceFile of sourceFiles) {
291
- allItems.push(...(0, extraction_js_1.extractFromSourceFile)(sourceFile, resolvedProjectPath));
292
- }
293
- return allItems;
294
- }
295
- /**
296
- * Replace a previously-seen item in its existing namespace group with a
297
- * higher-scoring duplicate. Handles the case where the duplicate is a
298
- * different kind (action vs event) by moving it between lists.
299
- *
300
- * @param byNamespace - Map of namespace to its group.
301
- * @param previous - The previously stored item.
302
- * @param replacement - The new item to replace it with.
303
- */
304
- function replaceDuplicateInGroup(byNamespace, previous, replacement) {
305
- const namespace = replacement.typeString.split(':')[0];
306
- const group = byNamespace.get(namespace);
307
- // istanbul ignore next: `previous` and `replacement` have the same
308
- // typeString, so they share a namespace, and we always insert the
309
- // namespace into `byNamespace` before recording the original entry.
310
- if (!group) {
311
- return;
312
- }
313
- const previousList = previous.kind === 'action' ? group.actions : group.events;
314
- const index = previousList.indexOf(previous);
315
- // istanbul ignore next: `previous` was added to its kind's list by
316
- // `groupByNamespace` before being recorded in `seen`, so it is always
317
- // present when we look it up here.
318
- if (index === -1) {
319
- return;
320
- }
321
- if (previous.kind === replacement.kind) {
322
- previousList[index] = replacement;
323
- }
324
- else {
325
- previousList.splice(index, 1);
326
- const newList = replacement.kind === 'action' ? group.actions : group.events;
327
- newList.push(replacement);
328
- }
329
- }
330
- /**
331
- * Group items by namespace, deduplicating duplicate typeStrings using
332
- * `deduplicationScore`. Returns groups sorted alphabetically by namespace,
333
- * with each group's items sorted alphabetically by typeString.
334
- *
335
- * @param items - The full list of extracted items.
336
- * @returns The deduplicated and sorted namespace groups.
337
- */
338
- function groupByNamespace(items) {
339
- const byNamespace = new Map();
340
- const seen = new Map();
341
- for (const item of items) {
342
- const existing = seen.get(item.typeString);
343
- if (existing) {
344
- if (deduplicationScore(item) <= deduplicationScore(existing)) {
345
- continue;
346
- }
347
- replaceDuplicateInGroup(byNamespace, existing, item);
348
- seen.set(item.typeString, item);
349
- continue;
350
- }
351
- seen.set(item.typeString, item);
352
- const namespace = item.typeString.split(':')[0];
353
- let group = byNamespace.get(namespace);
354
- if (!group) {
355
- group = { namespace, actions: [], events: [] };
356
- byNamespace.set(namespace, group);
357
- }
358
- if (item.kind === 'action') {
359
- group.actions.push(item);
360
- }
361
- else {
362
- group.events.push(item);
363
- }
364
- }
365
- const namespaces = Array.from(byNamespace.values()).sort((a, b) => a.namespace.localeCompare(b.namespace));
366
- for (const ns of namespaces) {
367
- ns.actions.sort((a, b) => a.typeString.localeCompare(b.typeString));
368
- ns.events.sort((a, b) => a.typeString.localeCompare(b.typeString));
369
- }
370
- return namespaces;
371
- }
372
- /**
373
- * Write generated docs (namespace pages, index page, sidebars) to disk,
374
- * replacing any existing `docs/` directory.
375
- *
376
- * @param namespaces - The grouped namespaces to render.
377
- * @param outputDir - The root output directory.
378
- * @param repoBaseUrl - GitHub blob base URL for source links, or null.
379
- * @param indexOptions - Options stamped on the index page header.
380
- * @param indexOptions.projectLabel - Short label identifying the project.
381
- * @param indexOptions.commitSha - Git commit SHA the docs were generated from.
382
- * @returns Promise that resolves once all files are written.
383
- */
384
- async function writeOutput(namespaces, outputDir, repoBaseUrl, indexOptions) {
385
- const docsDir = path.join(outputDir, 'docs');
386
- if (await (0, node_1.directoryExists)(docsDir)) {
387
- await fs.rm(docsDir, { recursive: true });
388
- }
389
- await fs.mkdir(docsDir, { recursive: true });
390
- for (const ns of namespaces) {
391
- const nsDir = path.join(docsDir, ns.namespace);
392
- await fs.mkdir(nsDir, { recursive: true });
393
- if (ns.actions.length > 0) {
394
- await fs.writeFile(path.join(nsDir, 'actions.md'), (0, markdown_js_1.generateNamespacePage)(ns, 'action', repoBaseUrl));
395
- }
396
- if (ns.events.length > 0) {
397
- await fs.writeFile(path.join(nsDir, 'events.md'), (0, markdown_js_1.generateNamespacePage)(ns, 'event', repoBaseUrl));
398
- }
399
- }
400
- await fs.writeFile(path.join(docsDir, 'index.md'), (0, markdown_js_1.generateIndexPage)(namespaces, indexOptions));
401
- await fs.writeFile(path.join(outputDir, 'sidebars.ts'), (0, markdown_js_1.generateSidebars)(namespaces));
402
- }
403
- /**
404
- * Collect capabilities by scanning the project's files.
405
- *
406
- * @param projectPath - The project root path.
407
- * @param scanDirs - Directories (relative to projectPath) to scan.
408
- * @returns The extracted capabilities.
409
- * @throws If the project has no scannable directories at all.
410
- */
411
- async function collectByScanning(projectPath, scanDirs) {
412
- const sources = await discoverScanSources(projectPath, scanDirs);
413
- if (sources.scanDirs.length === 0 &&
414
- !sources.packagesDir &&
415
- !sources.nodeModulesDir) {
416
- throw new Error(`No scannable directories found in ${projectPath}. ` +
417
- `Looked for: ${scanDirs.join(', ')}, packages/, node_modules/@metamask/`);
418
- }
419
- logScanPlan(sources);
420
- return await scanSources(projectPath, sources);
421
- }
422
- /**
423
- * Using the project's root messenger capability collection types as
424
- * entrypoints, collect the constituent individual capability types and package
425
- * them so that they can be displayed within the documentation site.
426
- *
427
- * @param projectPath - The project root path.
428
- * @param options - The root-messenger strategy options.
429
- * @returns The extracted capabilities.
430
- */
431
- function collectFromRootMessengerCapabilities(projectPath, options) {
432
- const { rootActions, rootEvents } = options;
433
- console.log(`Resolving actions from ${rootActions.filePath}#${rootActions.typeName} ` +
434
- `and events from ${rootEvents.filePath}#${rootEvents.typeName}...`);
435
- const { capabilityPackets, skippedCapabilities } = (0, root_messenger_discovery_js_1.discoverFromRootMessengerCapabilitiesTypes)({
436
- projectPath,
437
- rootActionsTypeReference: rootActions,
438
- rootEventsTypeReference: rootEvents,
439
- });
440
- // Report rather than drop silently: a jump in any of these usually means the
441
- // project changed how it declares its capabilities.
442
- warnSkipped('declared inline, with no name to document', skippedCapabilities.unnamedCapabilities);
443
- warnSkipped('whose shape could not be read', skippedCapabilities.unextractableCapabilities);
444
- // If both capability collection types resolve to nothing, it's always a
445
- // misconfiguration (a wrong type name, or imports that didn't resolve).
446
- // Failing here matters because generation would otherwise replace an existing
447
- // docs directory with an empty one and exit successfully.
448
- if (capabilityPackets.length === 0) {
449
- throw new Error(`No messenger actions or events found in ` +
450
- `${rootActions.filePath}#${rootActions.typeName} or ` +
451
- `${rootEvents.filePath}#${rootEvents.typeName}. ` +
452
- `Check that these types name the collections carrying every ` +
453
- `capability, and that their imports resolve.`);
454
- }
455
- return capabilityPackets;
456
- }
457
- /**
458
- * Warn about capability types that couldn't be documented, naming them so the
459
- * warning is actionable.
460
- *
461
- * @param description - Why they were skipped, as a noun phrase.
462
- * @param labels - Labels identifying each skipped type.
463
- */
464
- function warnSkipped(description, labels) {
465
- if (labels.length === 0) {
466
- return;
467
- }
468
- const shown = labels.slice(0, MAX_SKIPPED_SHOWN);
469
- const remaining = labels.length - shown.length;
470
- console.warn(`Warning: skipped ${labels.length} capability ` +
471
- `${labels.length === 1 ? 'type' : 'types'} ${description}: ` +
472
- `${shown.join(', ')}${remaining > 0 ? `, and ${remaining} more` : ''}`);
473
- }
474
- /**
475
- * Scan a project for messenger action/event types and generate documentation.
476
- *
477
- * @param options - Generation options.
478
- * @returns A promise resolving to counts of generated namespaces, actions, and events.
479
- */
480
- async function generate(options) {
481
- const { projectPath, outputDir, projectLabel, commitSha } = options;
482
- const allItems = options.strategy === 'root-messenger'
483
- ? collectFromRootMessengerCapabilities(projectPath, options)
484
- : await collectByScanning(projectPath, options.scanDirs);
485
- console.log(`Found ${allItems.length} messenger ${allItems.length === 1 ? 'item' : 'items'} total.`);
486
- const namespaces = groupByNamespace(allItems);
487
- const repoBaseUrl = await resolveRepoBaseUrl(projectPath, commitSha ?? null);
488
- await writeOutput(namespaces, outputDir, repoBaseUrl, {
489
- projectLabel,
490
- commitSha,
491
- });
492
- const totalActions = namespaces.reduce((sum, ns) => sum + ns.actions.length, 0);
493
- const totalEvents = namespaces.reduce((sum, ns) => sum + ns.events.length, 0);
494
- console.log(`Generated docs for ${namespaces.length} ${namespaces.length === 1 ? 'namespace' : 'namespaces'}.`);
495
- console.log(` Actions: ${totalActions}`);
496
- console.log(` Events: ${totalEvents}`);
497
- console.log(`Output: ${path.join(outputDir, 'docs')}/`);
498
- return {
499
- namespaces: namespaces.length,
500
- actions: totalActions,
501
- events: totalEvents,
502
- };
503
- }
504
- exports.generate = generate;
505
- //# sourceMappingURL=generate.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.cjs","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAuD;AACvD,2DAA8C;AAC9C,qDAAuC;AACvC,gDAAkC;AAClC,yCAAsC;AAGtC,oDAAwD;AACxD,gDAIuB;AAEvB,gFAA2F;AAC3F,oDAAgD;AAGhD,6EAA6E;AAC7E,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAsE7B;;;;;;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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M,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;AAxCD,4BAwCC","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 { extractFromSourceFile } from './extraction.js';\nimport {\n generateIndexPage,\n generateNamespacePage,\n generateSidebars,\n} from './markdown.js';\nimport type { RootCapabilitiesTypeReference } from './root-messenger-discovery.js';\nimport { discoverFromRootMessengerCapabilitiesTypes } from './root-messenger-discovery.js';\nimport { createProject } from './ts-project.js';\nimport type { MessengerCapabilityPacket, NamespaceGroup } from './types.js';\n\n/** How many skipped capability types to name before summarizing the rest. */\nconst MAX_SKIPPED_SHOWN = 10;\n\n/**\n * Options for the `scan` strategy, which reads every `*Messenger` type alias\n * in every file it can find. Used when no single messenger aggregates every\n * capability.\n */\ntype ScanStrategyOptions = {\n /** The selected strategy. */\n strategy: 'scan';\n /** Directories, relative to the project root, to scan. */\n scanDirs: string[];\n};\n\n/**\n * Options for the `root-messenger` strategy, which walks the types a\n * project declares for its root messenger capabilities instead of scanning the\n * entire repo. Used when one messenger carries every action and event.\n */\ntype RootMessengerStrategyOptions = {\n /** The selected strategy. */\n strategy: 'root-messenger';\n /** The root messenger actions type reference. */\n rootActions: RootCapabilitiesTypeReference;\n /** The root messenger events type reference. */\n rootEvents: RootCapabilitiesTypeReference;\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 /**\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} & (ScanStrategyOptions | RootMessengerStrategyOptions);\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 * 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 * 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 * Patterns excluded when scanning TypeScript sources: build output, tests, and\n * declaration files (which are only read under `node_modules/@metamask`, via\n * the separate set below).\n *\n * Every pattern is anchored to `root` rather than written as a bare\n * `!**‍/*.test.ts`. A matcher resolves an unanchored negation against the\n * process's working directory, not against the pattern it accompanies, so an\n * unanchored exclusion silently stops excluding anything the moment the scanned\n * path falls outside the working directory — which is the normal case, since\n * this runs from wherever the consumer invoked it.\n *\n * `contentRoot` must be the directory the matched *files* live under, not an\n * ancestor of it. Anchoring at `packages/` rather than `packages/*‍/src` would\n * make the first path segment a package name, so a workspace package called\n * `test` or `dist` would match `test/**` and be dropped whole.\n *\n * @param contentRoot - Resolved directory, or directory glob, that the matched\n * files live directly under.\n * @returns The exclusion patterns.\n */\nfunction buildTsSourceExclusions(contentRoot: string): string[] {\n return [\n 'node_modules/**',\n 'dist/**',\n '__tests__/**',\n 'tests/**',\n 'test/**',\n '__mocks__/**',\n '*.test.ts',\n '*.test-d.ts',\n '*.spec.ts',\n '*.d.ts',\n ].map((pattern) => `!${contentRoot}/**/${pattern}`);\n}\n\n/**\n * Add every file matching a set of glob patterns to the project, in a stable\n * order.\n *\n * ts-morph promises nothing about the order it returns matches in, and\n * deduplication downstream keeps the first of two equally-scored items, so an\n * unsorted list would let the filesystem decide which source link a capability\n * gets.\n *\n * Ordering is by code unit rather than `localeCompare`, which collates\n * differently depending on the locale the process happens to run under.\n *\n * @param project - The shared ts-morph project.\n * @param patterns - Glob patterns to match, including `!` exclusions.\n * @returns The added source files, sorted by path.\n */\nfunction addSourceFiles(\n project: Project,\n patterns: string[],\n): ReturnType<Project['addSourceFilesAtPaths']> {\n return project.addSourceFilesAtPaths(patterns).sort(\n (fileA, fileB) =>\n // Subtracting the two comparisons keeps this branchless, so it reads\n // the same whichever order the matcher happened to return.\n Number(fileA.getFilePath() > fileB.getFilePath()) -\n Number(fileA.getFilePath() < fileB.getFilePath()),\n );\n}\n\n/**\n * Build a glob pattern from a directory path.\n *\n * Two things have to be true of the result. Glob syntax is always\n * forward-slashed, including on Windows, where `path.join` would produce\n * backslashes that a matcher reads as escapes. And the path must be fully\n * resolved: the matcher does not follow a symlinked *ancestor* of the pattern,\n * so a project under `/tmp` or `/var` on macOS (both symlinks) would match\n * nothing at all.\n *\n * @param segments - Path segments to join.\n * @returns The joined, resolved path with forward slashes.\n */\nasync function toGlobPath(...segments: string[]): Promise<string> {\n // Safe to resolve without a fallback: `discoverScanSources` has already\n // confirmed every directory reaching this point exists.\n const resolved = await fs.realpath(path.join(...segments));\n return resolved.replace(/\\\\/gu, '/');\n}\n\n/**\n * Scan every source location described by `sources` (scan directories first,\n * then workspace packages, then published declaration files) and return all\n * extracted messenger items.\n *\n * A single ts-morph Project is shared across every file so the type checker can\n * resolve cross-file references (e.g. a `*Messenger` declaration in one file\n * walking through an imported umbrella union into an auto-generated\n * `*-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 = createProject();\n const sourceFiles = [];\n\n for (const dir of sources.scanDirs) {\n const root = await toGlobPath(projectPath, dir);\n sourceFiles.push(\n ...addSourceFiles(project, [\n `${root}/**/*.ts`,\n ...buildTsSourceExclusions(root),\n ]),\n );\n }\n\n if (sources.packagesDir) {\n const root = await toGlobPath(sources.packagesDir);\n // Anchored at each package's `src`, not at `packages` itself, so a package\n // whose name collides with an exclusion (`test`, `dist`) isn't dropped.\n const contentRoot = `${root}/*/src`;\n sourceFiles.push(\n ...addSourceFiles(project, [\n `${contentRoot}/**/*.ts`,\n ...buildTsSourceExclusions(contentRoot),\n ]),\n );\n }\n\n if (sources.nodeModulesDir) {\n const root = await toGlobPath(sources.nodeModulesDir);\n sourceFiles.push(...addSourceFiles(project, [`${root}/*/dist/**/*.d.cts`]));\n }\n\n // Matched paths are fully resolved, so the root they are made relative to\n // has to be resolved the same way or every source link becomes a `../..`\n // walk out of the project.\n const resolvedProjectPath = await fs.realpath(projectPath);\n\n const allItems: MessengerCapabilityPacket[] = [];\n for (const sourceFile of sourceFiles) {\n allItems.push(...extractFromSourceFile(sourceFile, resolvedProjectPath));\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 * Collect capabilities by scanning the project's files.\n *\n * @param projectPath - The project root path.\n * @param scanDirs - Directories (relative to projectPath) to scan.\n * @returns The extracted capabilities.\n * @throws If the project has no scannable directories at all.\n */\nasync function collectByScanning(\n projectPath: string,\n scanDirs: string[],\n): Promise<MessengerCapabilityPacket[]> {\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 return await scanSources(projectPath, sources);\n}\n\n/**\n * Using the project's root messenger capability collection types as\n * entrypoints, collect the constituent individual capability types and package\n * them so that they can be displayed within the documentation site.\n *\n * @param projectPath - The project root path.\n * @param options - The root-messenger strategy options.\n * @returns The extracted capabilities.\n */\nfunction collectFromRootMessengerCapabilities(\n projectPath: string,\n options: RootMessengerStrategyOptions,\n): MessengerCapabilityPacket[] {\n const { rootActions, rootEvents } = options;\n\n console.log(\n `Resolving actions from ${rootActions.filePath}#${rootActions.typeName} ` +\n `and events from ${rootEvents.filePath}#${rootEvents.typeName}...`,\n );\n\n const { capabilityPackets, skippedCapabilities } =\n discoverFromRootMessengerCapabilitiesTypes({\n projectPath,\n rootActionsTypeReference: rootActions,\n rootEventsTypeReference: rootEvents,\n });\n\n // Report rather than drop silently: a jump in any of these usually means the\n // project changed how it declares its capabilities.\n warnSkipped(\n 'declared inline, with no name to document',\n skippedCapabilities.unnamedCapabilities,\n );\n warnSkipped(\n 'whose shape could not be read',\n skippedCapabilities.unextractableCapabilities,\n );\n\n // If both capability collection types resolve to nothing, it's always a\n // misconfiguration (a wrong type name, or imports that didn't resolve).\n // Failing here matters because generation would otherwise replace an existing\n // docs directory with an empty one and exit successfully.\n if (capabilityPackets.length === 0) {\n throw new Error(\n `No messenger actions or events found in ` +\n `${rootActions.filePath}#${rootActions.typeName} or ` +\n `${rootEvents.filePath}#${rootEvents.typeName}. ` +\n `Check that these types name the collections carrying every ` +\n `capability, and that their imports resolve.`,\n );\n }\n\n return capabilityPackets;\n}\n\n/**\n * Warn about capability types that couldn't be documented, naming them so the\n * warning is actionable.\n *\n * @param description - Why they were skipped, as a noun phrase.\n * @param labels - Labels identifying each skipped type.\n */\nfunction warnSkipped(description: string, labels: string[]): void {\n if (labels.length === 0) {\n return;\n }\n\n const shown = labels.slice(0, MAX_SKIPPED_SHOWN);\n const remaining = labels.length - shown.length;\n console.warn(\n `Warning: skipped ${labels.length} capability ` +\n `${labels.length === 1 ? 'type' : 'types'} ${description}: ` +\n `${shown.join(', ')}${remaining > 0 ? `, and ${remaining} more` : ''}`,\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, projectLabel, commitSha } = options;\n\n const allItems =\n options.strategy === 'root-messenger'\n ? collectFromRootMessengerCapabilities(projectPath, options)\n : await collectByScanning(projectPath, options.scanDirs);\n\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.d.cts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,6BAA6B,EAAE,uCAAsC;AAQnF;;;;GAIG;AACH,KAAK,mBAAmB,GAAG;IACzB,6BAA6B;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF;;;;GAIG;AACH,KAAK,4BAA4B,GAAG;IAClC,6BAA6B;IAC7B,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,iDAAiD;IACjD,WAAW,EAAE,6BAA6B,CAAC;IAC3C,gDAAgD;IAChD,UAAU,EAAE,6BAA6B,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,GAAG,CAAC,mBAAmB,GAAG,4BAA4B,CAAC,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAmEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAuBxB;AA+dD;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,cAAc,CAAC,CAsCzB"}
@@ -1,70 +0,0 @@
1
- import type { RootCapabilitiesTypeReference } from "./root-messenger-discovery.mjs";
2
- /**
3
- * Options for the `scan` strategy, which reads every `*Messenger` type alias
4
- * in every file it can find. Used when no single messenger aggregates every
5
- * capability.
6
- */
7
- type ScanStrategyOptions = {
8
- /** The selected strategy. */
9
- strategy: 'scan';
10
- /** Directories, relative to the project root, to scan. */
11
- scanDirs: string[];
12
- };
13
- /**
14
- * Options for the `root-messenger` strategy, which walks the types a
15
- * project declares for its root messenger capabilities instead of scanning the
16
- * entire repo. Used when one messenger carries every action and event.
17
- */
18
- type RootMessengerStrategyOptions = {
19
- /** The selected strategy. */
20
- strategy: 'root-messenger';
21
- /** The root messenger actions type reference. */
22
- rootActions: RootCapabilitiesTypeReference;
23
- /** The root messenger events type reference. */
24
- rootEvents: RootCapabilitiesTypeReference;
25
- };
26
- /**
27
- * Options for the generate function.
28
- */
29
- export type GenerateOptions = {
30
- /** Absolute path to the project to scan. */
31
- projectPath: string;
32
- /** Absolute path to the output directory for generated docs. */
33
- outputDir: string;
34
- /**
35
- * Short label identifying the project the docs were generated from (e.g.
36
- * "Core", "Extension"). Stamped in the index page title.
37
- */
38
- projectLabel?: string | null;
39
- /**
40
- * Git commit SHA the docs were generated from. Stamped in the index page
41
- * intro so engineers know how current the site is.
42
- */
43
- commitSha?: string | null;
44
- } & (ScanStrategyOptions | RootMessengerStrategyOptions);
45
- /**
46
- * Result returned by the generate function.
47
- */
48
- export type GenerateResult = {
49
- namespaces: number;
50
- actions: number;
51
- events: number;
52
- };
53
- /**
54
- * Resolve the bare GitHub repository URL for a project by reading its
55
- * `origin` remote.
56
- *
57
- * @param projectPath - Absolute path to the project root.
58
- * @returns A URL like "https://github.com/Owner/Repo" or null when the remote
59
- * isn't a GitHub URL or can't be read.
60
- */
61
- export declare function resolveRepoUrl(projectPath: string): Promise<string | null>;
62
- /**
63
- * Scan a project for messenger action/event types and generate documentation.
64
- *
65
- * @param options - Generation options.
66
- * @returns A promise resolving to counts of generated namespaces, actions, and events.
67
- */
68
- export declare function generate(options: GenerateOptions): Promise<GenerateResult>;
69
- export {};
70
- //# sourceMappingURL=generate.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.d.mts","sourceRoot":"","sources":["../src/generate.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,6BAA6B,EAAE,uCAAsC;AAQnF;;;;GAIG;AACH,KAAK,mBAAmB,GAAG;IACzB,6BAA6B;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC;AAEF;;;;GAIG;AACH,KAAK,4BAA4B,GAAG;IAClC,6BAA6B;IAC7B,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,iDAAiD;IACjD,WAAW,EAAE,6BAA6B,CAAC;IAC3C,gDAAgD;IAChD,UAAU,EAAE,6BAA6B,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,GAAG,CAAC,mBAAmB,GAAG,4BAA4B,CAAC,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAmEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAuBxB;AA+dD;;;;;GAKG;AACH,wBAAsB,QAAQ,CAC5B,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,cAAc,CAAC,CAsCzB"}