@warlock.js/grimoire 5.64.0 → 5.65.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/esm/contracts/scry.d.mts +22 -1
- package/esm/contracts/scry.d.mts.map +1 -1
- package/esm/devtools/index.d.mts +7 -0
- package/esm/devtools/index.d.mts.map +1 -1
- package/esm/devtools/index.mjs +1 -1
- package/esm/devtools/index.mjs.map +1 -1
- package/esm/devtools/snapshot-source.mjs +8 -2
- package/esm/devtools/snapshot-source.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/scry/also-changes.mjs +3 -2
- package/esm/scry/also-changes.mjs.map +1 -1
- package/esm/scry/format.d.mts.map +1 -1
- package/esm/scry/format.mjs +14 -1
- package/esm/scry/format.mjs.map +1 -1
- package/esm/scry/query.d.mts.map +1 -1
- package/esm/scry/query.mjs +34 -1
- package/esm/scry/query.mjs.map +1 -1
- package/esm/warlock/adapter.d.mts.map +1 -1
- package/esm/warlock/adapter.mjs +11 -4
- package/esm/warlock/adapter.mjs.map +1 -1
- package/esm/warlock/collect-off-thread.mjs +66 -0
- package/esm/warlock/collect-off-thread.mjs.map +1 -0
- package/esm/warlock/mcp-tools.mjs +2 -2
- package/esm/warlock/mcp-tools.mjs.map +1 -1
- package/llms-full.txt +10 -4
- package/package.json +3 -3
- package/skills/use-the-grimoire/SKILL.md +10 -4
package/esm/scry/query.mjs
CHANGED
|
@@ -370,10 +370,42 @@ function scryFlow(snapshot, query) {
|
|
|
370
370
|
findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref)
|
|
371
371
|
};
|
|
372
372
|
}
|
|
373
|
+
/** The most of each list a search answer carries from the top file's impact. */
|
|
374
|
+
const SEARCH_IMPACT_FILES = 8;
|
|
375
|
+
const SEARCH_IMPACT_OTHERS = 5;
|
|
376
|
+
/** The top file's impact, shortened for a search answer; no file already listed twice. */
|
|
377
|
+
function impactOfTop(snapshot, file, hits, alsoChanges) {
|
|
378
|
+
let full;
|
|
379
|
+
try {
|
|
380
|
+
full = scryImpact(snapshot, {
|
|
381
|
+
type: "impact",
|
|
382
|
+
file
|
|
383
|
+
});
|
|
384
|
+
} catch {
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
const listed = /* @__PURE__ */ new Set([
|
|
388
|
+
file,
|
|
389
|
+
...alsoChanges.map((change) => change.file),
|
|
390
|
+
...hits.filter((hit) => hit.type === "file").map((hit) => hit.id)
|
|
391
|
+
]);
|
|
392
|
+
const specs = new Set(snapshot.book.facts.files.filter((item) => item.type === "spec").map((item) => item.file));
|
|
393
|
+
const files = full.importers.all.filter((item) => !listed.has(item) && !specs.has(item));
|
|
394
|
+
const impact = {
|
|
395
|
+
file,
|
|
396
|
+
files: files.slice(0, SEARCH_IMPACT_FILES),
|
|
397
|
+
more: Math.max(0, files.length - SEARCH_IMPACT_FILES),
|
|
398
|
+
routes: full.routes.slice(0, SEARCH_IMPACT_OTHERS).map((route) => `${route.method} ${route.path}`),
|
|
399
|
+
flows: full.flows.slice(0, SEARCH_IMPACT_OTHERS),
|
|
400
|
+
tests: full.tests.filter((item) => !listed.has(item)).slice(0, SEARCH_IMPACT_OTHERS)
|
|
401
|
+
};
|
|
402
|
+
return impact.files.length + impact.routes.length + impact.flows.length + impact.tests.length === 0 ? void 0 : impact;
|
|
403
|
+
}
|
|
373
404
|
function scrySearch(snapshot, query) {
|
|
374
405
|
if (wordsOf(query.text).length === 0) throw new GrimoireError("GR9006", `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`);
|
|
375
406
|
const { counts, hits, weak } = searchSnapshot(snapshot, query);
|
|
376
|
-
const { alsoChanges, next } = alsoChangesOf(snapshot, hits);
|
|
407
|
+
const { alsoChanges, next, topFile } = alsoChangesOf(snapshot, hits);
|
|
408
|
+
const impact = topFile === void 0 ? void 0 : impactOfTop(snapshot, topFile, hits, alsoChanges);
|
|
377
409
|
return {
|
|
378
410
|
type: "search",
|
|
379
411
|
...notesOf(snapshot, false),
|
|
@@ -381,6 +413,7 @@ function scrySearch(snapshot, query) {
|
|
|
381
413
|
counts,
|
|
382
414
|
hits,
|
|
383
415
|
alsoChanges,
|
|
416
|
+
...impact === void 0 ? {} : { impact },
|
|
384
417
|
weak,
|
|
385
418
|
...next === void 0 ? {} : { next }
|
|
386
419
|
};
|
package/esm/scry/query.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRoutePage,\n ScryRouteResult,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\nimport { alsoChangesOf } from \"./also-changes\";\nimport { searchSnapshot, wordsOf } from \"./search\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Route facts with routes but none that names its source file: only the core list was read, not the app's routes files. */\nconst INCOMPLETE_ROUTES = \"route facts look incomplete; run warlock grimoire build\";\n\nfunction routeFactsIncomplete(facts: GrimoireSnapshot[\"book\"][\"facts\"]): boolean {\n return (\n facts.routes !== null &&\n facts.routes.length > 0 &&\n facts.routes.every((route) => route.sourceFile === null)\n );\n}\n\n/** Notes every answer carries: whether the stored book is behind the files, and how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.behind !== undefined) {\n const count = snapshot.behind.changed;\n\n notes.push(\n `book is stale (${count} ${count === 1 ? \"file\" : \"files\"} changed); run warlock grimoire build`,\n );\n }\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n if (snapshot.book.routeNote !== undefined) notes.push(snapshot.book.routeNote);\n if (needsRoutes && routeFactsIncomplete(snapshot.book.facts)) notes.push(INCOMPLETE_ROUTES);\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n // Pages and screens come from the code scan, so a page URL is found with or without route facts.\n const pageMethod = method === \"GET\" || method === \"HEAD\";\n\n if (facts.routes === null) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n\n if (routeFactsIncomplete(facts)) {\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}; ${INCOMPLETE_ROUTES}.`);\n }\n\n const pagePaths = pagesAt(snapshot, { path: query.path }).map(\n (page) => `${page.app} ${page.route}`,\n );\n const hint = [\n samePath.length > 0 ? ` Routes on that path: ${samePath.join(\", \")}.` : \"\",\n pagePaths.length > 0\n ? ` Pages on that path (GET or HEAD only${query.site === undefined ? \"\" : `, none on site ${query.site}`}): ${pagePaths.join(\", \")}.`\n : \"\",\n samePath.length === 0 && pagePaths.length === 0\n ? \" Run warlock routes to list them, or warlock grimoire build when the route is new.\"\n : \"\",\n ].join(\"\");\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n pages: [],\n };\n}\n\n/** Pages and mobile screens whose URL is the asked path, narrowed to `--site` when given. */\nfunction pagesAt(\n snapshot: GrimoireSnapshot,\n query: { path: string; site?: string | undefined },\n): ScryRoutePage[] {\n const facts = snapshot.book.facts;\n const graph = fileGraph(facts.files);\n const wanted = normalizeRoutePath(query.path);\n const site = query.site;\n const closure = (files: (string | null)[]): string[] =>\n importClosure(\n graph,\n files.filter((file): file is string => file !== null),\n );\n\n return [\n ...facts.pages\n .filter(\n (page) =>\n normalizeRoutePath(page.route) === wanted &&\n (site === undefined || page.site === site || siteApp(snapshot, page.site) === site),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n site: page.site,\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n setupFile: page.setupFile,\n layouts: page.layouts,\n files: closure([page.file, page.setupFile, ...page.layouts]),\n })),\n ...facts.mobile.flatMap((app) =>\n site !== undefined && app.id !== site && mobileApp(snapshot, app.id) !== site\n ? []\n : app.screens\n .filter((screen) => normalizeRoutePath(screen.route) === wanted)\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n site: app.id,\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n setupFile: null,\n layouts: screen.layouts,\n files: closure([screen.file, ...screen.layouts]),\n })),\n ),\n ].sort((left, right) => byText(left.app, right.app) || byText(left.file, right.file));\n}\n\n/** The answer for a URL that only pages or screens serve. */\nfunction pageRouteResult(snapshot: GrimoireSnapshot, pages: ScryRoutePage[]): ScryRouteResult {\n const first = pages[0];\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route: null,\n files: sortedUnique(pages.flatMap((page) => page.files)),\n steps: [],\n page:\n first === undefined\n ? null\n : (snapshot.book.facts.pages.find(\n (item) => item.file === first.file && item.site === first.site,\n ) ?? null),\n pages,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n const findings = findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n );\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => {\n const criteria = snapshot.collected.flows[flow.ref]?.criteria ?? [];\n\n return {\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n steps: flow.steps.length,\n cases: flow.cases.length,\n criteria: flow.criteria.length,\n tested: criteria.filter((criterion) => criterion.tests.length > 0).length,\n findings: findings.filter(\n (finding) => !finding.expected && finding.subject.flow === flow.ref,\n ).length,\n };\n }),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings,\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n if (wordsOf(query.text).length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const { counts, hits, weak } = searchSnapshot(snapshot, query);\n const { alsoChanges, next } = alsoChangesOf(snapshot, hits);\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n counts,\n hits,\n alsoChanges,\n weak,\n ...(next === undefined ? {} : { next }),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA+BA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,MAAM,oBAAoB;AAE1B,SAAS,qBAAqB,OAAmD;CAC/E,OACE,MAAM,WAAW,QACjB,MAAM,OAAO,SAAS,KACtB,MAAM,OAAO,OAAO,UAAU,MAAM,eAAe,IAAI;AAE3D;;AAGA,SAAS,QAAQ,UAA4B,aAAiC;CAC5E,MAAM,QAAkB,CAAC;CAEzB,IAAI,SAAS,WAAW,QAAW;EACjC,MAAM,QAAQ,SAAS,OAAO;EAE9B,MA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Y,CAAC,IAAI,EAAE,KAAK;CACvC;AACF;;;;;;AAOA,SAAgB,KAAK,UAA4B,OAA8B;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;EACnC,KAAK,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"query.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/scry/query.ts"],"sourcesContent":["/**\n * Answers one scry query from a snapshot. Pure: reads the snapshot only.\n */\nimport { packagesOf } from \"../book\";\nimport { normalizeRoutePath, routeMatches } from \"../bookmap\";\nimport { checkGrimoire } from \"../check\";\nimport { GrimoireError } from \"../codes\";\nimport type { BookFile, BookRoute } from \"../contracts/adapter\";\nimport { BOOK_SCHEMA_VERSION, type BookEntry } from \"../contracts/book\";\nimport type { FeatureBookmap, FlowBookmap } from \"../contracts/bookmap\";\nimport type { GrimoireFinding } from \"../contracts/findings\";\nimport type {\n ScryFeatureResult,\n ScryFileResult,\n ScryFlowResult,\n ScryImpactResult,\n ScryNotes,\n ScryPageRef,\n ScryQuery,\n ScryResult,\n ScryRoutePage,\n ScryRouteResult,\n ScryHit,\n ScrySearchImpact,\n ScrySearchResult,\n} from \"../contracts/scry\";\nimport type { GrimoireSnapshot } from \"../contracts/snapshot\";\nimport type { WrittenFeature, WrittenFlow } from \"../contracts/written\";\nimport { fileGraph, importClosure, importerClosure } from \"../graph\";\nimport { bookEntryPaths, projectPath, toPosixPath } from \"../paths\";\nimport { alsoChangesOf } from \"./also-changes\";\nimport { searchSnapshot, wordsOf } from \"./search\";\n\nconst byText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0);\nconst sortedUnique = (items: Iterable<string>): string[] => [...new Set(items)].sort(byText);\n\n/** Route facts with routes but none that names its source file: only the core list was read, not the app's routes files. */\nconst INCOMPLETE_ROUTES = \"route facts look incomplete; run warlock grimoire build\";\n\nfunction routeFactsIncomplete(facts: GrimoireSnapshot[\"book\"][\"facts\"]): boolean {\n return (\n facts.routes !== null &&\n facts.routes.length > 0 &&\n facts.routes.every((route) => route.sourceFile === null)\n );\n}\n\n/** Notes every answer carries: whether the stored book is behind the files, and how fresh the route facts are. */\nfunction notesOf(snapshot: GrimoireSnapshot, needsRoutes: boolean): ScryNotes {\n const notes: string[] = [];\n\n if (snapshot.behind !== undefined) {\n const count = snapshot.behind.changed;\n\n notes.push(\n `book is stale (${count} ${count === 1 ? \"file\" : \"files\"} changed); run warlock grimoire build`,\n );\n }\n\n if (snapshot.routes === \"stale\") notes.push(\"route facts are stale; run warlock grimoire build\");\n if (snapshot.routes === \"missing\" && needsRoutes) {\n notes.push(\"route facts were never read; run warlock grimoire build\");\n }\n\n if (snapshot.book.routeNote !== undefined) notes.push(snapshot.book.routeNote);\n if (needsRoutes && routeFactsIncomplete(snapshot.book.facts)) notes.push(INCOMPLETE_ROUTES);\n\n return { routes: snapshot.routes, notes };\n}\n\n/** A project-relative POSIX path for what the caller typed (either separator, absolute or relative). */\nfunction fileOf(snapshot: GrimoireSnapshot, file: string): string {\n return projectPath(snapshot.root, toPosixPath(file.trim()));\n}\n\nfunction bookFile(snapshot: GrimoireSnapshot, file: string): BookFile {\n const found = snapshot.book.facts.files.find((item) => item.file === file);\n\n if (!found) {\n const roots = [\n ...new Set(snapshot.book.facts.files.map((item) => item.file.split(\"/\")[0] ?? \"\")),\n ]\n .filter((root) => root !== \"\")\n .sort(byText);\n\n throw new GrimoireError(\n \"GR9001\",\n `${file} is not in the book. Pass a code file under ${roots.join(\", \") || \"the source roots\"} as a project-relative path; if the file is new, run warlock grimoire build.`,\n );\n }\n\n return found;\n}\n\n/** The written app id that shows a site, or the site id when no written app matches it. */\nfunction siteApp(snapshot: GrimoireSnapshot, site: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.site?.id === site);\n\n return match?.app ?? site;\n}\n\n/** The written app id of a mobile app, or its own id. */\nfunction mobileApp(snapshot: GrimoireSnapshot, mobile: string): string {\n const match = Object.values(snapshot.apps).find((app) => app.mobile?.id === mobile);\n\n return match?.app ?? mobile;\n}\n\n/** The project files a file imports only through type-only imports, sorted. */\nfunction typeOnlyImportsOf(file: BookFile): string[] {\n const value = new Set<string>();\n const typeOnly = new Set<string>();\n\n for (const entry of file.imports) {\n if (entry.file === null) continue;\n\n (entry.typeOnly === true ? typeOnly : value).add(entry.file);\n }\n\n return sortedUnique([...typeOnly].filter((target) => !value.has(target)));\n}\n\n/** The book entry of one file, as the book writes it. */\nfunction entryOf(snapshot: GrimoireSnapshot, file: BookFile): BookEntry {\n const facts = snapshot.book.facts;\n const annotation = snapshot.annotations.files[file.file];\n const routeRef = (route: BookRoute) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n });\n const routes = facts.routes ?? [];\n\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n file: file.file,\n module: file.module,\n type: file.type,\n lines: file.lines,\n about: file.about,\n feature: annotation?.feature ?? null,\n borrowedBy: sortedUnique(annotation?.borrowedBy ?? []),\n flows: sortedUnique(annotation?.flows ?? []),\n exports: file.exports.map((entry) => ({ name: entry.name, about: entry.about })),\n // The same list the book entry holds (bare Node builtins such as `fs` left out too).\n packages: packagesOf(file),\n imports: sortedUnique(\n file.imports.flatMap((entry) => (entry.file === null ? [] : [entry.file])),\n ),\n // The same rule as the book entry: project files whose every import edge is type-only.\n typeOnlyImports: typeOnlyImportsOf(file),\n importedBy: sortedUnique(file.importedBy),\n routes: [\n ...routes\n .filter((route) => route.sourceFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"registers\" as const })),\n ...routes\n .filter((route) => route.handlerFile === file.file)\n .map((route) => ({ ...routeRef(route), via: \"handles\" as const })),\n ],\n pages: facts.pages\n .flatMap((page) => [\n ...(page.file === file.file\n ? [{ site: page.site, route: page.route, via: \"page\" as const }]\n : []),\n ...(page.setupFile === file.file\n ? [{ site: page.site, route: page.route, via: \"setup\" as const }]\n : []),\n ...(page.layouts.includes(file.file)\n ? [{ site: page.site, route: page.route, via: \"layout\" as const }]\n : []),\n ])\n .sort(\n (left, right) =>\n byText(left.site, right.site) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n screens: facts.mobile\n .flatMap((app) =>\n app.screens.flatMap((screen) => [\n ...(screen.file === file.file\n ? [{ app: app.id, route: screen.route, via: \"screen\" as const }]\n : []),\n ...(screen.layouts.includes(file.file)\n ? [{ app: app.id, route: screen.route, via: \"layout\" as const }]\n : []),\n ]),\n )\n .sort(\n (left, right) =>\n byText(left.app, right.app) ||\n byText(left.route, right.route) ||\n byText(left.via, right.via),\n ),\n };\n}\n\n/** Where the book keeps the entry of `file`, or `null` when it has none. */\nfunction bookEntryOf(snapshot: GrimoireSnapshot, file: string): string | null {\n const facts = snapshot.book.facts;\n const roots = new Map(facts.mobile.map((app) => [app.id, app.root]));\n const paths = bookEntryPaths(\n facts.files.map((item) => {\n const root = item.mobileApp === null ? undefined : roots.get(item.mobileApp);\n\n return {\n file: item.file,\n mobileApp:\n item.mobileApp === null || root === undefined ? null : { id: item.mobileApp, root },\n };\n }),\n );\n const entry = paths.get(file);\n\n return entry === undefined || entry.split(\"/\").includes(\"..\") ? null : entry;\n}\n\nfunction scryFile(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"file\" }>,\n): ScryFileResult {\n const file = bookFile(snapshot, fileOf(snapshot, query.file));\n\n return {\n type: \"file\",\n ...notesOf(snapshot, false),\n entry: entryOf(snapshot, file),\n bookEntry: bookEntryOf(snapshot, file.file),\n };\n}\n\nfunction flowBookmaps(snapshot: GrimoireSnapshot): FlowBookmap[] {\n return Object.values(snapshot.collected.flows).sort((left, right) => byText(left.ref, right.ref));\n}\n\nfunction scryImpact(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"impact\" }>,\n): ScryImpactResult {\n const facts = snapshot.book.facts;\n const target = bookFile(snapshot, fileOf(snapshot, query.file));\n const graph = fileGraph(facts.files);\n const reach = new Set(importerClosure(graph, [target.file]));\n const importers = [...reach].filter((file) => file !== target.file).sort(byText);\n const routes = (facts.routes ?? []).filter(\n (route) =>\n !route.isPage &&\n (route.handlerFile !== null\n ? reach.has(route.handlerFile)\n : route.sourceFile !== null && reach.has(route.sourceFile)),\n );\n const pages: ScryPageRef[] = [\n ...facts.pages\n .filter(\n (page) =>\n reach.has(page.file) ||\n (page.setupFile !== null && reach.has(page.setupFile)) ||\n page.layouts.some((layout) => reach.has(layout)),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n })),\n ...facts.mobile.flatMap((app) =>\n app.screens\n .filter(\n (screen) => reach.has(screen.file) || screen.layouts.some((layout) => reach.has(layout)),\n )\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n })),\n ),\n ];\n const flows = flowBookmaps(snapshot)\n .filter((bookmap) =>\n bookmap.steps.some(\n (step) => step.files.includes(target.file) || step.typeOnlyFiles.includes(target.file),\n ),\n )\n .map((bookmap) => bookmap.ref);\n const ownership = snapshot.ownership.files;\n const owner = ownership[target.file]?.owner ?? null;\n // Looked up once per importer: an app with thousands of files stays linear.\n const specFiles = new Set(\n facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const borrowers = sortedUnique([\n ...(ownership[target.file]?.borrowedBy ?? []),\n ...importers.flatMap((file) => {\n const ownerOf = ownership[file]?.owner;\n\n return ownerOf === undefined || ownerOf === null || specFiles.has(file) ? [] : [ownerOf];\n }),\n ]).filter((feature) => feature !== owner);\n const testFiles = new Set(facts.tests);\n const flowSet = new Set(flows);\n const tests = sortedUnique([\n ...importers.filter((file) => testFiles.has(file) || specFiles.has(file)),\n ...snapshot.proofs.filter((proof) => flowSet.has(proof.ref)).map((proof) => proof.at.file),\n ]);\n\n return {\n type: \"impact\",\n ...notesOf(snapshot, true),\n file: target.file,\n importers: { direct: sortedUnique(target.importedBy), all: importers },\n routes: routes.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n handlerFile: route.handlerFile,\n })),\n pages,\n flows,\n features: [\n ...(owner === null ? [] : [{ id: owner, via: \"owner\" as const }]),\n ...borrowers.map((id) => ({ id, via: \"borrower\" as const })),\n ],\n tests,\n };\n}\n\nfunction scryRoute(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"route\" }>,\n): ScryRouteResult {\n const facts = snapshot.book.facts;\n const method = query.method.toUpperCase();\n const asked = `${method} ${query.path}`;\n // Pages and screens come from the code scan, so a page URL is found with or without route facts.\n const pageMethod = method === \"GET\" || method === \"HEAD\";\n\n if (facts.routes === null) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n throw new GrimoireError(\n \"GR9002\",\n `No route facts yet, so ${asked} cannot be looked up. Run warlock grimoire build (it boots the app once to read the routes), then ask again.`,\n );\n }\n\n const route = facts.routes.find((item) => routeMatches(item, method, query.path));\n\n if (!route) {\n const pages = pageMethod ? pagesAt(snapshot, query) : [];\n\n if (pages.length > 0) return pageRouteResult(snapshot, pages);\n\n const samePath = facts.routes\n .filter((item) => normalizeRoutePath(item.path) === normalizeRoutePath(query.path))\n .map((item) => `${item.method} ${item.path}`);\n\n if (routeFactsIncomplete(facts)) {\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}; ${INCOMPLETE_ROUTES}.`);\n }\n\n const pagePaths = pagesAt(snapshot, { path: query.path }).map(\n (page) => `${page.app} ${page.route}`,\n );\n const hint = [\n samePath.length > 0 ? ` Routes on that path: ${samePath.join(\", \")}.` : \"\",\n pagePaths.length > 0\n ? ` Pages on that path (GET or HEAD only${query.site === undefined ? \"\" : `, none on site ${query.site}`}): ${pagePaths.join(\", \")}.`\n : \"\",\n samePath.length === 0 && pagePaths.length === 0\n ? \" Run warlock routes to list them, or warlock grimoire build when the route is new.\"\n : \"\",\n ].join(\"\");\n\n throw new GrimoireError(\"GR9002\", `No route matches ${asked}.${hint}`);\n }\n\n const graph = fileGraph(facts.files);\n const start = route.handlerFile ?? route.sourceFile;\n const files = start === null ? [] : importClosure(graph, [start]);\n const steps = snapshot.written.features.flatMap((feature) =>\n feature.flows.flatMap((flow) =>\n flow.steps\n .filter(\n (step) =>\n step.type === \"route\" &&\n step.route !== null &&\n routeMatches(route, step.route.method, step.route.path),\n )\n .map((step) => ({ flow: flow.ref, index: step.index })),\n ),\n );\n const page = route.isPage\n ? (facts.pages.find((item) => item.file === route.handlerFile) ??\n facts.pages.find(\n (item) => normalizeRoutePath(item.route) === normalizeRoutePath(route.path),\n ) ??\n null)\n : null;\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route,\n files,\n steps: steps.sort((left, right) => byText(left.flow, right.flow) || left.index - right.index),\n page,\n pages: [],\n };\n}\n\n/** Pages and mobile screens whose URL is the asked path, narrowed to `--site` when given. */\nfunction pagesAt(\n snapshot: GrimoireSnapshot,\n query: { path: string; site?: string | undefined },\n): ScryRoutePage[] {\n const facts = snapshot.book.facts;\n const graph = fileGraph(facts.files);\n const wanted = normalizeRoutePath(query.path);\n const site = query.site;\n const closure = (files: (string | null)[]): string[] =>\n importClosure(\n graph,\n files.filter((file): file is string => file !== null),\n );\n\n return [\n ...facts.pages\n .filter(\n (page) =>\n normalizeRoutePath(page.route) === wanted &&\n (site === undefined || page.site === site || siteApp(snapshot, page.site) === site),\n )\n .map((page) => ({\n app: siteApp(snapshot, page.site),\n site: page.site,\n route: page.route,\n file: page.file,\n type: \"page\" as const,\n setupFile: page.setupFile,\n layouts: page.layouts,\n files: closure([page.file, page.setupFile, ...page.layouts]),\n })),\n ...facts.mobile.flatMap((app) =>\n site !== undefined && app.id !== site && mobileApp(snapshot, app.id) !== site\n ? []\n : app.screens\n .filter((screen) => normalizeRoutePath(screen.route) === wanted)\n .map((screen) => ({\n app: mobileApp(snapshot, app.id),\n site: app.id,\n route: screen.route,\n file: screen.file,\n type: \"screen\" as const,\n setupFile: null,\n layouts: screen.layouts,\n files: closure([screen.file, ...screen.layouts]),\n })),\n ),\n ].sort((left, right) => byText(left.app, right.app) || byText(left.file, right.file));\n}\n\n/** The answer for a URL that only pages or screens serve. */\nfunction pageRouteResult(snapshot: GrimoireSnapshot, pages: ScryRoutePage[]): ScryRouteResult {\n const first = pages[0];\n\n return {\n type: \"route\",\n ...notesOf(snapshot, true),\n route: null,\n files: sortedUnique(pages.flatMap((page) => page.files)),\n steps: [],\n page:\n first === undefined\n ? null\n : (snapshot.book.facts.pages.find(\n (item) => item.file === first.file && item.site === first.site,\n ) ?? null),\n pages,\n };\n}\n\nfunction writtenFeature(snapshot: GrimoireSnapshot, id: string): WrittenFeature {\n const feature = snapshot.written.features.find((item) => item.id === id);\n\n if (!feature) {\n const known = snapshot.written.features.map((item) => item.id).sort(byText);\n const list =\n known.length > 0\n ? ` Features: ${known.join(\", \")}.`\n : \" The project has no grimoire/features/ folder yet.\";\n\n throw new GrimoireError(\"GR9003\", `No feature has the id ${JSON.stringify(id)}.${list}`);\n }\n\n return feature;\n}\n\nfunction findingsFor(\n snapshot: GrimoireSnapshot,\n match: (finding: GrimoireFinding) => boolean,\n): GrimoireFinding[] {\n return checkGrimoire(snapshot).findings.filter(match);\n}\n\nfunction emptyFeatureBookmap(feature: string): FeatureBookmap {\n return {\n schemaVersion: BOOK_SCHEMA_VERSION,\n feature,\n own: [],\n borrowed: [],\n routes: [],\n pages: {},\n unreached: [],\n };\n}\n\nfunction scryFeature(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"feature\" }>,\n): ScryFeatureResult {\n const feature = writtenFeature(snapshot, query.feature);\n\n if (feature.readme === null) {\n throw new GrimoireError(\n \"GR9003\",\n `grimoire/features/${feature.id} has no README.md, so the feature cannot be shown. Write the README (see warlock grimoire check), then ask again.`,\n );\n }\n\n const findings = findingsFor(\n snapshot,\n (finding) =>\n finding.subject.feature === feature.id ||\n (finding.subject.flow ?? \"\").startsWith(`${feature.id}/`),\n );\n\n return {\n type: \"feature\",\n ...notesOf(snapshot, false),\n readme: feature.readme,\n flows: [...feature.flows]\n .sort((left, right) => byText(left.id.value, right.id.value))\n .map((flow) => {\n const criteria = snapshot.collected.flows[flow.ref]?.criteria ?? [];\n\n return {\n id: flow.id.value,\n status: flow.status.value,\n since: flow.since.value,\n heading: flow.heading?.value ?? null,\n steps: flow.steps.length,\n cases: flow.cases.length,\n criteria: flow.criteria.length,\n tested: criteria.filter((criterion) => criterion.tests.length > 0).length,\n findings: findings.filter(\n (finding) => !finding.expected && finding.subject.flow === flow.ref,\n ).length,\n };\n }),\n bookmap: snapshot.collected.features[feature.id] ?? emptyFeatureBookmap(feature.id),\n changes: (feature.changelog?.entries ?? []).slice(0, 10),\n tasks: snapshot.collected.tasksIndex.open.filter((task) => task.feature === feature.id),\n findings,\n };\n}\n\nfunction scryFlow(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"flow\" }>,\n): ScryFlowResult {\n const feature = writtenFeature(snapshot, query.feature);\n const flow: WrittenFlow | undefined = feature.flows.find((item) => item.id.value === query.flow);\n\n if (!flow) {\n const known = feature.flows.map((item) => item.id.value).sort(byText);\n const list =\n known.length > 0\n ? ` Flows of ${feature.id}: ${known.join(\", \")}.`\n : ` ${feature.id} has no flows yet.`;\n\n throw new GrimoireError(\"GR9004\", `No flow ${feature.id}/${query.flow}.${list}`);\n }\n\n const bookmap =\n Object.values(snapshot.collected.flows).find(\n (item) => item.feature === feature.id && item.flow === flow.id.value,\n ) ?? snapshot.collected.flows[flow.ref];\n\n if (!bookmap) {\n throw new GrimoireError(\n \"GR9004\",\n `${flow.ref} has no book map yet. Run warlock grimoire build, then ask again.`,\n );\n }\n\n return {\n type: \"flow\",\n ...notesOf(snapshot, true),\n flow,\n bookmap,\n history: (feature.changelog?.entries ?? []).filter((entry) => entry.flow === flow.id.value),\n findings: findingsFor(snapshot, (finding) => finding.subject.flow === flow.ref),\n };\n}\n\n// ── Search ─────────────────────────────────────────────────────────────────\n\n/** The most of each list a search answer carries from the top file's impact. */\nconst SEARCH_IMPACT_FILES = 8;\nconst SEARCH_IMPACT_OTHERS = 5;\n\n/** The top file's impact, shortened for a search answer; no file already listed twice. */\nfunction impactOfTop(\n snapshot: GrimoireSnapshot,\n file: string,\n hits: readonly ScryHit[],\n alsoChanges: readonly { file: string }[],\n): ScrySearchImpact | undefined {\n let full: ScryImpactResult;\n\n try {\n full = scryImpact(snapshot, { type: \"impact\", file });\n } catch {\n return undefined;\n }\n\n const listed = new Set([\n file,\n ...alsoChanges.map((change) => change.file),\n ...hits.filter((hit) => hit.type === \"file\").map((hit) => hit.id),\n ]);\n const specs = new Set(\n snapshot.book.facts.files.filter((item) => item.type === \"spec\").map((item) => item.file),\n );\n const files = full.importers.all.filter((item) => !listed.has(item) && !specs.has(item));\n\n const impact: ScrySearchImpact = {\n file,\n files: files.slice(0, SEARCH_IMPACT_FILES),\n more: Math.max(0, files.length - SEARCH_IMPACT_FILES),\n routes: full.routes\n .slice(0, SEARCH_IMPACT_OTHERS)\n .map((route) => `${route.method} ${route.path}`),\n flows: full.flows.slice(0, SEARCH_IMPACT_OTHERS),\n tests: full.tests.filter((item) => !listed.has(item)).slice(0, SEARCH_IMPACT_OTHERS),\n };\n\n // Nothing beyond what the answer already lists: leave it out, so `next` stays the way to look further.\n return impact.files.length + impact.routes.length + impact.flows.length + impact.tests.length ===\n 0\n ? undefined\n : impact;\n}\n\nfunction scrySearch(\n snapshot: GrimoireSnapshot,\n query: Extract<ScryQuery, { type: \"search\" }>,\n): ScrySearchResult {\n if (wordsOf(query.text).length === 0) {\n throw new GrimoireError(\n \"GR9006\",\n `Search text ${JSON.stringify(query.text)} has no letters or digits; pass a word to look for.`,\n );\n }\n\n const { counts, hits, weak } = searchSnapshot(snapshot, query);\n const { alsoChanges, next, topFile } = alsoChangesOf(snapshot, hits);\n const impact =\n topFile === undefined ? undefined : impactOfTop(snapshot, topFile, hits, alsoChanges);\n\n return {\n type: \"search\",\n ...notesOf(snapshot, false),\n text: query.text,\n counts,\n hits,\n alsoChanges,\n ...(impact === undefined ? {} : { impact }),\n weak,\n ...(next === undefined ? {} : { next }),\n };\n}\n\n/**\n * Answer one query. Throws a `GrimoireError`: `GR9001` for a file not in the\n * book, `GR9002` no route, `GR9003` no feature, `GR9004` no flow, `GR9006`\n * a search with no words. Pure.\n */\nexport function scry(snapshot: GrimoireSnapshot, query: ScryQuery): ScryResult {\n switch (query.type) {\n case \"file\":\n return scryFile(snapshot, query);\n case \"impact\":\n return scryImpact(snapshot, query);\n case \"route\":\n return scryRoute(snapshot, query);\n case \"feature\":\n return scryFeature(snapshot, query);\n case \"flow\":\n return scryFlow(snapshot, query);\n case \"search\":\n return scrySearch(snapshot, query);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,MAAM,UAAU,MAAc,UAA2B,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChG,MAAM,gBAAgB,UAAsC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,MAAM;;AAG3F,MAAM,oBAAoB;AAE1B,SAAS,qBAAqB,OAAmD;CAC/E,OACE,MAAM,WAAW,QACjB,MAAM,OAAO,SAAS,KACtB,MAAM,OAAO,OAAO,UAAU,MAAM,eAAe,IAAI;AAE3D;;AAGA,SAAS,QAAQ,UAA4B,aAAiC;CAC5E,MAAM,QAAkB,CAAC;CAEzB,IAAI,SAAS,WAAW,QAAW;EACjC,MAAM,QAAQ,SAAS,OAAO;EAE9B,MAAM,KACJ,kBAAkB,MAAM,GAAG,UAAU,IAAI,SAAS,QAAQ,sCAC5D;CACF;CAEA,IAAI,SAAS,WAAW,SAAS,MAAM,KAAK,mDAAmD;CAC/F,IAAI,SAAS,WAAW,aAAa,aACnC,MA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,SACH,OAAO,UAAU,UAAU,KAAK;EAClC,KAAK,WACH,OAAO,YAAY,UAAU,KAAK;EACpC,KAAK,QACH,OAAO,SAAS,UAAU,KAAK;EACjC,KAAK,UACH,OAAO,WAAW,UAAU,KAAK;CACrC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"mappings":";;;;;;;;;;YA2CY,kBACV,cACA,mBAAmB,qBAChB,QAAQ;;YAGD;;;;;;;;EAQV,kBAAkB;;EAElB,UAAU;;;;;;EAMV;;;YAuJU;EACV,aAAa,SAAS,mBAAmB,QAAQ;EACjD,0BAA0B;;;;;;;wBAQZ,YACd,aAAY,QAAQ,sBACnB;;wBA0Na,qBAAqB,UAAS,wBAA6B"}
|
package/esm/warlock/adapter.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isCodeFile, isInsideFolder, toPosixPath } from "../paths/index.mjs";
|
|
2
2
|
import { WARLOCK_LOGO_DATA_URI } from "./logo.mjs";
|
|
3
|
+
import { collectOffThread } from "./collect-off-thread.mjs";
|
|
3
4
|
import { collectMobileFacts } from "./mobile-facts.mjs";
|
|
4
5
|
import { readAppLanguages } from "./languages.mjs";
|
|
5
6
|
import path from "node:path";
|
|
@@ -283,10 +284,16 @@ function createWarlockAdapter(options = {}) {
|
|
|
283
284
|
async function files(root) {
|
|
284
285
|
const { collectFiles } = await import("@warlock.js/core/tooling");
|
|
285
286
|
const mobile = await mobileApps(root);
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
287
|
+
const dirs = await sourceFolders(root, mobile);
|
|
288
|
+
const topFiles = (await Promise.all(mobile.map((app) => mobileTopFiles(root, app)))).flat();
|
|
289
|
+
const collected = (await collectOffThread({
|
|
290
|
+
root,
|
|
291
|
+
dirs,
|
|
292
|
+
files: topFiles
|
|
293
|
+
}) ?? collectFiles(root, [], {
|
|
294
|
+
dirs,
|
|
295
|
+
files: topFiles
|
|
296
|
+
})).filter((file) => isCodeFile(file.file)).map((file) => toBookFile(file, mobile));
|
|
290
297
|
lastFiles = {
|
|
291
298
|
root,
|
|
292
299
|
files: collected
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"sourcesContent":["/**\n * The Warlock adapter: turns core's inspect report into the book's facts.\n * It never parses app source itself: files come from `collectFiles()`,\n * routes, events and jobs from `inspectApp()` after the `warlock inspect`\n * boot pass, pages from `inspectApp()` (the web page graph, no boot), and\n * mobile apps from their folders.\n *\n * `@warlock.js/core/tooling` is imported inside the methods, never at the\n * top: this module is reached from `warlock.config.ts`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n InspectFile,\n InspectOptions,\n InspectReport,\n InspectRoute,\n InspectSection,\n} from \"@warlock.js/core/tooling\";\nimport type {\n BookAdapter,\n BookFile,\n BookHost,\n BookMobileApp,\n BookNamedThing,\n BookPage,\n BookRoute,\n BookSite,\n} from \"../contracts/adapter\";\nimport { isCodeFile, isInsideFolder, toPosixPath } from \"../paths\";\nimport { WARLOCK_LOGO_DATA_URI } from \"./logo\";\nimport { collectMobileFacts, type MobileAppOption } from \"./mobile-facts\";\nimport { readAppLanguages } from \"./languages\";\n\n/**\n * Reads the sections of the inspect report that need the app booted\n * (`routes`, `events`, `jobs`) for the project at `root`. The default boots\n * the app once, the `warlock inspect` way (connectors boot, none starts).\n * `warlock mcp` passes its own, which shares the server's boot.\n */\nexport type WarlockInspect = (\n root: string,\n sections: readonly InspectSection[],\n) => Promise<InspectReport>;\n\n/** Options of `createWarlockAdapter()`. */\nexport type WarlockAdapterOptions = {\n /**\n * Mobile apps in the repository: folder, id and routing. Default: every\n * top-level folder with an `app.json` or an `app.config.*` file; it is\n * file-routed when its `package.json` lists `expo-router` (screens come\n * from the files), and code-navigated otherwise (no screens: the agent\n * declares them in `grimoire/apps/<app>/screens/`).\n */\n mobile?: readonly MobileAppOption[];\n /** How the booted sections are read. Default: the `warlock inspect` boot pass, run at most once. Pages never boot. */\n inspect?: WarlockInspect;\n /**\n * Read the route, event and job facts from the registries of the running process instead of booting the app\n * (`inspect` wins when both are set). For code that runs inside `warlock dev`, such as the devtools panel;\n * nothing is booted and no module is loaded twice. Default `false`.\n */\n live?: boolean;\n};\n\n/** The `version` of a `package.json` named `name`, or `null` when the file is not that package's. */\nfunction versionIn(file: string, name: string): string | null {\n try {\n const manifest = JSON.parse(readFileSync(file, \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return manifest.name === name && typeof manifest.version === \"string\" ? manifest.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The installed version of a package, read from its `package.json` without\n * going through its `exports` (published `@warlock.js/core` exports neither\n * `./package.json` nor a `require` condition). It resolves the package's\n * entry and walks up to the `package.json` with that name; when the entry\n * cannot be resolved, it looks in each `node_modules` above `from`.\n *\n * @param from Absolute folder to look from.\n * @param resolve Resolves a bare specifier to a file URL or path (`import.meta.resolve`).\n */\nexport function installedVersion(\n name: string,\n from: string,\n resolve: ((specifier: string) => string) | undefined,\n): string | null {\n try {\n const entry = resolve?.(name);\n\n if (entry !== undefined) {\n let folder = path.dirname(entry.startsWith(\"file:\") ? fileURLToPath(entry) : entry);\n\n for (;;) {\n const version = versionIn(path.join(folder, \"package.json\"), name);\n\n if (version !== null) return version;\n\n const parent = path.dirname(folder);\n\n if (parent === folder) break;\n\n folder = parent;\n }\n }\n } catch {\n // Not resolvable from here: look in the node_modules folders below.\n }\n\n for (let folder = from; ; folder = path.dirname(folder)) {\n const version = versionIn(\n path.join(folder, \"node_modules\", ...name.split(\"/\"), \"package.json\"),\n name,\n );\n\n if (version !== null) return version;\n if (path.dirname(folder) === folder) return null;\n }\n}\n\n/** The framework version, for the book manifest (a core upgrade rebuilds the book). */\nfunction coreVersion(): string {\n const resolve =\n typeof import.meta.resolve === \"function\"\n ? (specifier: string) => import.meta.resolve(specifier)\n : undefined;\n\n return (\n installedVersion(\"@warlock.js/core\", path.dirname(fileURLToPath(import.meta.url)), resolve) ??\n \"unknown\"\n );\n}\n\n/** The app's own `name` and `version` from `<root>/package.json`, or `null` when it has no name. */\nexport function appIdentity(root: string): { name: string; version: string | null } | null {\n try {\n const manifest = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return typeof manifest.name === \"string\" && manifest.name !== \"\"\n ? {\n name: manifest.name,\n version: typeof manifest.version === \"string\" ? manifest.version : null,\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/** The Warlock.js brand (logo and installed version) and the app at `root`, for the view's header and footer. */\nexport function warlockHost(root: string, frameworkVersion: string): BookHost {\n return {\n name: \"Warlock.js\",\n version: frameworkVersion === \"unknown\" ? null : frameworkVersion,\n logo: WARLOCK_LOGO_DATA_URI,\n app: appIdentity(root),\n };\n}\n\n/** Run `work` with `console.log`/`info`/`debug` on stderr, so a boot never mixes with `--json` output. */\nasync function withConsoleOnStderr<T>(work: () => Promise<T>): Promise<T> {\n const { log, info, debug } = console;\n const toStderr = (...args: unknown[]) => console.error(...args);\n\n console.log = toStderr;\n console.info = toStderr;\n console.debug = toStderr;\n\n try {\n return await work();\n } finally {\n console.log = log;\n console.info = info;\n console.debug = debug;\n }\n}\n\n/** The default booted `inspect`: one boot pass, shared by every call. */\nfunction bootedInspect(): WarlockInspect {\n let boot: Promise<unknown> | undefined;\n\n return async (root, sections) => {\n const tooling = await import(\"@warlock.js/core/tooling\");\n\n boot ??= withConsoleOnStderr(() => tooling.bootForInspect(root));\n\n const booted = (await boot) as Awaited<ReturnType<typeof tooling.bootForInspect>>;\n\n if (!booted.context.booted) {\n const failures = booted.context.moduleFailures.map(\n (failure) => `${failure.file}: ${failure.message}`,\n );\n\n throw new Error(\n `the app did not boot${failures.length > 0 ? ` (${failures.join(\"; \")})` : \"\"}. Run warlock doctor to see why.`,\n );\n }\n\n return tooling.inspectApp({ ...tooling.inspectOptionsFromBoot(booted), cwd: root, sections });\n };\n}\n\n/** The slice of `@warlock.js/core/tooling` that {@link liveInspect} reads (a seam for specs). */\nexport type LiveInspectTooling = {\n inspectApp: (options: InspectOptions) => Promise<InspectReport>;\n liveInspectOptions: () => InspectOptions;\n};\n\n/**\n * The `inspect` for code running inside the app's own process (`warlock dev`): reads the live router and the\n * event listeners recorded since dev start. It never boots a connector and never imports the route or event\n * modules again, so the running app is not touched.\n */\nexport function liveInspect(\n load: () => Promise<LiveInspectTooling> = () => import(\"@warlock.js/core/tooling\"),\n): WarlockInspect {\n return async (root, sections) => {\n const tooling = await load();\n\n return tooling.inspectApp({ ...tooling.liveInspectOptions(), cwd: root, sections });\n };\n}\n\n/** `send-receipt.job.ts` → `send-receipt` (the stem without the role suffix). */\nfunction stemOf(file: string, ...suffixes: string[]): string {\n const base = path.posix.basename(file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n\n for (const suffix of suffixes) {\n if (base.endsWith(`.${suffix}`)) return base.slice(0, -suffix.length - 1);\n }\n\n return base;\n}\n\n/**\n * The book's role of a file: the framework's role, with CLI command files\n * (`*.command.ts`, or a file directly in `<module>/commands/`) told apart from\n * plain source.\n */\nexport function bookRole(file: Pick<InspectFile, \"file\" | \"role\">): string {\n if (file.role !== \"source\") return file.role;\n\n const stem = path.posix.basename(file.file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n const folders = file.file.split(\"/\").slice(0, -1);\n\n return stem.endsWith(\".command\") || (folders.length === 4 && folders[3] === \"commands\")\n ? \"command\"\n : file.role;\n}\n\nfunction toBookFile(file: InspectFile, mobile: readonly BookMobileApp[]): BookFile {\n const docs = file.exportDocs ?? {};\n const app = mobile.find((item) => isInsideFolder(file.file, item.root));\n\n return {\n file: file.file,\n module: file.module,\n type: bookRole(file),\n lines: file.lines ?? 0,\n about: file.about ?? null,\n tags: file.tags ?? {},\n exports: file.exports.map((name) => ({ name, about: docs[name] ?? null })),\n imports: file.imports.map((entry) =>\n entry.typeOnly === true\n ? { specifier: entry.specifier, file: entry.file, typeOnly: true }\n : { specifier: entry.specifier, file: entry.file },\n ),\n importedBy: [...file.importedBy],\n mobileApp: app?.id ?? null,\n };\n}\n\n/** Files by the names they export, built once per `routes()` call. */\ntype ExportIndex = () => ReadonlyMap<string, readonly string[]>;\n\nfunction exportIndex(files: ReadonlyMap<string, BookFile>): ExportIndex {\n let index: Map<string, string[]> | undefined;\n\n return () => {\n if (index) return index;\n\n index = new Map();\n\n for (const file of files.values()) {\n for (const entry of file.exports) {\n const list = index.get(entry.name) ?? [];\n\n list.push(file.file);\n index.set(entry.name, list);\n }\n }\n\n return index;\n };\n}\n\n/** The file that defines a route's handler: the controller's file for a tuple, else the file exporting the handler. */\nfunction handlerFileOf(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): string | null {\n if (route.isPage) {\n return pages.find((page) => page.route === route.path)?.file ?? null;\n }\n\n const exportsName = (file: string | null | undefined, name: string): boolean =>\n file !== null &&\n file !== undefined &&\n files.get(file)?.exports.some((entry) => entry.name === name) === true;\n const imported =\n route.sourceFile === null\n ? []\n : (files.get(route.sourceFile)?.imports ?? []).map((entry) => entry.file);\n const name = route.controller ?? route.handler;\n\n if (!name || name === \"anonymous\") return null;\n\n const fromImports = imported.find((file) => exportsName(file, name));\n\n if (fromImports) return fromImports;\n if (exportsName(route.sourceFile, name)) return route.sourceFile;\n\n // Not imported by the routes file: the one file in the project exporting it, when there is only one.\n const anywhere = [...new Set(exporters().get(name) ?? [])];\n\n return anywhere.length === 1 ? (anywhere[0] ?? null) : null;\n}\n\nfunction toBookRoute(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): BookRoute {\n const controller = route.controller ?? null;\n const action = route.action ?? null;\n const handler =\n controller !== null && action !== null && !route.handler.includes(\".\")\n ? `${controller}.${action}`\n : route.handler;\n\n return {\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n sourceFile: route.sourceFile === null ? null : toPosixPath(route.sourceFile),\n handler,\n controller,\n action,\n handlerFile: handlerFileOf(route, files, pages, exporters),\n middleware: [...route.middleware],\n auth: { required: route.auth.required, userTypes: [...route.auth.userTypes] },\n isPage: route.isPage,\n description: route.description,\n };\n}\n\nasync function folderNames(dir: string): Promise<string[]> {\n try {\n return (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The site folders of a multi-site app (`src/web/$sites/<id>`), sorted; empty for a single site. */\nfunction siteFolders(root: string): Promise<string[]> {\n return folderNames(path.join(root, \"src\", \"web\", \"$sites\"));\n}\n\n/** `web.sites` from the loaded config, or `undefined` when `src/config/web.ts` is not loaded. */\nasync function webSitesConfig(): Promise<\n Record<string, { basePath?: unknown } | undefined> | undefined\n> {\n const { config } = await import(\"@warlock.js/core\");\n const sites: unknown = config.key(\"web.sites\");\n\n return typeof sites === \"object\" && sites !== null\n ? (sites as Record<string, { basePath?: unknown }>)\n : undefined;\n}\n\n/**\n * Folders of a mobile app that hold native projects, build output or tool\n * caches, never app source. `node_modules` and dot folders are skipped too.\n */\nconst MOBILE_SKIPPED_FOLDERS = new Set([\n \"android\",\n \"ios\",\n \"build\",\n \"dist\",\n \"web-build\",\n \"coverage\",\n \"node_modules\",\n]);\n\n/**\n * The source folders of a mobile app: its top-level folders minus native\n * projects and build output (`android/`, `ios/` with Pods and builds can hold\n * hundreds of megabytes). Code files directly in the app folder (`App.tsx`)\n * are not folders; {@link mobileTopFiles} lists them.\n */\nasync function mobileSourceFolders(root: string, app: BookMobileApp): Promise<string[]> {\n return (await folderNames(path.join(root, ...app.root.split(\"/\"))))\n .filter((name) => !name.startsWith(\".\") && !MOBILE_SKIPPED_FOLDERS.has(name))\n .map((name) => `${app.root}/${name}`);\n}\n\n/** Code files directly in a mobile app folder (`App.tsx`, `index.ts`), without tool configs and type shims. */\nasync function mobileTopFiles(root: string, app: BookMobileApp): Promise<string[]> {\n try {\n return (await readdir(path.join(root, ...app.root.split(\"/\")), { withFileTypes: true }))\n .filter(\n (entry) =>\n entry.isFile() &&\n !entry.name.startsWith(\".\") &&\n isCodeFile(entry.name) &&\n !entry.name.endsWith(\".d.ts\") &&\n !/\\.config\\.[^.]+$/.test(entry.name),\n )\n .map((entry) => `${app.root}/${entry.name}`)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The adapter over `inspectApp()`, `collectFiles()` and the mobile app folders. */\nexport function createWarlockAdapter(options: WarlockAdapterOptions = {}): BookAdapter {\n const inspect = options.inspect ?? (options.live === true ? liveInspect() : bootedInspect());\n const mobileOptions = options.mobile === undefined ? {} : { mobile: options.mobile };\n let lastFiles: { root: string; files: BookFile[] } | null = null;\n let lastPages: { root: string; pages: BookPage[] } | null = null;\n\n const mobileApps = (root: string) => collectMobileFacts(root, mobileOptions);\n\n /** `src` and each mobile app's source folders: what `files()` reads and the book fingerprints. */\n async function sourceFolders(root: string, mobile: readonly BookMobileApp[]): Promise<string[]> {\n const folders = await Promise.all(mobile.map((app) => mobileSourceFolders(root, app)));\n\n return [\"src\", ...folders.flat()];\n }\n\n async function files(root: string): Promise<BookFile[]> {\n const { collectFiles } = await import(\"@warlock.js/core/tooling\");\n const mobile = await mobileApps(root);\n const dirs = await sourceFolders(root, mobile);\n const topFiles = (await Promise.all(mobile.map((app) => mobileTopFiles(root, app)))).flat();\n const collected = collectFiles(root, [], { dirs, files: topFiles })\n .filter((file) => isCodeFile(file.file))\n .map((file) => toBookFile(file, mobile));\n\n lastFiles = { root, files: collected };\n\n return collected;\n }\n\n /** File facts for the routes: the last `files()` answer, else the book's cache, else a new scan. */\n async function currentFiles(root: string): Promise<BookFile[]> {\n if (lastFiles?.root === root) return lastFiles.files;\n\n const { loadBook } = await import(\"../book\");\n const book = await loadBook(root);\n\n return book?.facts.files ?? files(root);\n }\n\n async function pages(root: string): Promise<BookPage[]> {\n // A multi-site app's routes depend on `web.sites` (base paths), which only `src/config/web.ts` holds.\n if ((await siteFolders(root)).length > 0 && (await webSitesConfig()) === undefined) {\n throw new Error(\n \"This app has several sites (src/web/$sites), and their page routes need src/config/web.ts, which is not loaded. Run the command through the warlock CLI, which loads it.\",\n );\n }\n\n // Pages come from the web page graph: files only, never a boot.\n const { inspectApp } = await import(\"@warlock.js/core/tooling\");\n const report = await inspectApp({ cwd: root, sections: [\"pages\"] });\n const found = (report.pages ?? []).map((page): BookPage => ({\n site: page.site ?? \"default\",\n route: page.path,\n name: page.name,\n file: toPosixPath(page.file),\n setupFile: page.setupFile === null ? null : toPosixPath(page.setupFile),\n layouts: page.layouts.map(toPosixPath),\n loaders: page.loaders.map(toPosixPath),\n actions: [...page.actions],\n requires: page.guard === null ? [] : [page.guard],\n reachedFrom: null,\n }));\n\n lastPages = { root, pages: found };\n\n return found;\n }\n\n return {\n name: \"warlock\",\n version: coreVersion(),\n host: (root) => warlockHost(root, coreVersion()),\n languages: (root) => readAppLanguages(root),\n async sourceRoots(root) {\n return sourceFolders(root, await mobileApps(root));\n },\n files,\n async routes(root) {\n const report = await inspect(root, [\"routes\"]);\n const known = new Map((await currentFiles(root)).map((file) => [file.file, file]));\n // Pages only name the file of a page route; a page problem is reported by `pages()` itself.\n const sitePages =\n lastPages?.root === root ? lastPages.pages : await pages(root).catch(() => []);\n\n const exporters = exportIndex(known);\n\n return (report.routes ?? []).map((route) => toBookRoute(route, known, sitePages, exporters));\n },\n async named(root) {\n const report = await inspect(root, [\"events\", \"jobs\", \"schedules\"]);\n const known = await currentFiles(root);\n const ofType = (type: string) => known.filter((file) => file.type === type);\n const named: BookNamedThing[] = [];\n\n // `*.mail.ts`, `*.email.ts` and the files of a `mails/` or `emails/` folder are all typed as mails.\n for (const file of ofType(\"mail\")) {\n named.push({\n type: \"mail\",\n name: stemOf(file.file, \"mail\", \"email\"),\n file: file.file,\n });\n }\n\n const jobFiles = ofType(\"job\");\n const jobFileOf = (name: string): string | null =>\n jobFiles.find((item) => {\n const stem = stemOf(item.file, \"job\");\n\n return name === stem || name.endsWith(`.${stem}`) || name.endsWith(`/${stem}`);\n })?.file ?? null;\n const seen = new Set<string>();\n\n // Queue jobs (`defineJob()`) and scheduled tasks are both jobs a flow can name.\n for (const name of [\n ...(report.jobs ?? []).map((job) => job.name),\n ...(report.schedules ?? []).map((schedule) => schedule.name),\n ]) {\n if (seen.has(name)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: jobFileOf(name) });\n }\n\n // A job file the registries do not list is still a job by its file name.\n for (const file of jobFiles) {\n const name = stemOf(file.file, \"job\");\n\n if (seen.has(name) || [...seen].some((item) => jobFileOf(item) === file.file)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: file.file });\n }\n\n for (const event of report.events ?? []) {\n const source = event.listeners[0]?.sourceFile;\n\n named.push({\n type: \"event\",\n name: event.event,\n file: source === undefined ? null : toPosixPath(source),\n });\n }\n\n for (const file of known) {\n if (/\\.notification\\.[cm]?[jt]sx?$/.test(file.file)) {\n named.push({\n type: \"notification\",\n name: stemOf(file.file, \"notification\"),\n file: file.file,\n });\n }\n }\n\n return named;\n },\n async sites(root): Promise<BookSite[]> {\n const multi = await siteFolders(root);\n\n if (multi.length > 0) {\n const configured = await webSitesConfig();\n\n return multi.map((id) => {\n const basePath: unknown = configured?.[id]?.basePath;\n\n return {\n id,\n root: `src/web/$sites/${id}`,\n basePath: typeof basePath === \"string\" ? basePath : null,\n };\n });\n }\n\n return (await folderNames(path.join(root, \"src\"))).includes(\"web\")\n ? [{ id: \"default\", root: \"src/web\", basePath: null }]\n : [];\n },\n pages,\n mobile: mobileApps,\n async tests(root) {\n const known = await currentFiles(root);\n const specs = known.filter((file) => file.type === \"spec\").map((file) => file.file);\n const outside: string[] = [];\n\n const walk = async (dir: string, pattern: RegExp): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(path.join(root, dir), { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n\n const relative = `${dir}/${entry.name}`;\n\n if (entry.isDirectory()) await walk(relative, pattern);\n else if (entry.isFile() && pattern.test(entry.name)) outside.push(relative);\n }\n };\n\n await walk(\"e2e\", /\\.e2e\\.(?:ts|mts|js|mjs)$/);\n await walk(\"tests\", /\\.(?:test|spec)\\.ts$/);\n\n return [...new Set([...specs, ...outside])].sort();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoEA,SAAS,UAAU,MAAc,MAA6B;CAC5D,IAAI;EACF,MAAM,WAAW,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;EAKtD,OAAO,SAAS,SAAS,QAAQ,OAAO,SAAS,YAAY,WAAW,SAAS,UAAU;CAC7F,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,iBACd,MACA,MACA,SACe;CACf,IAAI;EACF,MAAM,QAAQ,UAAU,IAAI;EAE5B,IAAI,UAAU,QAAW;GACvB,IAAI,SAAS,KAAK,QAAQ,MAAM,WAAW,OAAO,IAAI,cAAc,KAAK,IAAI,KAAK;GAElF,SAAS;IACP,MAAM,UAAU,UAAU,KAAK,KAAK,QAAQ,cAAc,GAAG,IAAI;IAEjE,IAAI,YAAY,MAAM,OAAO;IAE7B,MAAM,SAAS,KAAK,QAAQ,MAAM;IAElC,IAAI,WAAW,QAAQ;IAEvB,SAAS;GACX;EACF;CACF,QAAQ,CAER;CAEA,KAAK,IAAI,SAAS,OAAQ,SAAS,KAAK,QAAQ,MAAM,GAAG;EACvD,MAAM,UAAU,UACd,KAAK,KAAK,QAAQ,gB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":3,"file":"adapter.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/adapter.ts"],"sourcesContent":["/**\n * The Warlock adapter: turns core's inspect report into the book's facts.\n * It never parses app source itself: files come from `collectFiles()`,\n * routes, events and jobs from `inspectApp()` after the `warlock inspect`\n * boot pass, pages from `inspectApp()` (the web page graph, no boot), and\n * mobile apps from their folders.\n *\n * `@warlock.js/core/tooling` is imported inside the methods, never at the\n * top: this module is reached from `warlock.config.ts`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type {\n InspectFile,\n InspectOptions,\n InspectReport,\n InspectRoute,\n InspectSection,\n} from \"@warlock.js/core/tooling\";\nimport type {\n BookAdapter,\n BookFile,\n BookHost,\n BookMobileApp,\n BookNamedThing,\n BookPage,\n BookRoute,\n BookSite,\n} from \"../contracts/adapter\";\nimport { isCodeFile, isInsideFolder, toPosixPath } from \"../paths\";\nimport { WARLOCK_LOGO_DATA_URI } from \"./logo\";\nimport { collectOffThread } from \"./collect-off-thread\";\nimport { collectMobileFacts, type MobileAppOption } from \"./mobile-facts\";\nimport { readAppLanguages } from \"./languages\";\n\n/**\n * Reads the sections of the inspect report that need the app booted\n * (`routes`, `events`, `jobs`) for the project at `root`. The default boots\n * the app once, the `warlock inspect` way (connectors boot, none starts).\n * `warlock mcp` passes its own, which shares the server's boot.\n */\nexport type WarlockInspect = (\n root: string,\n sections: readonly InspectSection[],\n) => Promise<InspectReport>;\n\n/** Options of `createWarlockAdapter()`. */\nexport type WarlockAdapterOptions = {\n /**\n * Mobile apps in the repository: folder, id and routing. Default: every\n * top-level folder with an `app.json` or an `app.config.*` file; it is\n * file-routed when its `package.json` lists `expo-router` (screens come\n * from the files), and code-navigated otherwise (no screens: the agent\n * declares them in `grimoire/apps/<app>/screens/`).\n */\n mobile?: readonly MobileAppOption[];\n /** How the booted sections are read. Default: the `warlock inspect` boot pass, run at most once. Pages never boot. */\n inspect?: WarlockInspect;\n /**\n * Read the route, event and job facts from the registries of the running process instead of booting the app\n * (`inspect` wins when both are set). For code that runs inside `warlock dev`, such as the devtools panel;\n * nothing is booted and no module is loaded twice. Default `false`.\n */\n live?: boolean;\n};\n\n/** The `version` of a `package.json` named `name`, or `null` when the file is not that package's. */\nfunction versionIn(file: string, name: string): string | null {\n try {\n const manifest = JSON.parse(readFileSync(file, \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return manifest.name === name && typeof manifest.version === \"string\" ? manifest.version : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The installed version of a package, read from its `package.json` without\n * going through its `exports` (published `@warlock.js/core` exports neither\n * `./package.json` nor a `require` condition). It resolves the package's\n * entry and walks up to the `package.json` with that name; when the entry\n * cannot be resolved, it looks in each `node_modules` above `from`.\n *\n * @param from Absolute folder to look from.\n * @param resolve Resolves a bare specifier to a file URL or path (`import.meta.resolve`).\n */\nexport function installedVersion(\n name: string,\n from: string,\n resolve: ((specifier: string) => string) | undefined,\n): string | null {\n try {\n const entry = resolve?.(name);\n\n if (entry !== undefined) {\n let folder = path.dirname(entry.startsWith(\"file:\") ? fileURLToPath(entry) : entry);\n\n for (;;) {\n const version = versionIn(path.join(folder, \"package.json\"), name);\n\n if (version !== null) return version;\n\n const parent = path.dirname(folder);\n\n if (parent === folder) break;\n\n folder = parent;\n }\n }\n } catch {\n // Not resolvable from here: look in the node_modules folders below.\n }\n\n for (let folder = from; ; folder = path.dirname(folder)) {\n const version = versionIn(\n path.join(folder, \"node_modules\", ...name.split(\"/\"), \"package.json\"),\n name,\n );\n\n if (version !== null) return version;\n if (path.dirname(folder) === folder) return null;\n }\n}\n\n/** The framework version, for the book manifest (a core upgrade rebuilds the book). */\nfunction coreVersion(): string {\n const resolve =\n typeof import.meta.resolve === \"function\"\n ? (specifier: string) => import.meta.resolve(specifier)\n : undefined;\n\n return (\n installedVersion(\"@warlock.js/core\", path.dirname(fileURLToPath(import.meta.url)), resolve) ??\n \"unknown\"\n );\n}\n\n/** The app's own `name` and `version` from `<root>/package.json`, or `null` when it has no name. */\nexport function appIdentity(root: string): { name: string; version: string | null } | null {\n try {\n const manifest = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n\n return typeof manifest.name === \"string\" && manifest.name !== \"\"\n ? {\n name: manifest.name,\n version: typeof manifest.version === \"string\" ? manifest.version : null,\n }\n : null;\n } catch {\n return null;\n }\n}\n\n/** The Warlock.js brand (logo and installed version) and the app at `root`, for the view's header and footer. */\nexport function warlockHost(root: string, frameworkVersion: string): BookHost {\n return {\n name: \"Warlock.js\",\n version: frameworkVersion === \"unknown\" ? null : frameworkVersion,\n logo: WARLOCK_LOGO_DATA_URI,\n app: appIdentity(root),\n };\n}\n\n/** Run `work` with `console.log`/`info`/`debug` on stderr, so a boot never mixes with `--json` output. */\nasync function withConsoleOnStderr<T>(work: () => Promise<T>): Promise<T> {\n const { log, info, debug } = console;\n const toStderr = (...args: unknown[]) => console.error(...args);\n\n console.log = toStderr;\n console.info = toStderr;\n console.debug = toStderr;\n\n try {\n return await work();\n } finally {\n console.log = log;\n console.info = info;\n console.debug = debug;\n }\n}\n\n/** The default booted `inspect`: one boot pass, shared by every call. */\nfunction bootedInspect(): WarlockInspect {\n let boot: Promise<unknown> | undefined;\n\n return async (root, sections) => {\n const tooling = await import(\"@warlock.js/core/tooling\");\n\n boot ??= withConsoleOnStderr(() => tooling.bootForInspect(root));\n\n const booted = (await boot) as Awaited<ReturnType<typeof tooling.bootForInspect>>;\n\n if (!booted.context.booted) {\n const failures = booted.context.moduleFailures.map(\n (failure) => `${failure.file}: ${failure.message}`,\n );\n\n throw new Error(\n `the app did not boot${failures.length > 0 ? ` (${failures.join(\"; \")})` : \"\"}. Run warlock doctor to see why.`,\n );\n }\n\n return tooling.inspectApp({ ...tooling.inspectOptionsFromBoot(booted), cwd: root, sections });\n };\n}\n\n/** The slice of `@warlock.js/core/tooling` that {@link liveInspect} reads (a seam for specs). */\nexport type LiveInspectTooling = {\n inspectApp: (options: InspectOptions) => Promise<InspectReport>;\n liveInspectOptions: () => InspectOptions;\n};\n\n/**\n * The `inspect` for code running inside the app's own process (`warlock dev`): reads the live router and the\n * event listeners recorded since dev start. It never boots a connector and never imports the route or event\n * modules again, so the running app is not touched.\n */\nexport function liveInspect(\n load: () => Promise<LiveInspectTooling> = () => import(\"@warlock.js/core/tooling\"),\n): WarlockInspect {\n return async (root, sections) => {\n const tooling = await load();\n\n return tooling.inspectApp({ ...tooling.liveInspectOptions(), cwd: root, sections });\n };\n}\n\n/** `send-receipt.job.ts` → `send-receipt` (the stem without the role suffix). */\nfunction stemOf(file: string, ...suffixes: string[]): string {\n const base = path.posix.basename(file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n\n for (const suffix of suffixes) {\n if (base.endsWith(`.${suffix}`)) return base.slice(0, -suffix.length - 1);\n }\n\n return base;\n}\n\n/**\n * The book's role of a file: the framework's role, with CLI command files\n * (`*.command.ts`, or a file directly in `<module>/commands/`) told apart from\n * plain source.\n */\nexport function bookRole(file: Pick<InspectFile, \"file\" | \"role\">): string {\n if (file.role !== \"source\") return file.role;\n\n const stem = path.posix.basename(file.file).replace(/\\.(?:d\\.ts|[cm]?[jt]sx?)$/, \"\");\n const folders = file.file.split(\"/\").slice(0, -1);\n\n return stem.endsWith(\".command\") || (folders.length === 4 && folders[3] === \"commands\")\n ? \"command\"\n : file.role;\n}\n\nfunction toBookFile(file: InspectFile, mobile: readonly BookMobileApp[]): BookFile {\n const docs = file.exportDocs ?? {};\n const app = mobile.find((item) => isInsideFolder(file.file, item.root));\n\n return {\n file: file.file,\n module: file.module,\n type: bookRole(file),\n lines: file.lines ?? 0,\n about: file.about ?? null,\n tags: file.tags ?? {},\n exports: file.exports.map((name) => ({ name, about: docs[name] ?? null })),\n imports: file.imports.map((entry) =>\n entry.typeOnly === true\n ? { specifier: entry.specifier, file: entry.file, typeOnly: true }\n : { specifier: entry.specifier, file: entry.file },\n ),\n importedBy: [...file.importedBy],\n mobileApp: app?.id ?? null,\n };\n}\n\n/** Files by the names they export, built once per `routes()` call. */\ntype ExportIndex = () => ReadonlyMap<string, readonly string[]>;\n\nfunction exportIndex(files: ReadonlyMap<string, BookFile>): ExportIndex {\n let index: Map<string, string[]> | undefined;\n\n return () => {\n if (index) return index;\n\n index = new Map();\n\n for (const file of files.values()) {\n for (const entry of file.exports) {\n const list = index.get(entry.name) ?? [];\n\n list.push(file.file);\n index.set(entry.name, list);\n }\n }\n\n return index;\n };\n}\n\n/** The file that defines a route's handler: the controller's file for a tuple, else the file exporting the handler. */\nfunction handlerFileOf(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): string | null {\n if (route.isPage) {\n return pages.find((page) => page.route === route.path)?.file ?? null;\n }\n\n const exportsName = (file: string | null | undefined, name: string): boolean =>\n file !== null &&\n file !== undefined &&\n files.get(file)?.exports.some((entry) => entry.name === name) === true;\n const imported =\n route.sourceFile === null\n ? []\n : (files.get(route.sourceFile)?.imports ?? []).map((entry) => entry.file);\n const name = route.controller ?? route.handler;\n\n if (!name || name === \"anonymous\") return null;\n\n const fromImports = imported.find((file) => exportsName(file, name));\n\n if (fromImports) return fromImports;\n if (exportsName(route.sourceFile, name)) return route.sourceFile;\n\n // Not imported by the routes file: the one file in the project exporting it, when there is only one.\n const anywhere = [...new Set(exporters().get(name) ?? [])];\n\n return anywhere.length === 1 ? (anywhere[0] ?? null) : null;\n}\n\nfunction toBookRoute(\n route: InspectRoute,\n files: ReadonlyMap<string, BookFile>,\n pages: readonly BookPage[],\n exporters: ExportIndex,\n): BookRoute {\n const controller = route.controller ?? null;\n const action = route.action ?? null;\n const handler =\n controller !== null && action !== null && !route.handler.includes(\".\")\n ? `${controller}.${action}`\n : route.handler;\n\n return {\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n sourceFile: route.sourceFile === null ? null : toPosixPath(route.sourceFile),\n handler,\n controller,\n action,\n handlerFile: handlerFileOf(route, files, pages, exporters),\n middleware: [...route.middleware],\n auth: { required: route.auth.required, userTypes: [...route.auth.userTypes] },\n isPage: route.isPage,\n description: route.description,\n };\n}\n\nasync function folderNames(dir: string): Promise<string[]> {\n try {\n return (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The site folders of a multi-site app (`src/web/$sites/<id>`), sorted; empty for a single site. */\nfunction siteFolders(root: string): Promise<string[]> {\n return folderNames(path.join(root, \"src\", \"web\", \"$sites\"));\n}\n\n/** `web.sites` from the loaded config, or `undefined` when `src/config/web.ts` is not loaded. */\nasync function webSitesConfig(): Promise<\n Record<string, { basePath?: unknown } | undefined> | undefined\n> {\n const { config } = await import(\"@warlock.js/core\");\n const sites: unknown = config.key(\"web.sites\");\n\n return typeof sites === \"object\" && sites !== null\n ? (sites as Record<string, { basePath?: unknown }>)\n : undefined;\n}\n\n/**\n * Folders of a mobile app that hold native projects, build output or tool\n * caches, never app source. `node_modules` and dot folders are skipped too.\n */\nconst MOBILE_SKIPPED_FOLDERS = new Set([\n \"android\",\n \"ios\",\n \"build\",\n \"dist\",\n \"web-build\",\n \"coverage\",\n \"node_modules\",\n]);\n\n/**\n * The source folders of a mobile app: its top-level folders minus native\n * projects and build output (`android/`, `ios/` with Pods and builds can hold\n * hundreds of megabytes). Code files directly in the app folder (`App.tsx`)\n * are not folders; {@link mobileTopFiles} lists them.\n */\nasync function mobileSourceFolders(root: string, app: BookMobileApp): Promise<string[]> {\n return (await folderNames(path.join(root, ...app.root.split(\"/\"))))\n .filter((name) => !name.startsWith(\".\") && !MOBILE_SKIPPED_FOLDERS.has(name))\n .map((name) => `${app.root}/${name}`);\n}\n\n/** Code files directly in a mobile app folder (`App.tsx`, `index.ts`), without tool configs and type shims. */\nasync function mobileTopFiles(root: string, app: BookMobileApp): Promise<string[]> {\n try {\n return (await readdir(path.join(root, ...app.root.split(\"/\")), { withFileTypes: true }))\n .filter(\n (entry) =>\n entry.isFile() &&\n !entry.name.startsWith(\".\") &&\n isCodeFile(entry.name) &&\n !entry.name.endsWith(\".d.ts\") &&\n !/\\.config\\.[^.]+$/.test(entry.name),\n )\n .map((entry) => `${app.root}/${entry.name}`)\n .sort();\n } catch {\n return [];\n }\n}\n\n/** The adapter over `inspectApp()`, `collectFiles()` and the mobile app folders. */\nexport function createWarlockAdapter(options: WarlockAdapterOptions = {}): BookAdapter {\n const inspect = options.inspect ?? (options.live === true ? liveInspect() : bootedInspect());\n const mobileOptions = options.mobile === undefined ? {} : { mobile: options.mobile };\n let lastFiles: { root: string; files: BookFile[] } | null = null;\n let lastPages: { root: string; pages: BookPage[] } | null = null;\n\n const mobileApps = (root: string) => collectMobileFacts(root, mobileOptions);\n\n /** `src` and each mobile app's source folders: what `files()` reads and the book fingerprints. */\n async function sourceFolders(root: string, mobile: readonly BookMobileApp[]): Promise<string[]> {\n const folders = await Promise.all(mobile.map((app) => mobileSourceFolders(root, app)));\n\n return [\"src\", ...folders.flat()];\n }\n\n async function files(root: string): Promise<BookFile[]> {\n const { collectFiles } = await import(\"@warlock.js/core/tooling\");\n const mobile = await mobileApps(root);\n const dirs = await sourceFolders(root, mobile);\n const topFiles = (await Promise.all(mobile.map((app) => mobileTopFiles(root, app)))).flat();\n // The scan runs in a worker thread when it can, so a large app's scan never blocks the event loop.\n const scanned =\n (await collectOffThread<InspectFile>({ root, dirs, files: topFiles })) ??\n collectFiles(root, [], { dirs, files: topFiles });\n const collected = scanned\n .filter((file) => isCodeFile(file.file))\n .map((file) => toBookFile(file, mobile));\n\n lastFiles = { root, files: collected };\n\n return collected;\n }\n\n /** File facts for the routes: the last `files()` answer, else the book's cache, else a new scan. */\n async function currentFiles(root: string): Promise<BookFile[]> {\n if (lastFiles?.root === root) return lastFiles.files;\n\n const { loadBook } = await import(\"../book\");\n const book = await loadBook(root);\n\n return book?.facts.files ?? files(root);\n }\n\n async function pages(root: string): Promise<BookPage[]> {\n // A multi-site app's routes depend on `web.sites` (base paths), which only `src/config/web.ts` holds.\n if ((await siteFolders(root)).length > 0 && (await webSitesConfig()) === undefined) {\n throw new Error(\n \"This app has several sites (src/web/$sites), and their page routes need src/config/web.ts, which is not loaded. Run the command through the warlock CLI, which loads it.\",\n );\n }\n\n // Pages come from the web page graph: files only, never a boot.\n const { inspectApp } = await import(\"@warlock.js/core/tooling\");\n const report = await inspectApp({ cwd: root, sections: [\"pages\"] });\n const found = (report.pages ?? []).map((page): BookPage => ({\n site: page.site ?? \"default\",\n route: page.path,\n name: page.name,\n file: toPosixPath(page.file),\n setupFile: page.setupFile === null ? null : toPosixPath(page.setupFile),\n layouts: page.layouts.map(toPosixPath),\n loaders: page.loaders.map(toPosixPath),\n actions: [...page.actions],\n requires: page.guard === null ? [] : [page.guard],\n reachedFrom: null,\n }));\n\n lastPages = { root, pages: found };\n\n return found;\n }\n\n return {\n name: \"warlock\",\n version: coreVersion(),\n host: (root) => warlockHost(root, coreVersion()),\n languages: (root) => readAppLanguages(root),\n async sourceRoots(root) {\n return sourceFolders(root, await mobileApps(root));\n },\n files,\n async routes(root) {\n const report = await inspect(root, [\"routes\"]);\n const known = new Map((await currentFiles(root)).map((file) => [file.file, file]));\n // Pages only name the file of a page route; a page problem is reported by `pages()` itself.\n const sitePages =\n lastPages?.root === root ? lastPages.pages : await pages(root).catch(() => []);\n\n const exporters = exportIndex(known);\n\n return (report.routes ?? []).map((route) => toBookRoute(route, known, sitePages, exporters));\n },\n async named(root) {\n const report = await inspect(root, [\"events\", \"jobs\", \"schedules\"]);\n const known = await currentFiles(root);\n const ofType = (type: string) => known.filter((file) => file.type === type);\n const named: BookNamedThing[] = [];\n\n // `*.mail.ts`, `*.email.ts` and the files of a `mails/` or `emails/` folder are all typed as mails.\n for (const file of ofType(\"mail\")) {\n named.push({\n type: \"mail\",\n name: stemOf(file.file, \"mail\", \"email\"),\n file: file.file,\n });\n }\n\n const jobFiles = ofType(\"job\");\n const jobFileOf = (name: string): string | null =>\n jobFiles.find((item) => {\n const stem = stemOf(item.file, \"job\");\n\n return name === stem || name.endsWith(`.${stem}`) || name.endsWith(`/${stem}`);\n })?.file ?? null;\n const seen = new Set<string>();\n\n // Queue jobs (`defineJob()`) and scheduled tasks are both jobs a flow can name.\n for (const name of [\n ...(report.jobs ?? []).map((job) => job.name),\n ...(report.schedules ?? []).map((schedule) => schedule.name),\n ]) {\n if (seen.has(name)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: jobFileOf(name) });\n }\n\n // A job file the registries do not list is still a job by its file name.\n for (const file of jobFiles) {\n const name = stemOf(file.file, \"job\");\n\n if (seen.has(name) || [...seen].some((item) => jobFileOf(item) === file.file)) continue;\n\n seen.add(name);\n named.push({ type: \"job\", name, file: file.file });\n }\n\n for (const event of report.events ?? []) {\n const source = event.listeners[0]?.sourceFile;\n\n named.push({\n type: \"event\",\n name: event.event,\n file: source === undefined ? null : toPosixPath(source),\n });\n }\n\n for (const file of known) {\n if (/\\.notification\\.[cm]?[jt]sx?$/.test(file.file)) {\n named.push({\n type: \"notification\",\n name: stemOf(file.file, \"notification\"),\n file: file.file,\n });\n }\n }\n\n return named;\n },\n async sites(root): Promise<BookSite[]> {\n const multi = await siteFolders(root);\n\n if (multi.length > 0) {\n const configured = await webSitesConfig();\n\n return multi.map((id) => {\n const basePath: unknown = configured?.[id]?.basePath;\n\n return {\n id,\n root: `src/web/$sites/${id}`,\n basePath: typeof basePath === \"string\" ? basePath : null,\n };\n });\n }\n\n return (await folderNames(path.join(root, \"src\"))).includes(\"web\")\n ? [{ id: \"default\", root: \"src/web\", basePath: null }]\n : [];\n },\n pages,\n mobile: mobileApps,\n async tests(root) {\n const known = await currentFiles(root);\n const specs = known.filter((file) => file.type === \"spec\").map((file) => file.file);\n const outside: string[] = [];\n\n const walk = async (dir: string, pattern: RegExp): Promise<void> => {\n let entries;\n\n try {\n entries = await readdir(path.join(root, dir), { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n\n const relative = `${dir}/${entry.name}`;\n\n if (entry.isDirectory()) await walk(relative, pattern);\n else if (entry.isFile() && pattern.test(entry.name)) outside.push(relative);\n }\n };\n\n await walk(\"e2e\", /\\.e2e\\.(?:ts|mts|js|mjs)$/);\n await walk(\"tests\", /\\.(?:test|spec)\\.ts$/);\n\n return [...new Set([...specs, ...outside])].sort();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAS,UAAU,MAAc,MAA6B;CAC5D,IAAI;EACF,MAAM,WAAW,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;EAKtD,OAAO,SAAS,SAAS,QAAQ,OAAO,SAAS,YAAY,WAAW,SAAS,UAAU;CAC7F,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,iBACd,MACA,MACA,SACe;CACf,IAAI;EACF,MAAM,QAAQ,UAAU,IAAI;EAE5B,IAAI,UAAU,QAAW;GACvB,IAAI,SAAS,KAAK,QAAQ,MAAM,WAAW,OAAO,IAAI,cAAc,KAAK,IAAI,KAAK;GAElF,SAAS;IACP,MAAM,UAAU,UAAU,KAAK,KAAK,QAAQ,cAAc,GAAG,IAAI;IAEjE,IAAI,YAAY,MAAM,OAAO;IAE7B,MAAM,SAAS,KAAK,QAAQ,MAAM;IAElC,IAAI,WAAW,QAAQ;IAEvB,SAAS;GACX;EACF;CACF,QAAQ,CAER;CAEA,KAAK,IAAI,SAAS,OAAQ,SAAS,KAAK,QAAQ,MAAM,GAAG;EACvD,MAAM,UAAU,UACd,KAAK,KAAK,QAAQ,gBAAgB,GAAG,KAAK,MAAM,GAAG,GAAG,cAAc,GACpE,IACF;EAEA,IAAI,YAAY,MAAM,OAAO;EAC7B,IAAI,KAAK,QAAQ,MAAM,MAAM,QAAQ,OAAO;CAC9C;AACF;;AAGA,SAAS,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#region ../../packages/grimoire/src/warlock/collect-off-thread.ts
|
|
4
|
+
/**
|
|
5
|
+
* Runs the source scan (`collectFiles`) in a worker thread, so a large app's scan never blocks the event loop of
|
|
6
|
+
* the process that serves the app. The scan reads and parses every source file synchronously; on thousands of
|
|
7
|
+
* files that is seconds. The worker only reads files; the result comes back as plain data.
|
|
8
|
+
*
|
|
9
|
+
* Returns `null` when the worker cannot run (the tooling entry does not resolve to a plain module a worker can
|
|
10
|
+
* load, or the worker fails); the caller then scans in the current thread, which gives the same answer.
|
|
11
|
+
*/
|
|
12
|
+
/** The worker's body: load the tooling entry, scan, post the files back. */
|
|
13
|
+
const WORKER_SOURCE = `
|
|
14
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
15
|
+
import(workerData.entry)
|
|
16
|
+
.then(({ collectFiles }) => {
|
|
17
|
+
parentPort.postMessage({ files: collectFiles(workerData.root, [], workerData.options) });
|
|
18
|
+
})
|
|
19
|
+
.catch((error) => {
|
|
20
|
+
parentPort.postMessage({ error: String(error && error.message ? error.message : error) });
|
|
21
|
+
});
|
|
22
|
+
`;
|
|
23
|
+
/** Scan in a worker thread; `null` when it could not (scan in the current thread instead). */
|
|
24
|
+
async function collectOffThread(scan) {
|
|
25
|
+
let entry;
|
|
26
|
+
try {
|
|
27
|
+
if (typeof import.meta.resolve !== "function") return null;
|
|
28
|
+
entry = import.meta.resolve("@warlock.js/core/tooling");
|
|
29
|
+
if (/\.[cm]?tsx?$/.test(entry)) return null;
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return new Promise((resolve) => {
|
|
34
|
+
let worker;
|
|
35
|
+
try {
|
|
36
|
+
worker = new Worker(WORKER_SOURCE, {
|
|
37
|
+
eval: true,
|
|
38
|
+
workerData: {
|
|
39
|
+
entry,
|
|
40
|
+
root: scan.root,
|
|
41
|
+
options: {
|
|
42
|
+
dirs: [...scan.dirs],
|
|
43
|
+
files: [...scan.files]
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
} catch {
|
|
48
|
+
resolve(null);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
let settled = false;
|
|
52
|
+
const finish = (files) => {
|
|
53
|
+
if (settled) return;
|
|
54
|
+
settled = true;
|
|
55
|
+
worker.terminate();
|
|
56
|
+
resolve(files);
|
|
57
|
+
};
|
|
58
|
+
worker.once("message", (message) => finish(message.files ?? null));
|
|
59
|
+
worker.once("error", () => finish(null));
|
|
60
|
+
worker.once("exit", () => finish(null));
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
export { collectOffThread };
|
|
66
|
+
//# sourceMappingURL=collect-off-thread.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collect-off-thread.mjs","names":[],"sources":["../../../../../../../../packages/grimoire/src/warlock/collect-off-thread.ts"],"sourcesContent":["/**\n * Runs the source scan (`collectFiles`) in a worker thread, so a large app's scan never blocks the event loop of\n * the process that serves the app. The scan reads and parses every source file synchronously; on thousands of\n * files that is seconds. The worker only reads files; the result comes back as plain data.\n *\n * Returns `null` when the worker cannot run (the tooling entry does not resolve to a plain module a worker can\n * load, or the worker fails); the caller then scans in the current thread, which gives the same answer.\n */\nimport { Worker } from \"node:worker_threads\";\n\n/** The worker's body: load the tooling entry, scan, post the files back. */\nconst WORKER_SOURCE = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nimport(workerData.entry)\n .then(({ collectFiles }) => {\n parentPort.postMessage({ files: collectFiles(workerData.root, [], workerData.options) });\n })\n .catch((error) => {\n parentPort.postMessage({ error: String(error && error.message ? error.message : error) });\n });\n`;\n\n/** The scan options the worker passes to `collectFiles`. */\nexport type OffThreadScan = {\n root: string;\n dirs: readonly string[];\n files: readonly string[];\n};\n\n/** Scan in a worker thread; `null` when it could not (scan in the current thread instead). */\nexport async function collectOffThread<File>(scan: OffThreadScan): Promise<File[] | null> {\n let entry: string;\n\n try {\n if (typeof import.meta.resolve !== \"function\") return null;\n\n entry = import.meta.resolve(\"@warlock.js/core/tooling\");\n\n // A worker loads plain JavaScript only: a TypeScript source entry (a checkout of the framework) is scanned in-thread.\n if (/\\.[cm]?tsx?$/.test(entry)) return null;\n } catch {\n return null;\n }\n\n return new Promise((resolve) => {\n let worker: Worker;\n\n try {\n worker = new Worker(WORKER_SOURCE, {\n eval: true,\n workerData: {\n entry,\n root: scan.root,\n options: { dirs: [...scan.dirs], files: [...scan.files] },\n },\n });\n } catch {\n resolve(null);\n\n return;\n }\n\n let settled = false;\n const finish = (files: File[] | null): void => {\n if (settled) return;\n\n settled = true;\n void worker.terminate();\n resolve(files);\n };\n\n worker.once(\"message\", (message: { files?: File[]; error?: string }) =>\n finish(message.files ?? null),\n );\n worker.once(\"error\", () => finish(null));\n worker.once(\"exit\", () => finish(null));\n });\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,gBAAgB;;;;;;;;;;;AAmBtB,eAAsB,iBAAuB,MAA6C;CACxF,IAAI;CAEJ,IAAI;EACF,IAAI,OAAO,YAAY,YAAY,YAAY,OAAO;EAEtD,QAAQ,YAAY,QAAQ,0BAA0B;EAGtD,IAAI,eAAe,KAAK,KAAK,GAAG,OAAO;CACzC,QAAQ;EACN,OAAO;CACT;CAEA,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI;EAEJ,IAAI;GACF,SAAS,IAAI,OAAO,eAAe;IACjC,MAAM;IACN,YAAY;KACV;KACA,MAAM,KAAK;KACX,SAAS;MAAE,MAAM,CAAC,GAAG,KAAK,IAAI;MAAG,OAAO,CAAC,GAAG,KAAK,KAAK;KAAE;IAC1D;GACF,CAAC;EACH,QAAQ;GACN,QAAQ,IAAI;GAEZ;EACF;EAEA,IAAI,UAAU;EACd,MAAM,UAAU,UAA+B;GAC7C,IAAI,SAAS;GAEb,UAAU;GACV,AAAK,OAAO,UAAU;GACtB,QAAQ,KAAK;EACf;EAEA,OAAO,KAAK,YAAY,YACtB,OAAO,QAAQ,SAAS,IAAI,CAC9B;EACA,OAAO,KAAK,eAAe,OAAO,IAAI,CAAC;EACvC,OAAO,KAAK,cAAc,OAAO,IAAI,CAAC;CACxC,CAAC;AACH"}
|
|
@@ -65,7 +65,7 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
65
65
|
},
|
|
66
66
|
{
|
|
67
67
|
name: "grimoire_impact",
|
|
68
|
-
description: "What a change to a file reaches: importers (direct and all), API routes, pages and screens, flows, features (owner and borrowers) and tests.
|
|
68
|
+
description: "What a change to a file reaches: importers (direct and all), API routes, pages and screens, flows, features (owner and borrowers) and tests. grimoire_search already folds a shortened version into its answer for the top hit; call this for the full lists, or for another file. Read the importers and tests: they are the files that usually change with it. Read-only.",
|
|
69
69
|
input: inputSchema({ file: {
|
|
70
70
|
type: "string",
|
|
71
71
|
description: "Project-relative path of the file to change."
|
|
@@ -174,7 +174,7 @@ function createGrimoireMcpTools(context, options = {}, adapterFor) {
|
|
|
174
174
|
},
|
|
175
175
|
{
|
|
176
176
|
name: "grimoire_search",
|
|
177
|
-
description: "Search the Grimoire with a sentence or words (pass the whole commit title or bug report, not two keywords): features, flows, blocks, pages, screens, routes, file paths, export names, header sentences, written text (summary, story, cases, criteria such as AC-5) and tasks. Hits whose name or title holds the words come first; every other hit follows by BM25F score. Hits are in score order and carry their score and app. Search first
|
|
177
|
+
description: "Search the Grimoire with a sentence or words (pass the whole commit title or bug report, not two keywords): features, flows, blocks, pages, screens, routes, file paths, export names, header sentences, written text (summary, story, cases, criteria such as AC-5) and tasks. Hits whose name or title holds the words come first; every other hit follows by BM25F score. Hits are in score order and carry their score and app. Search first: the answer already holds what changes with the top hit, so you do not need grimoire_impact for it. Its alsoChanges list names the files that usually change with the top hits, `impact` lists the importers, routes, flows and tests that reach the top file, `next` is the full impact command (present when `impact` is not), and `weak: true` means no hit holds most of the request's words (use grep for literal text). Read-only.",
|
|
178
178
|
input: inputSchema({
|
|
179
179
|
text: {
|
|
180
180
|
type: "string",
|