Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(webv2): share architecture analysis with scripts
joshistoasta7f418712615
diff --git a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjsindex b5fdaadae7..46e3e95ea6 100644--- a/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs+++ b/invokeai/frontend/webv2/scripts/check-architecture-performance.mjs@@ -1,9 +1,8 @@import assert from 'node:assert/strict';import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';import { dirname, resolve } from 'node:path';-import { isExportDeclaration, isImportDeclaration, isStringLiteralLikeNode } from 'typescript/unstable/ast';-import { parseSource, primeSources } from './parse-source.mjs';+import { analyzeSource, closeSourceAnalysis, primeSourceAnalysis } from '../src/architecture/tsSourceAnalysis.ts';import {BUILD_METRIC_KEYS,checkRouteBudget,@@ -177,59 +176,56 @@ const collectFiles = async (directory) => {const productionFiles = await collectFiles(resolve(root, 'src'));const importerCounts = new Map(Object.values(baseline.developmentInvalidation).map((budget) => [budget.specifier, 0]));const productionSources = await Promise.all(productionFiles.map(async (path) => [path, await readFile(path, 'utf8')]));-// One snapshot for the whole tree keeps the sweep to a single round trip.-primeSources(productionSources, { jsx: true });+try {+ // One snapshot for the whole tree keeps the sweep to a single round trip.+ primeSourceAnalysis(productionSources, { jsx: true });-for (const [path, source] of productionSources) {- const sourceFile = parseSource(path, source, { jsx: true });- const seen = new Set();- const visit = (node) => {- if (- (isImportDeclaration(node) || isExportDeclaration(node)) &&- node.moduleSpecifier &&- isStringLiteralLikeNode(node.moduleSpecifier)- ) {- seen.add(node.moduleSpecifier.text);+ for (const [path, source] of productionSources) {+ const seen = new Set();+ for (const reference of analyzeSource(path, source, { jsx: true }).moduleReferences) {+ if (reference.form === 'import-declaration' || reference.form === 'export-declaration') {+ seen.add(reference.specifier);+ }}- node.forEachChild(visit);- };- visit(sourceFile);- for (const specifier of seen) {- if (importerCounts.has(specifier)) {- importerCounts.set(specifier, importerCounts.get(specifier) + 1);+ for (const specifier of seen) {+ if (importerCounts.has(specifier)) {+ importerCounts.set(specifier, importerCounts.get(specifier) + 1);+ }}}-}-for (const [metricId, budget] of Object.entries(baseline.developmentInvalidation)) {- const actual = importerCounts.get(budget.specifier) ?? 0;- if (actual > budget.maxDirectImporters) {- failures.push({- message: `${metricId} has ${actual} direct importers (budget ${budget.maxDirectImporters}).`,- owner: budget.owner,- remediationTicket: budget.remediationTicket,- routeId: 'development-invalidation',- });+ for (const [metricId, budget] of Object.entries(baseline.developmentInvalidation)) {+ const actual = importerCounts.get(budget.specifier) ?? 0;+ if (actual > budget.maxDirectImporters) {+ failures.push({+ message: `${metricId} has ${actual} direct importers (budget ${budget.maxDirectImporters}).`,+ owner: budget.owner,+ remediationTicket: budget.remediationTicket,+ routeId: 'development-invalidation',+ });+ }}-}-const reportPath = resolve(root, 'artifacts/architecture-performance/build-report.json');-await mkdir(dirname(reportPath), { recursive: true });-await writeFile(- reportPath,- `${JSON.stringify({ baselineCapturedAt: baseline.capturedAt, failures, importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`-);+ const reportPath = resolve(root, 'artifacts/architecture-performance/build-report.json');+ await mkdir(dirname(reportPath), { recursive: true });+ await writeFile(+ reportPath,+ `${JSON.stringify({ baselineCapturedAt: baseline.capturedAt, failures, importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`+ );-if (failures.length > 0) {- throw new Error(- failures- .map(- (failure) =>- `${failure.message} Owner: ${failure.owner}. Remediation: ${failure.remediationTicket}. Route: ${failure.routeId}.`- )- .join('\n')+ if (failures.length > 0) {+ throw new Error(+ failures+ .map(+ (failure) =>+ `${failure.message} Owner: ${failure.owner}. Remediation: ${failure.remediationTicket}. Route: ${failure.routeId}.`+ )+ .join('\n')+ );+ }++ process.stdout.write(+ `${JSON.stringify({ importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`);+} finally {+ closeSourceAnalysis();}--process.stdout.write(- `${JSON.stringify({ importerCounts: Object.fromEntries(importerCounts), measurements }, null, 2)}\n`-);diff --git a/invokeai/frontend/webv2/scripts/parse-source.mjs b/invokeai/frontend/webv2/scripts/parse-source.mjsdeleted file mode 100644index 1ea45dbc71..0000000000--- a/invokeai/frontend/webv2/scripts/parse-source.mjs+++ /dev/null@@ -1,106 +0,0 @@-import { createVirtualFileSystem } from 'typescript/unstable/fs';-import { API } from 'typescript/unstable/sync';--/**- * TypeScript 7 removed the in-process `ts.createSourceFile` parser. The- * replacement surface only hands out ASTs for files that belong to a program,- * so the architecture analyzers parse through a virtual filesystem backed by a- * single long-lived tsgo session instead of parsing detached strings.- *- * Files are staged into the virtual project and flushed in one `updateSnapshot`- * call, which keeps a whole-tree sweep to a single round trip.- */-const PARSE_ROOT = '/architecture-sources';-const CONFIG_PATH = `${PARSE_ROOT}/tsconfig.json`;-const SEED_PATH = `${PARSE_ROOT}/seed.tsx`;--// `noLib` keeps lib.d.ts out of the program: these analyzers only ever walk-// syntax, so skipping the default library removes the bulk of the load cost.-const CONFIG = JSON.stringify({- compilerOptions: { allowJs: true, jsx: 'preserve', module: 'esnext', noLib: true, target: 'esnext' },- include: ['**/*'],-});--let fileSystem;-let api;-let snapshot;-let nextId = 0;-const virtualPaths = new Map();-const stagedText = new Map();-const created = [];-const changed = [];--const ensureSession = () => {- if (!api) {- fileSystem = createVirtualFileSystem({ [CONFIG_PATH]: CONFIG, [SEED_PATH]: 'export {};' });- api = new API({ cwd: PARSE_ROOT, fs: fileSystem });- snapshot = api.updateSnapshot({ openProjects: [CONFIG_PATH] });- }- return api;-};--/**- * Logical paths are analyzer-facing labels rather than real files, so each one- * gets an opaque virtual path. The extension carries the only parse-visible- * decision: `.tsx` parses `<T>` as JSX, `.ts` parses it as a type assertion.- */-const virtualPathFor = (fileName, jsx) => {- const key = `${jsx ? 'x' : ''}:${fileName}`;- let virtualPath = virtualPaths.get(key);- if (!virtualPath) {- virtualPath = `${PARSE_ROOT}/${nextId++}.${jsx ? 'tsx' : 'ts'}`;- virtualPaths.set(key, virtualPath);- }- return virtualPath;-};--const stage = (fileName, text, jsx) => {- ensureSession();- const virtualPath = virtualPathFor(fileName, jsx);- if (stagedText.get(virtualPath) === text) {- return virtualPath;- }- (stagedText.has(virtualPath) ? changed : created).push(virtualPath);- stagedText.set(virtualPath, text);- fileSystem.writeFile(virtualPath, text);- return virtualPath;-};--const flush = () => {- if (created.length === 0 && changed.length === 0) {- return;- }- snapshot = api.updateSnapshot({- fileChanges: { changed: [...changed], created: [...created] },- openProjects: [CONFIG_PATH],- });- created.length = 0;- changed.length = 0;-};--const read = (virtualPath, fileName) => {- const sourceFile = snapshot.getProjects()[0]?.program.getSourceFile(virtualPath);- if (!sourceFile) {- throw new Error(`Failed to parse ${fileName} through the TypeScript API.`);- }- return sourceFile;-};--const resolveJsx = (fileName, jsx) => jsx ?? fileName.endsWith('x');--/**- * Stage many sources and load them with one snapshot update. Use this before a- * whole-tree sweep; parsing each file on its own costs a round trip apiece.- */-export const primeSources = (entries, { jsx } = {}) => {- for (const [fileName, text] of entries) {- stage(fileName, text, resolveJsx(fileName, jsx));- }- flush();-};--export const parseSource = (fileName, text, { jsx } = {}) => {- const virtualPath = stage(fileName, text, resolveJsx(fileName, jsx));- flush();- return read(virtualPath, fileName);-};diff --git a/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs b/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjsindex 34da7c4a98..c172a79483 100644--- a/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs+++ b/invokeai/frontend/webv2/scripts/write-canvas-import-matrix.mjs@@ -1,13 +1,7 @@import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';import { dirname, extname, join, relative, resolve } from 'node:path';-import {- isImportDeclaration,- isNamedImports,- isNamespaceImport,- isStringLiteralLikeNode,-} from 'typescript/unstable/ast';-import { parseSource, primeSources } from './parse-source.mjs';+import { analyzeSource, closeSourceAnalysis, primeSourceAnalysis } from '../src/architecture/tsSourceAnalysis.ts';const packageRoot = process.cwd();const sourceRoot = resolve(packageRoot, 'src');@@ -85,70 +79,54 @@ const callerIntent = (path) => {}return path.split('/').slice(0, 2).join('/');};-const importedSymbols = (clause) => {- if (!clause) {- return ['side-effect'];- }- const symbols = [];- if (clause.name) {- symbols.push('default');- }- if (clause.namedBindings && isNamespaceImport(clause.namedBindings)) {- symbols.push('*');- }- if (clause.namedBindings && isNamedImports(clause.namedBindings)) {- for (const element of clause.namedBindings.elements) {- symbols.push((element.propertyName ?? element.name).text);- }- }- return symbols.sort();-};-const scanned = new Map(paths.filter((path) => isProduction(path) && !isCanvasOwned(path)).map((path) => [path, readFileSync(resolve(sourceRoot, path), 'utf8')]));-// Load the whole tree in one snapshot; parsing file by file costs a round trip each.-primeSources(scanned);+try {+ // Load the whole tree in one snapshot; parsing file by file costs a round trip each.+ primeSourceAnalysis(scanned);-const imports = [];-for (const [source, text] of scanned) {- const file = parseSource(source, text);- for (const statement of file.statements) {- if (!isImportDeclaration(statement) || !isStringLiteralLikeNode(statement.moduleSpecifier)) {- continue;- }- const target = resolveImport(source, statement.moduleSpecifier.text);- if (!target || !isCanvasTarget(target)) {- continue;+ const imports = [];+ for (const [source, text] of scanned) {+ for (const reference of analyzeSource(source, text).moduleReferences) {+ if (reference.form !== 'import-declaration') {+ continue;+ }+ const target = resolveImport(source, reference.specifier);+ if (!target || !isCanvasTarget(target)) {+ continue;+ }+ imports.push({+ intent: callerIntent(source),+ interface: target.startsWith('workbench/canvas-engine/') ? 'canvas-engine' : 'canvas-operations',+ private: !isPublicTarget(target),+ source,+ symbols: [...reference.symbols].sort(),+ target,+ });}- imports.push({- intent: callerIntent(source),- interface: target.startsWith('workbench/canvas-engine/') ? 'canvas-engine' : 'canvas-operations',- private: !isPublicTarget(target),- source,- symbols: importedSymbols(statement.importClause),- target,- });}-}-const grouped = Object.entries(Object.groupBy(imports, ({ intent }) => intent))- .sort(([left], [right]) => left.localeCompare(right))- .map(([intent, records]) => ({ intent, imports: records }));-const privateImports = imports.filter((record) => record.private);-const artifact = {- generatedBy: 'scripts/write-canvas-import-matrix.mjs',- groups: grouped,- summary: {- externalProductionCallerCount: new Set(imports.map(({ source }) => source)).size,- importDeclarationCount: imports.length,- privateCallerCount: new Set(privateImports.map(({ source }) => source)).size,- privateImportDeclarationCount: privateImports.length,- },-};+ const grouped = Object.entries(Object.groupBy(imports, ({ intent }) => intent))+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([intent, records]) => ({ intent, imports: records }));+ const privateImports = imports.filter((record) => record.private);+ const artifact = {+ generatedBy: 'scripts/write-canvas-import-matrix.mjs',+ groups: grouped,+ summary: {+ externalProductionCallerCount: new Set(imports.map(({ source }) => source)).size,+ importDeclarationCount: imports.length,+ privateCallerCount: new Set(privateImports.map(({ source }) => source)).size,+ privateImportDeclarationCount: privateImports.length,+ },+ };-const artifactPath = resolve(packageRoot, 'artifacts/architecture/canvas-import-matrix.json');-mkdirSync(dirname(artifactPath), { recursive: true });-writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);+ const artifactPath = resolve(packageRoot, 'artifacts/architecture/canvas-import-matrix.json');+ mkdirSync(dirname(artifactPath), { recursive: true });+ writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);+} finally {+ closeSourceAnalysis();+}diff --git a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjsindex 7870b63771..e2a3247a76 100644--- a/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs+++ b/invokeai/frontend/webv2/scripts/write-contract-caller-matrix.mjs@@ -1,17 +1,7 @@import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';import { dirname, extname, join, relative, resolve } from 'node:path';-import {- isExportDeclaration,- isIdentifier,- isImportDeclaration,- isNamedExports,- isNamedImports,- isStringLiteralLikeNode,- isVariableStatement,- ModifierFlags,-} from 'typescript/unstable/ast';-import { parseSource, primeSources } from './parse-source.mjs';+import { analyzeSource, closeSourceAnalysis, primeSourceAnalysis } from '../src/architecture/tsSourceAnalysis.ts';const packageRoot = process.cwd();const sourceRoot = resolve(packageRoot, 'src');@@ -25,8 +15,6 @@ const paths = readdirSync(sourceRoot, { recursive: true, withFileTypes: true }).filter(isTypeScript).sort();const sources = new Map(paths.map((path) => [path, readFileSync(resolve(sourceRoot, path), 'utf8')]));-// Load the whole tree in one snapshot; parsing file by file costs a round trip each.-primeSources(sources);const pathByStem = new Map(paths.map((path) => [stripExtension(path), path]));const aliases = [['@app', 'app'],@@ -107,33 +95,8 @@ const resolveImport = (sourcePath, specifier) => {return stem ? (pathByStem.get(stem) ?? pathByStem.get(`${stem}/index`) ?? null) : null;};-const parse = (path) => parseSource(path, sources.get(path));--const exportedSymbols = (path) => {- const symbols = new Set();- for (const statement of parse(path).statements) {- if ((statement.modifierFlags & ModifierFlags.Export) !== 0) {- if (statement.name && isIdentifier(statement.name)) {- symbols.add(statement.name.text);- }- if (isVariableStatement(statement)) {- for (const declaration of statement.declarationList.declarations) {- if (isIdentifier(declaration.name)) {- symbols.add(declaration.name.text);- }- }- }- }- if (isExportDeclaration(statement) && statement.exportClause && isNamedExports(statement.exportClause)) {- for (const element of statement.exportClause.elements) {- symbols.add(element.name.text);- }- }- }- return [...symbols].sort();-};-const callerRecords = new Map(hubs.map((hub) => [hub, new Map()]));+const allCallerRecords = new Map(hubs.map((hub) => [hub, new Set()]));const addCaller = (hub, symbol, caller) => {const symbols = callerRecords.get(hub);const callers = symbols.get(symbol) ?? new Set();@@ -141,49 +104,53 @@ const addCaller = (hub, symbol, caller) => {symbols.set(symbol, callers);};-for (const path of paths) {- for (const statement of parse(path).statements) {- if (- !isImportDeclaration(statement) ||- !statement.importClause ||- !isStringLiteralLikeNode(statement.moduleSpecifier)- ) {- continue;- }- const target = resolveImport(path, statement.moduleSpecifier.text);- if (!target || !callerRecords.has(target)) {- continue;- }- const bindings = statement.importClause.namedBindings;- if (bindings && isNamedImports(bindings)) {- for (const element of bindings.elements) {- addCaller(target, (element.propertyName ?? element.name).text, path);+try {+ // Load the whole tree in one snapshot; parsing file by file costs a round trip each.+ primeSourceAnalysis(sources);++ for (const path of paths) {+ for (const reference of analyzeSource(path, sources.get(path)).moduleReferences) {+ if (reference.form !== 'import-declaration') {+ continue;+ }+ const target = resolveImport(path, reference.specifier);+ if (!target || !callerRecords.has(target)) {+ continue;+ }+ allCallerRecords.get(target).add(path);+ for (const symbol of reference.symbols) {+ if (symbol !== 'default' && symbol !== '*') {+ addCaller(target, symbol, path);+ }}- } else {- addCaller(target, '*', path);}}-}-const matrix = hubs.map((hub) => {- const callersBySymbol = callerRecords.get(hub);- const symbols = exportedSymbols(hub).map((symbol) => {- const callers = [...(callersBySymbol.get(symbol) ?? [])].sort();+ const matrix = hubs.map((hub) => {+ const callersBySymbol = callerRecords.get(hub);+ const exportedSymbols = new Set(analyzeSource(hub, sources.get(hub)).publicExports);+ exportedSymbols.delete('default');+ exportedSymbols.delete('*');+ const symbols = [...exportedSymbols].sort().map((symbol) => {+ const callers = [...(callersBySymbol.get(symbol) ?? [])].sort();+ return {+ callers,+ productionCallers: callers.filter((path) => !isTest(path)),+ symbol,+ };+ });+ const allCallers = [...allCallerRecords.get(hub)].sort();return {- callers,- productionCallers: callers.filter((path) => !isTest(path)),- symbol,+ allCallers,+ hub,+ productionCallerCount: allCallers.filter((path) => !isTest(path)).length,+ symbols,};});- const allCallers = [...new Set([...callersBySymbol.values()].flatMap((callers) => [...callers]))].sort();- return {- allCallers,- hub,- productionCallerCount: allCallers.filter((path) => !isTest(path)).length,- symbols,- };-});-const artifactPath = resolve(packageRoot, 'artifacts/architecture/contract-caller-matrix.json');-mkdirSync(dirname(artifactPath), { recursive: true });-writeFileSync(artifactPath, `${JSON.stringify({ hubs: matrix }, null, 2)}\n`);+ const artifactPath = resolve(packageRoot, 'artifacts/architecture/contract-caller-matrix.json');+ mkdirSync(dirname(artifactPath), { recursive: true });+ writeFileSync(artifactPath, `${JSON.stringify({ hubs: matrix }, null, 2)}\n`);+} finally {+ closeSourceAnalysis();+}diff --git a/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs b/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjsindex 2137b75207..1d7e5b9b77 100644--- a/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs+++ b/invokeai/frontend/webv2/scripts/write-workbench-ownership-inventory.mjs@@ -1,24 +1,7 @@import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';import { dirname, extname, join, relative, resolve } from 'node:path';-import {- isCallExpression,- isEmptyStatement,- isExportAssignment,- isExportDeclaration,- isIdentifier,- isImportDeclaration,- isImportTypeNode,- isInterfaceDeclaration,- isLiteralTypeNode,- isNamedExports,- isStringLiteralLikeNode,- isTypeAliasDeclaration,- isVariableStatement,- ModifierFlags,- SyntaxKind,-} from 'typescript/unstable/ast';-import { parseSource, primeSources } from './parse-source.mjs';+import { analyzeSource, closeSourceAnalysis, primeSourceAnalysis } from '../src/architecture/tsSourceAnalysis.ts';const packageRoot = process.cwd();const sourceRoot = resolve(packageRoot, 'src');@@ -34,8 +17,6 @@ const paths = readdirSync(sourceRoot, { recursive: true, withFileTypes: true }).sort();const productionPaths = paths.filter((path) => !isTest(path));const sources = new Map(productionPaths.map((path) => [path, readFileSync(resolve(sourceRoot, path), 'utf8')]));-// Load the whole tree in one snapshot; parsing file by file costs a round trip each.-primeSources(sources, { jsx: true });const pathByStem = new Map(productionPaths.map((path) => [stripExtension(path), path]));const aliases = [@@ -116,110 +97,6 @@ const targetRule = (path) => {};const targetOwner = (path) => (path.startsWith('workbench/') ? targetRule(path)?.targetOwner : currentOwner(path));-const parse = (path, source) => parseSource(path, source, { jsx: true });-const imports = (path, source) => {- const sourceFile = parse(path, source);- const specifiers = [];- const visit = (node) => {- if (- (isImportDeclaration(node) || isExportDeclaration(node)) &&- node.moduleSpecifier &&- isStringLiteralLikeNode(node.moduleSpecifier)- ) {- specifiers.push(node.moduleSpecifier.text);- } else if (- isImportTypeNode(node) &&- isLiteralTypeNode(node.argument) &&- isStringLiteralLikeNode(node.argument.literal)- ) {- specifiers.push(node.argument.literal.text);- } else if (isCallExpression(node) && node.expression.kind === SyntaxKind.ImportKeyword) {- const argument = node.arguments[0];- if (argument && isStringLiteralLikeNode(argument)) {- specifiers.push(argument.text);- }- }- node.forEachChild(visit);- };- visit(sourceFile);- return specifiers;-};--const publicExports = (path, source) => {- const names = new Set();- for (const statement of parse(path, source).statements) {- if ((statement.modifierFlags & ModifierFlags.Export) !== 0) {- if (statement.name && isIdentifier(statement.name)) {- names.add(statement.name.text);- }- if (isVariableStatement(statement)) {- for (const declaration of statement.declarationList.declarations) {- if (isIdentifier(declaration.name)) {- names.add(declaration.name.text);- }- }- }- }- if (isExportAssignment(statement)) {- names.add('default');- }- if (isExportDeclaration(statement)) {- if (!statement.exportClause) {- names.add('*');- } else if (isNamedExports(statement.exportClause)) {- for (const element of statement.exportClause.elements) {- names.add(element.name.text);- }- }- }- }- return [...names].sort();-};--const isTypeOnly = (path, source) =>- parse(path, source).statements.every((statement) => {- if (isInterfaceDeclaration(statement) || isTypeAliasDeclaration(statement)) {- return true;- }- if (isImportDeclaration(statement)) {- return statement.importClause?.phaseModifier === SyntaxKind.TypeKeyword;- }- if (isExportDeclaration(statement)) {- return statement.isTypeOnly;- }- return isEmptyStatement(statement);- });--const inbound = new Map();-const graph = new Map();-const fileGraph = new Map();-for (const [sourcePath, source] of sources) {- const sourceOwner = targetOwner(sourcePath);- if (!sourceOwner) {- throw new Error(`Unclassified source: ${sourcePath}`);- }- graph.set(sourceOwner, graph.get(sourceOwner) ?? new Set());- fileGraph.set(sourcePath, fileGraph.get(sourcePath) ?? new Set());- for (const specifier of imports(sourcePath, source)) {- const targetPath = resolveImport(sourcePath, specifier);- if (!targetPath) {- continue;- }- const owner = targetOwner(targetPath);- if (!owner) {- throw new Error(`Unclassified target: ${targetPath}`);- }- fileGraph.get(sourcePath).add(targetPath);- const inboundOwners = inbound.get(targetPath) ?? new Set();- inboundOwners.add(sourceOwner);- inbound.set(targetPath, inboundOwners);- graph.set(owner, graph.get(owner) ?? new Set());- if (owner !== sourceOwner) {- graph.get(sourceOwner).add(owner);- }- }-}-const components = (dependencyGraph) => {let index = 0;const indexes = new Map();@@ -261,48 +138,86 @@ const components = (dependencyGraph) => {return result.sort((a, b) => a.join().localeCompare(b.join()));};-const workbenchPaths = productionPaths.filter((path) => path.startsWith('workbench/'));-const modules = workbenchPaths.map((path) => {- const source = sources.get(path);- const rule = targetRule(path);- if (!rule) {- throw new Error(`Unclassified Workbench module: ${path}`);+try {+ // Load the whole tree in one snapshot; parsing file by file costs a round trip each.+ primeSourceAnalysis(sources, { jsx: true });+ const analyses = new Map([...sources].map(([path, source]) => [path, analyzeSource(path, source, { jsx: true })]));++ const inbound = new Map();+ const graph = new Map();+ const fileGraph = new Map();+ for (const [sourcePath, analysis] of analyses) {+ const sourceOwner = targetOwner(sourcePath);+ if (!sourceOwner) {+ throw new Error(`Unclassified source: ${sourcePath}`);+ }+ graph.set(sourceOwner, graph.get(sourceOwner) ?? new Set());+ fileGraph.set(sourcePath, fileGraph.get(sourcePath) ?? new Set());+ for (const specifier of analysis.moduleReferences.map(({ specifier }) => specifier)) {+ const targetPath = resolveImport(sourcePath, specifier);+ if (!targetPath) {+ continue;+ }+ const owner = targetOwner(targetPath);+ if (!owner) {+ throw new Error(`Unclassified target: ${targetPath}`);+ }+ fileGraph.get(sourcePath).add(targetPath);+ const inboundOwners = inbound.get(targetPath) ?? new Set();+ inboundOwners.add(sourceOwner);+ inbound.set(targetPath, inboundOwners);+ graph.set(owner, graph.get(owner) ?? new Set());+ if (owner !== sourceOwner) {+ graph.get(sourceOwner).add(owner);+ }+ }}- const outboundOwners = new Set(- imports(path, source)- .map((specifier) => resolveImport(path, specifier))- .filter(Boolean)- .map(targetOwner)- .filter(Boolean)- );- const stem = stripExtension(path);- return {- currentOwner: 'workbench',- inboundOwners: [...(inbound.get(path) ?? [])].sort(),- moduleKind: isTypeOnly(path, source) ? 'type-only' : 'runtime',- outboundOwners: [...outboundOwners].sort(),- path,- publicExports: publicExports(path, source),- targetOwner: rule.targetOwner,- targetPath: rule.targetPath,- testCompanions: paths.filter((candidate) => candidate.startsWith(`${stem}.`) && isTest(candidate)).sort(),- };-});-const artifact = {- counts: {- productionWorkbenchModules: modules.length,- runtimeModules: modules.filter((module) => module.moduleKind === 'runtime').length,- typeOnlyModules: modules.filter((module) => module.moduleKind === 'type-only').length,- },- generatedFromManifestVersion: manifest.version,- fileCycles: components(fileGraph),- modules,- targetDependencyGraph: Object.fromEntries(- [...graph].sort(([a], [b]) => a.localeCompare(b)).map(([owner, targets]) => [owner, [...targets].sort()])- ),- transitionalCycles: components(graph),-};-const artifactPath = resolve(packageRoot, 'artifacts/architecture/workbench-ownership-inventory.json');-mkdirSync(dirname(artifactPath), { recursive: true });-writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);+ const workbenchPaths = productionPaths.filter((path) => path.startsWith('workbench/'));+ const modules = workbenchPaths.map((path) => {+ const analysis = analyses.get(path);+ const rule = targetRule(path);+ if (!rule) {+ throw new Error(`Unclassified Workbench module: ${path}`);+ }+ const outboundOwners = new Set(+ analysis.moduleReferences+ .map(({ specifier }) => resolveImport(path, specifier))+ .filter(Boolean)+ .map(targetOwner)+ .filter(Boolean)+ );+ const stem = stripExtension(path);+ return {+ currentOwner: 'workbench',+ inboundOwners: [...(inbound.get(path) ?? [])].sort(),+ moduleKind: analysis.typeOnly ? 'type-only' : 'runtime',+ outboundOwners: [...outboundOwners].sort(),+ path,+ publicExports: analysis.publicExports,+ targetOwner: rule.targetOwner,+ targetPath: rule.targetPath,+ testCompanions: paths.filter((candidate) => candidate.startsWith(`${stem}.`) && isTest(candidate)).sort(),+ };+ });++ const artifact = {+ counts: {+ productionWorkbenchModules: modules.length,+ runtimeModules: modules.filter((module) => module.moduleKind === 'runtime').length,+ typeOnlyModules: modules.filter((module) => module.moduleKind === 'type-only').length,+ },+ generatedFromManifestVersion: manifest.version,+ fileCycles: components(fileGraph),+ modules,+ targetDependencyGraph: Object.fromEntries(+ [...graph].sort(([a], [b]) => a.localeCompare(b)).map(([owner, targets]) => [owner, [...targets].sort()])+ ),+ transitionalCycles: components(graph),+ };+ const artifactPath = resolve(packageRoot, 'artifacts/architecture/workbench-ownership-inventory.json');+ mkdirSync(dirname(artifactPath), { recursive: true });+ writeFileSync(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);+} finally {+ closeSourceAnalysis();+}diff --git a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.tsindex 04a4baec93..648b69ba0f 100644--- a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts+++ b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts@@ -2,14 +2,17 @@ import { describe, expect, it } from 'vitest';describe('architecture workflow', () => {it('confines unstable TypeScript imports to the source-analysis adapter', () => {- const modules = import.meta.glob('./*.ts', { eager: true, import: 'default', query: '?raw' }) as Record<- string,- string- >;+ const modules = import.meta.glob(+ [+ './*.ts',+ '../../scripts/{check-architecture-performance,write-canvas-import-matrix,write-contract-caller-matrix,write-workbench-ownership-inventory,parse-source}.mjs',+ ],+ { eager: true, import: 'default', query: '?raw' }+ ) as Record<string, string>;const unstablePrefix = ['typescript', 'unstable'].join('/');const offenders = Object.entries(modules).filter(([path]) => !path.endsWith('/tsSourceAnalysis.ts'))- .filter(([, source]) => source.includes(unstablePrefix))+ .filter(([, source]) => source.includes(unstablePrefix) || source.includes('./parse-source.mjs')).map(([path]) => path).sort();expect(offenders).toEqual([]);