@happyvertical/smrt-core 0.49.5 → 0.49.7
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/README.md +56 -0
- package/dist/consumer-plugin/index.d.ts +19 -4
- package/dist/consumer-plugin/index.d.ts.map +1 -1
- package/dist/consumer-plugin/index.js +214 -6
- package/dist/consumer-plugin/index.js.map +1 -1
- package/dist/manifest/static-manifest.d.ts.map +1 -1
- package/dist/manifest/static-manifest.js +13 -7
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest.json +13 -7
- package/dist/scanner/manifest-generator.d.ts +39 -0
- package/dist/scanner/manifest-generator.d.ts.map +1 -1
- package/dist/scanner/manifest-generator.js +79 -12
- package/dist/scanner/manifest-generator.js.map +1 -1
- package/dist/smrt-knowledge.json +5 -4
- package/dist/vite-plugin/changes-route.d.ts.map +1 -1
- package/dist/vite-plugin/changes-route.js +4 -3
- package/dist/vite-plugin/changes-route.js.map +1 -1
- package/dist/vite-plugin/dev-plane-route.d.ts +2 -0
- package/dist/vite-plugin/dev-plane-route.d.ts.map +1 -1
- package/dist/vite-plugin/dev-plane-route.js +8 -5
- package/dist/vite-plugin/dev-plane-route.js.map +1 -1
- package/dist/vite-plugin/events-route.d.ts.map +1 -1
- package/dist/vite-plugin/events-route.js +4 -3
- package/dist/vite-plugin/events-route.js.map +1 -1
- package/dist/vite-plugin/index.d.ts.map +1 -1
- package/dist/vite-plugin/index.js +25 -40
- package/dist/vite-plugin/index.js.map +1 -1
- package/dist/vite-plugin/resources-route.d.ts +6 -0
- package/dist/vite-plugin/resources-route.d.ts.map +1 -1
- package/dist/vite-plugin/resources-route.js +30 -7
- package/dist/vite-plugin/resources-route.js.map +1 -1
- package/dist/vite-plugin/sveltekit-config-import.d.ts +19 -0
- package/dist/vite-plugin/sveltekit-config-import.d.ts.map +1 -0
- package/dist/vite-plugin/sveltekit-config-import.js +36 -0
- package/dist/vite-plugin/sveltekit-config-import.js.map +1 -0
- package/dist/vite-plugin/sveltekit-generator.d.ts +33 -2
- package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
- package/dist/vite-plugin/sveltekit-generator.js +181 -65
- package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
- package/dist/vite-plugin/sveltekit-path.d.ts +8 -0
- package/dist/vite-plugin/sveltekit-path.d.ts.map +1 -0
- package/dist/vite-plugin/sveltekit-path.js +25 -0
- package/dist/vite-plugin/sveltekit-path.js.map +1 -0
- package/dist/vite-plugin/sveltekit-route-coordinator.d.ts +67 -0
- package/dist/vite-plugin/sveltekit-route-coordinator.d.ts.map +1 -0
- package/dist/vite-plugin/sveltekit-route-coordinator.js +321 -0
- package/dist/vite-plugin/sveltekit-route-coordinator.js.map +1 -0
- package/dist/vite-plugin/sync-apply-route.d.ts +1 -1
- package/dist/vite-plugin/sync-apply-route.d.ts.map +1 -1
- package/dist/vite-plugin/sync-apply-route.js +4 -3
- package/dist/vite-plugin/sync-apply-route.js.map +1 -1
- package/package.json +6 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/consumer-plugin/index.ts"],"sourcesContent":["/**\n * Vite plugin for consuming SMRT packages\n * Solves virtual module resolution in downstream projects\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { DomainKnowledgeAgentSurface } from '@happyvertical/smrt-types';\nimport type { Plugin } from 'vite';\nimport {\n loadVerifiedSmrtGenerationSnapshot,\n type SmrtGenerationSnapshotOptions,\n} from '../generation-snapshot.js';\nimport { buildDomainKnowledgeManifest } from '../knowledge.js';\nimport { resolveFileKnowledgeConfig } from '../knowledge-config.js';\nimport { generateDeclarations } from '../prebuild/index.js';\nimport type { SmartObjectManifest } from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport { generateClientModule } from '../vite-plugin/generated-client.js';\nimport type { SmrtPluginApi } from '../vite-plugin/index.js';\nimport { generateWebModule } from '../vite-plugin/web-collections.js';\nimport { publishArtifactFiles } from './artifact-publication.js';\n\nexport {\n loadVerifiedSmrtGenerationSnapshot,\n type SerializeSmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotArtifact,\n type SmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotView,\n serializeSmrtGenerationSnapshot,\n sha256SmrtGenerationSnapshot,\n} from '../generation-snapshot.js';\n\n/**\n * Loosely-typed view of an object definition as carried by an external\n * package's static manifest. The static manifests are read from JSON at the\n * package boundary, so only the fields this plugin consumes are typed; the\n * index signature preserves any additional fields (e.g. for spreads). This is\n * a structural superset of a manifest `SmartObjectDefinition` plus the\n * consumer-only `hasCollection` marker.\n */\ninterface ConsumerObjectDefinition {\n className?: string;\n packageName?: string;\n packageVersion?: string;\n qualifiedName?: string;\n importPath?: string;\n exportName?: string;\n collectionExportName?: string;\n hasCollection?: boolean;\n collection?: string;\n extends?: string;\n extendsQualified?: string;\n extendsTypeArg?: string;\n [key: string]: unknown;\n}\n\n/**\n * Aggregated manifest assembled by the consumer plugin from one or more\n * external package manifests. Loosely typed because the inputs originate from\n * JSON read at the package boundary.\n */\ninterface ConsumerManifest {\n version: string;\n timestamp: number;\n packageName?: string;\n packageVersion?: string;\n objects: Record<string, ConsumerObjectDefinition>;\n}\n\n/**\n * Minimal structural shape of a parsed `package.json` consumed here (name,\n * version, and the export map used to derive import paths). The index\n * signature keeps the remaining fields accessible.\n */\ninterface ConsumerPackageJson {\n name?: string;\n version?: string;\n main?: string;\n exports?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface SmrtConsumerOptions {\n /** SMRT packages to scan (e.g., ['@my-org/products', '@my-org/content']) */\n packages?: string[];\n /** Generate TypeScript declarations */\n generateTypes?: boolean;\n /** Output directory for generated types */\n typesDir?: string;\n /** Project root path */\n projectRoot?: string;\n /**\n * Reuse an immutable, verified aggregated manifest instead of discovering\n * packages or writing `.smrt/manifest.json`. Registration and generated\n * types still consume the verified manifest.\n */\n generationSnapshot?: SmrtGenerationSnapshotOptions;\n /** SvelteKit integration mode */\n svelteKit?: boolean;\n /**\n * Apply kebab-case to generated custom-method URL segments. This must match\n * the producer plugin's `svelteKit.kebabRoutes` setting.\n */\n kebabRoutes?: boolean;\n /** Use static types only (for federation builds) */\n staticTypes?: boolean;\n /** Disable file scanning */\n disableScanning?: boolean;\n}\n\n// Distinct resolved ids per plugin (#1795). smrtPlugin resolves\n// `@happyvertical/smrt-virt-*` to `\\0smrt:*`; if this consumer plugin also\n// resolved its `@smrt/*` specifiers to `\\0smrt:*` the two virtual modules would\n// share a rollup id, and in standalone/federation builds the consumer's\n// fallback `load` would non-deterministically win and shadow smrtPlugin's real\n// module. Namespacing the consumer ids (`\\0smrt-consumer:*`) keeps them\n// separate so each plugin only ever loads its own module.\nconst VIRTUAL_MODULES = {\n '@smrt/routes': 'smrt-consumer:routes',\n '@smrt/client': 'smrt-consumer:client',\n '@smrt/mcp': 'smrt-consumer:mcp',\n '@smrt/types': 'smrt-consumer:types',\n '@smrt/manifest': 'smrt-consumer:manifest',\n '@smrt/web': 'smrt-consumer:web',\n};\n\n/**\n * Consumer plugin for projects that use SMRT packages\n */\nexport function smrtConsumer(options: SmrtConsumerOptions = {}): Plugin {\n const {\n packages = [],\n generateTypes = true,\n typesDir = 'src/types/smrt-generated',\n projectRoot = process.cwd(),\n generationSnapshot,\n disableScanning = false,\n kebabRoutes = false,\n } = options;\n\n let smrtPackages: string[] = [];\n let typeManifest: ConsumerManifest | null = null;\n let typesGenerated = false;\n let producerApi: SmrtPluginApi | undefined;\n\n function loadGenerationSnapshot(): ConsumerManifest {\n if (!generationSnapshot) {\n throw new Error('[smrt:consumer] Generation snapshot is not configured');\n }\n return loadVerifiedSmrtGenerationSnapshot<ConsumerManifest>(\n generationSnapshot,\n projectRoot,\n 'dependencies',\n );\n }\n\n return {\n name: 'smrt-consumer',\n\n config() {\n return {\n build: {\n rollupOptions: {\n // Runtime registration evaluates provider entry points so their\n // exact constructors can be registered. Leave optional native\n // provider binaries to Node instead of parsing them as JavaScript.\n external: [/\\.node$/],\n },\n },\n };\n },\n\n configResolved(resolvedConfig) {\n producerApi = (resolvedConfig.plugins ?? []).find(\n (plugin) => plugin?.name === 'smrt-auto-service',\n )?.api as SmrtPluginApi | undefined;\n },\n\n async buildStart() {\n console.log('[smrt:consumer] Initializing SMRT consumer plugin');\n\n if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n console.log(\n `[smrt:consumer] Reusing verified generation snapshot (${generationSnapshot.provenance})`,\n );\n await generateRegistrationFile(typeManifest, projectRoot);\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n return;\n }\n\n // Discover SMRT packages if not explicitly specified\n if (packages.length === 0 && !disableScanning) {\n smrtPackages = await discoverSmrtPackages(projectRoot);\n } else {\n smrtPackages = packages;\n }\n\n if (smrtPackages.length > 0) {\n console.log(\n `[smrt:consumer] Found SMRT packages: ${smrtPackages.join(', ')}`,\n );\n\n // Aggregate type manifests from discovered packages\n typeManifest = await aggregateTypeManifests(smrtPackages, projectRoot);\n // Wait before reading .smrt/manifest.json: a producer's parallel\n // buildStart writes its current local manifest after scanning. Reading\n // first could merge an older local manifest with a newer surface.\n const agentSurface = producerApi\n ? await producerApi.resolveKnowledgeAgentSurface()\n : undefined;\n\n // Save aggregated manifest for CLI discovery\n await saveAggregatedManifest(\n typeManifest,\n projectRoot,\n producerApi?.resolveKnowledgeConfig,\n agentSurface,\n );\n\n // Generate registration file for CLI class loading\n await generateRegistrationFile(typeManifest, projectRoot);\n\n // Generate types if requested\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n } else {\n console.log('[smrt:consumer] No SMRT packages found');\n typeManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n },\n\n resolveId(id, _importer) {\n // Resolve virtual modules to generated type declarations\n if (id in VIRTUAL_MODULES) {\n // Generated declarations are ambient TypeScript declarations, not\n // executable JavaScript. Vite must always load the consumer runtime\n // module after default type generation writes them.\n if (id !== '@smrt/types') {\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n\n const typeFileName = getTypeFileName(id);\n const typePath = path.join(projectRoot, typesDir, typeFileName);\n\n // If types file exists, resolve to it\n if (fs.existsSync(typePath)) {\n return typePath;\n }\n\n // Otherwise use virtual module ID for runtime resolution\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n return null;\n },\n\n async load(id) {\n // Handle virtual modules if types aren't available\n const cleanId = id.startsWith('\\0') ? id.slice(1) : id;\n\n if (!typeManifest) {\n typeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n\n switch (cleanId) {\n case 'smrt-consumer:routes':\n return generateFallbackRoutesModule();\n\n case 'smrt-consumer:client':\n return generateFallbackClientModule(typeManifest, { kebabRoutes });\n\n case 'smrt-consumer:mcp':\n return generateFallbackMcpModule();\n\n case 'smrt-consumer:types':\n return generateFallbackTypesModule(typeManifest);\n\n case 'smrt-consumer:manifest':\n return generateFallbackManifestModule(typeManifest);\n\n case 'smrt-consumer:web':\n return generateWebModule(\n typeManifest as unknown as SmartObjectManifest,\n {\n kebabRoutes,\n },\n );\n\n default:\n return null;\n }\n },\n };\n}\n\n/**\n * Discover SMRT packages from a consumer app's dependencies.\n *\n * Intentional split (#1579): this **consumer-plugin** path is async and\n * resolves SMRT packages from the downstream app's `package.json` dependency\n * names (`@have/`/`smrt` heuristic + `hasSmrtManifest` probe) inside the Vite\n * consumer plugin. It is deliberately separate from the build-time\n * `discoverSmrtPackages()` in `src/manifest/discover-smrt-packages.ts` — a\n * synchronous, lockfile-cached `node_modules` manifest scan used for manifest\n * generation. Different inputs, contexts, and lifecycles, not duplicated logic.\n */\nasync function discoverSmrtPackages(projectRoot: string): Promise<string[]> {\n const packages: string[] = [];\n const nodeModulesPath = path.join(projectRoot, 'node_modules');\n\n if (!fs.existsSync(nodeModulesPath)) {\n return packages;\n }\n\n try {\n // Check package.json for workspace dependencies\n const packageJsonPath = path.join(projectRoot, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Look for packages that likely contain SMRT objects\n for (const [name, version] of Object.entries(allDeps)) {\n if (\n typeof version === 'string' &&\n (name.includes('smrt') ||\n name.includes('@have/') ||\n (await hasSmrtManifest(nodeModulesPath, name)))\n ) {\n packages.push(name);\n }\n }\n }\n } catch (error) {\n console.warn('[smrt:consumer] Error discovering packages:', error);\n }\n\n return packages;\n}\n\n/**\n * Check if a package has SMRT manifest\n */\nasync function hasSmrtManifest(\n nodeModulesPath: string,\n packageName: string,\n): Promise<boolean> {\n const packagePath = path.join(nodeModulesPath, packageName);\n const manifestPath = path.join(\n packagePath,\n 'dist',\n 'manifest',\n 'static-manifest.js',\n );\n return fs.existsSync(manifestPath);\n}\n\n/**\n * Aggregate type manifests from multiple packages\n */\nasync function aggregateTypeManifests(\n packages: string[],\n projectRoot: string,\n): Promise<ConsumerManifest> {\n const aggregatedManifest: ConsumerManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n\n for (const packageName of packages) {\n try {\n const packageDir = path.join(projectRoot, 'node_modules', packageName);\n\n // Load package.json for version and export information\n const packageJsonPath = path.join(packageDir, 'package.json');\n let packageJson: ConsumerPackageJson;\n try {\n const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContent) as ConsumerPackageJson;\n } catch {\n console.warn(\n `[smrt:consumer] Could not read package.json for ${packageName}`,\n );\n continue;\n }\n\n // Try multiple manifest locations\n const manifestCandidates = [\n path.join(packageDir, 'dist', 'manifest', 'static-manifest.js'),\n path.join(packageDir, 'dist', 'manifest.json'),\n path.join(packageDir, 'manifest.json'),\n ];\n\n for (const manifestPath of manifestCandidates) {\n if (fs.existsSync(manifestPath)) {\n // Import or read the manifest\n let manifest: Partial<ConsumerManifest> | undefined;\n if (manifestPath.endsWith('.js')) {\n const manifestModule = await import(manifestPath);\n manifest = manifestModule.staticManifest || manifestModule.default;\n } else {\n const manifestContent = fs.readFileSync(manifestPath, 'utf-8');\n manifest = JSON.parse(manifestContent) as Partial<ConsumerManifest>;\n }\n\n if (manifest?.objects) {\n console.log(\n `[smrt:consumer] Loaded manifest from ${packageName} (${Object.keys(manifest.objects).length} objects)`,\n );\n\n // ENHANCED: Preserve package metadata for each object\n for (const [objectName, objectDef] of Object.entries(\n manifest.objects,\n )) {\n const def = objectDef;\n\n aggregatedManifest.objects[objectName] = {\n ...def,\n // Ensure package metadata is preserved/set\n packageName:\n def.packageName || manifest.packageName || packageName,\n packageVersion:\n def.packageVersion ||\n manifest.packageVersion ||\n packageJson.version,\n // Add fallback import paths if missing\n importPath: def.importPath || determineImportPath(packageJson),\n exportName: def.exportName || def.className || objectName,\n collectionExportName:\n def.collectionExportName ||\n `${def.className || objectName}Collection`,\n };\n }\n\n break; // Use first found manifest for this package\n }\n }\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Error loading manifest from ${packageName}:`,\n error,\n );\n }\n }\n\n return aggregatedManifest;\n}\n\n/**\n * Determine import path from package.json\n */\nfunction determineImportPath(packageJson: ConsumerPackageJson): string {\n const packageName = packageJson.name;\n\n if (!packageName) {\n throw new Error('Package name not found in package.json');\n }\n\n // Strategy 1: Check for specific exports\n if (packageJson.exports) {\n // Check for objects export\n if (packageJson.exports['./objects']) {\n return `${packageName}/objects`;\n }\n\n // Check for main export\n const mainExport = packageJson.exports['.'];\n if (mainExport) {\n // Handle conditional exports\n if (typeof mainExport === 'object' && mainExport !== null) {\n const conditional = mainExport as Record<string, unknown>;\n if (conditional.import) {\n return packageName;\n }\n if (conditional.default) {\n return packageName;\n }\n }\n return packageName;\n }\n }\n\n // Strategy 2: Check main field\n if (packageJson.main) {\n return packageName;\n }\n\n // Strategy 3: Fallback to package name\n return packageName;\n}\n\n/**\n * Save aggregated manifest to .smrt/manifest.json for CLI discovery.\n *\n * Merge-preserving: `smrtPlugin()` writes the project's own scanned objects\n * to the same file (`writeLocalManifest`, issue #963), and both writes happen\n * in parallel `buildStart` hooks — so a plain overwrite here would clobber\n * the local objects whenever this plugin's write lands last (issue #1760\n * review). Local field metadata would then silently vanish from CLI schema\n * commands and from server runtimes that seed `.smrt/manifest.json`, dropping\n * domain columns on write. This function therefore only ADDS/refreshes the\n * external-package entries it owns and preserves everything else already in\n * the file (including the top-level `packageName` the local write sets).\n */\nasync function saveAggregatedManifest(\n manifest: ConsumerManifest,\n projectRoot: string,\n resolveKnowledgeConfig?: SmrtPluginApi['resolveKnowledgeConfig'],\n agentSurface?: DomainKnowledgeAgentSurface,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const manifestPath = path.join(smrtDir, 'manifest.json');\n\n try {\n // Create .smrt directory if it doesn't exist\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Merge with whatever is on disk: existing entries (typically the local\n // project's objects written by smrtPlugin) are preserved; aggregated\n // external entries win for the qualified names this plugin owns.\n let merged: ConsumerManifest = manifest;\n if (fs.existsSync(manifestPath)) {\n try {\n const existing = JSON.parse(\n fs.readFileSync(manifestPath, 'utf-8'),\n ) as Partial<ConsumerManifest>;\n if (existing && typeof existing.objects === 'object') {\n merged = {\n ...existing,\n ...manifest,\n // The aggregated manifest carries no packageName; keep the local\n // project's (used as the manifest cache key at runtime).\n ...(existing.packageName\n ? { packageName: existing.packageName }\n : {}),\n objects: { ...existing.objects, ...manifest.objects },\n };\n }\n } catch {\n // Unreadable/corrupt existing file — fall back to a plain write.\n }\n }\n\n // smrtPlugin writes the local knowledge artifact before this consumer\n // plugin merges external package entries into the same manifest. Refresh\n // the artifact from the merged manifest so its source hash always names\n // the manifest that CLI discovery and server runtimes actually consume.\n // The consumer deliberately does not load the scanner. Only carry a\n // surface from the current producer scan: a prior artifact can describe\n // declarations that have since changed while retaining the same path.\n // Re-hashing that current path under a stale declaration would make an\n // incorrect agent contract look fresh.\n const knowledgePath = path.join(smrtDir, 'smrt-knowledge.json');\n const packageJsonPath = path.join(projectRoot, 'package.json');\n const packageJson = fs.existsSync(packageJsonPath)\n ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n : undefined;\n const knowledgeConfig = resolveKnowledgeConfig\n ? await resolveKnowledgeConfig(merged as unknown as SmartObjectManifest)\n : await resolveFileKnowledgeConfig(\n projectRoot,\n merged.packageName ?? packageJson?.name,\n );\n if (knowledgeConfig.enabled === false) {\n publishArtifactFiles([\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n return;\n }\n const knowledge = buildDomainKnowledgeManifest({\n manifest: merged as unknown as SmartObjectManifest,\n rootDir: projectRoot,\n packageJson,\n manifestPath,\n config: knowledgeConfig,\n agentSurface,\n });\n // Stage both artifacts before replacing either. Renames are individually\n // atomic; if a synchronous later rename fails, restore every earlier\n // replacement. A process crash between renames cannot be made pair-atomic\n // with ordinary filesystem operations, so the next generation remains the\n // freshness repair path for that distinct failure mode.\n publishArtifactFiles([\n { path: knowledgePath, content: JSON.stringify(knowledge, null, 2) },\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n\n console.log(\n `[smrt:consumer] Saved aggregated manifest to .smrt/manifest.json (${Object.keys(merged.objects).length} objects)`,\n );\n } catch (error) {\n throw new Error('[smrt:consumer] Failed to save aggregated manifest', {\n cause: error,\n });\n }\n}\n\n/**\n * Generate registration file for CLI class loading\n *\n * Creates .smrt/register.js with static imports and registrations\n * for all external SMRT objects discovered during build.\n */\nasync function generateRegistrationFile(\n manifest: ConsumerManifest,\n projectRoot: string,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const registerPath = path.join(smrtDir, 'register.js');\n\n // Bind every imported symbol to a generated local name. Aggregated manifests\n // may contain same-named exports from different packages (and may list a\n // collection both beside its object and as its own manifest entry), so using\n // provider export names as local bindings can produce invalid duplicate\n // imports in a production consumer bundle.\n const importBindings = new Map<string, string>();\n const importsByPath = new Map<string, Map<string, string>>();\n let nextImportBinding = 0;\n const getImportBinding = (importPath: string, exportName: string): string => {\n const key = `${importPath}\\0${exportName}`;\n const existing = importBindings.get(key);\n if (existing) return existing;\n const binding = `__smrt_consumer_${nextImportBinding++}`;\n importBindings.set(key, binding);\n const specifiers =\n importsByPath.get(importPath) ?? new Map<string, string>();\n specifiers.set(exportName, binding);\n importsByPath.set(importPath, specifiers);\n return binding;\n };\n\n const registrations: string[] = [];\n const registrationManifests: Record<string, ConsumerManifest> = {};\n let importedEntryCount = 0;\n let registeredObjectCount = 0;\n\n const manifestObjects = manifest.objects;\n const manifestObjectLookup = new Map<string, ConsumerObjectDefinition>();\n for (const [key, def] of Object.entries(manifestObjects)) {\n const candidate = def;\n const lookupKeys = [\n key,\n key.includes(':') ? key.split(':').pop() : undefined,\n candidate.qualifiedName,\n candidate.className,\n candidate.exportName,\n ];\n\n for (const lookupKey of lookupKeys) {\n if (lookupKey && !manifestObjectLookup.has(lookupKey)) {\n manifestObjectLookup.set(lookupKey, candidate);\n }\n }\n }\n\n const collectionClassMemo = new WeakMap<object, boolean>();\n\n const isCollectionClass = (\n def: ConsumerObjectDefinition | undefined,\n seen = new Set<string>(),\n ): boolean => {\n if (!def || typeof def !== 'object') {\n return false;\n }\n\n const cached = collectionClassMemo.get(def);\n if (cached !== undefined) {\n return cached;\n }\n\n if (\n def?.extends === 'SmrtCollection' ||\n def?.extendsTypeArg !== undefined\n ) {\n collectionClassMemo.set(def, true);\n return true;\n }\n\n const parentName = def?.extendsQualified || def?.extends;\n if (!parentName || seen.has(parentName)) {\n collectionClassMemo.set(def, false);\n return false;\n }\n seen.add(parentName);\n\n const parentDef = manifestObjectLookup.get(parentName);\n const isCollection = parentDef ? isCollectionClass(parentDef, seen) : false;\n collectionClassMemo.set(def, isCollection);\n\n return isCollection;\n };\n\n for (const [objectName, objectDef] of Object.entries(manifestObjects)) {\n const def = objectDef;\n\n // Skip local objects (they're imported from local entry point)\n if (!def.packageName || def.packageName === manifest.packageName) {\n continue;\n }\n\n const importPath = def.importPath || def.packageName;\n const exportName = def.exportName || def.className || objectName;\n const collectionExportName = def.collectionExportName;\n const hasCollection = def.hasCollection; // Check if collection class actually exists\n const tableName = def.collection || objectName.toLowerCase();\n\n const exportBinding = getImportBinding(importPath, exportName);\n const collectionBinding =\n hasCollection && collectionExportName\n ? getImportBinding(importPath, collectionExportName)\n : undefined;\n importedEntryCount++;\n\n if (isCollectionClass(def)) {\n continue;\n }\n\n const logicalName = def.className || exportName;\n registrationManifests[objectName] = {\n ...manifest,\n packageName: def.packageName,\n packageVersion: def.packageVersion || manifest.packageVersion,\n objects: { [objectName]: def },\n };\n\n // Import evaluation triggers the provider decorator first. The explicit\n // constructor/package/key tuple then promotes that exact constructor with\n // its isolated manifest, which is stable across Rollup name deconfliction.\n registrations.push(\n `if (${exportBinding}) ObjectRegistry.register(${exportBinding}, { name: ${JSON.stringify(logicalName)}, packageName: ${JSON.stringify(def.packageName)}, _manifest: smrtRegistrationManifests[${JSON.stringify(objectName)}], _manifestKey: ${JSON.stringify(objectName)} });`,\n );\n\n // Only register collection if it exists\n if (collectionBinding) {\n registrations.push(\n `if (${collectionBinding}) ObjectRegistry.registerCollection('${tableName}', ${collectionBinding});`,\n );\n }\n\n registeredObjectCount++;\n }\n\n // Skip generation if no external entries\n if (importedEntryCount === 0) {\n console.log('[smrt:consumer] No external entries - skipping register.js');\n return;\n }\n\n const registeredObjectLabel =\n registeredObjectCount === 1 ? 'object' : 'objects';\n const sortedImports = Array.from(importsByPath.entries()).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n const imports = sortedImports.map(\n ([importPath], index) =>\n `import * as __smrt_provider_${index} from '${importPath}';`,\n );\n const importDeclarations = sortedImports.flatMap(([, specifiers], index) =>\n Array.from(specifiers.entries())\n .sort(([left], [right]) => left.localeCompare(right))\n .map(\n ([exportName, binding]) =>\n `const ${binding} = getSmrtExport(__smrt_provider_${index}, ${JSON.stringify(exportName)});`,\n ),\n );\n const registrationManifestLiteral = JSON.stringify(\n JSON.stringify(registrationManifests),\n );\n\n // Generate file content\n const content = `/**\n * Auto-generated by @happyvertical/smrt-core/consumer-plugin\n * DO NOT EDIT - This file is regenerated on every build\n *\n * Registers SMRT objects from external packages for CLI discovery.\n * Generated at: ${new Date().toISOString()}\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n${imports.join('\\n')}\n\n/**\n * @param {Record<string, unknown>} provider\n * @param {string} exportName\n * @returns {any}\n */\nconst getSmrtExport = (provider, exportName) =>\n typeof provider[exportName] === 'function' ? provider[exportName] : undefined;\n${importDeclarations.join('\\n')}\n\nconst smrtRegistrationManifests = JSON.parse(${registrationManifestLiteral});\n\n// Register all objects (executed during module evaluation)\n${registrations.join('\\n')}\n\nexport function registerAll() {\n // Objects are already registered during module evaluation\n console.log('[smrt:register] Registered ${registeredObjectCount} external ${registeredObjectLabel}');\n}\n`;\n\n // Create .smrt directory if needed\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Write registration file\n fs.writeFileSync(registerPath, content, 'utf-8');\n\n console.log(\n `[smrt:consumer] Generated .smrt/register.js with ${importedEntryCount} external entries (${registeredObjectCount} registered ${registeredObjectLabel})`,\n );\n}\n\n/**\n * Generate project-specific types\n */\nasync function generateProjectTypes(\n typeManifest: ConsumerManifest,\n typesDir: string,\n projectRoot: string,\n): Promise<void> {\n if (!typeManifest || Object.keys(typeManifest.objects).length === 0) {\n console.log(\n '[smrt:consumer] No SMRT objects found, skipping type generation',\n );\n return;\n }\n\n await generateDeclarations({\n // The aggregated manifest is a runtime SMRT manifest assembled from external\n // package manifests; it is intentionally typed loosely at the JSON boundary,\n // so narrow it to the declaration generator's strict manifest shape here.\n manifest: typeManifest as unknown as SmartObjectManifest,\n outDir: typesDir,\n projectRoot,\n includeVirtualModules: true,\n includeObjectTypes: true,\n });\n\n console.log(\n `[smrt:consumer] Generated types for ${Object.keys(typeManifest.objects).length} objects`,\n );\n}\n\n/**\n * Get type file name for virtual module\n */\nfunction getTypeFileName(virtualModule: string): string {\n const moduleMap: Record<string, string> = {\n '@smrt/routes': 'smrt-routes.d.ts',\n '@smrt/client': 'smrt-client.d.ts',\n '@smrt/mcp': 'smrt-mcp.d.ts',\n '@smrt/types': 'smrt-types.d.ts',\n '@smrt/manifest': 'smrt-manifest.d.ts',\n '@smrt/web': 'smrt-web.d.ts',\n };\n return moduleMap[virtualModule] || 'smrt-unknown.d.ts';\n}\n\n/**\n * Fallback modules for when types aren't available\n */\nfunction generateFallbackRoutesModule(): string {\n return `\n// Fallback routes module\nexport function setupRoutes(app) {\n console.warn('[smrt:consumer] No routes available - SMRT packages may not be properly configured');\n}\nexport default setupRoutes;\n`;\n}\n\nfunction generateFallbackClientModule(\n manifest: ConsumerManifest,\n options: { kebabRoutes?: boolean } = {},\n): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `\n// Fallback client module\nexport function createClient(basePath = '/api/v1') {\n console.warn('[smrt:consumer] No API client available - SMRT packages may not be properly configured');\n return {};\n}\nexport default createClient;\n`;\n }\n\n return generateClientModule(manifest as unknown as SmartObjectManifest, {\n kebabRoutes: options.kebabRoutes,\n });\n}\n\nfunction generateFallbackMcpModule(): string {\n return `\n// Fallback MCP module\nexport const tools = [];\nexport function createMCPServer() {\n console.warn('[smrt:consumer] No MCP tools available - SMRT packages may not be properly configured');\n return { name: 'smrt-consumer', version: '1.0.0', tools: [] };\n}\nexport default createMCPServer;\n`;\n}\n\nfunction generateFallbackTypesModule(manifest: ConsumerManifest): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `// No types available`;\n }\n\n // Generate basic interfaces\n const interfaces = objects.map(([_name, obj]) => {\n return `export interface ${obj.className}Data {\n id?: string;\n created_at?: string;\n updated_at?: string;\n [key: string]: any;\n}`;\n });\n\n return interfaces.join('\\n\\n');\n}\n\nfunction generateFallbackManifestModule(manifest: ConsumerManifest): string {\n return `\n// Auto-generated manifest from SMRT consumer\nexport const manifest = ${JSON.stringify(manifest, null, 2)};\nexport default manifest;\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsHA,IAAM,kBAAkB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,aAAa;AACf;;;;AAKA,SAAgB,aAAa,UAA+B,CAAC,GAAW;CACtE,MAAM,EACJ,WAAW,CAAC,GACZ,gBAAgB,MAChB,WAAW,4BACX,cAAc,QAAQ,IAAI,GAC1B,oBACA,kBAAkB,OAClB,cAAc,UACZ;CAEJ,IAAI,eAAyB,CAAC;CAC9B,IAAI,eAAwC;CAC5C,IAAI,iBAAiB;CACrB,IAAI;CAEJ,SAAS,yBAA2C;EAClD,IAAI,CAAC,oBACH,MAAM,IAAI,MAAM,uDAAuD;EAEzE,OAAO,mCACL,oBACA,aACA,cACF;CACF;CAEA,OAAO;EACL,MAAM;EAEN,SAAS;GACP,OAAO,EACL,OAAO,EACL,eAAe,EAIb,UAAU,CAAC,SAAS,EACtB,EACF,EACF;EACF;EAEA,eAAe,gBAAgB;GAC7B,eAAe,eAAe,WAAW,CAAC,EAAA,CAAG,MAC1C,WAAW,QAAQ,SAAS,mBAC/B,CAAC,EAAE;EACL;EAEA,MAAM,aAAa;GACjB,QAAQ,IAAI,mDAAmD;GAE/D,IAAI,oBAAoB;IACtB,eAAe,uBAAuB;IACtC,QAAQ,IACN,yDAAyD,mBAAmB,WAAW,EACzF;IACA,MAAM,yBAAyB,cAAc,WAAW;IACxD,IAAI,iBAAiB,CA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Q,KAAK,CAAC,OAAO,SAAS;EAC/C,OAAO,oBAAoB,IAAI,UAAU;;;;;;CAM3C,CAEO,CAAA,CAAW,KAAK,MAAM;AAC/B;AAEA,SAAS,+BAA+B,UAAoC;CAC1E,OAAO;;0BAEiB,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE;;;AAG5D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/consumer-plugin/index.ts"],"sourcesContent":["/**\n * Vite plugin for consuming SMRT packages\n * Solves virtual module resolution in downstream projects\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { DomainKnowledgeAgentSurface } from '@happyvertical/smrt-types';\nimport type { ConfigEnv, Plugin } from 'vite';\nimport {\n loadVerifiedSmrtGenerationSnapshot,\n type SmrtGenerationSnapshotOptions,\n} from '../generation-snapshot.js';\nimport { buildDomainKnowledgeManifest } from '../knowledge.js';\nimport { resolveFileKnowledgeConfig } from '../knowledge-config.js';\nimport { generateDeclarations } from '../prebuild/index.js';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from '../scanner/types.js';\nimport { MANIFEST_TIMESTAMP } from '../scanner/types.js';\nimport { generateClientModule } from '../vite-plugin/generated-client.js';\nimport type { SmrtPluginApi } from '../vite-plugin/index.js';\nimport {\n clearGeneratedSvelteKitRouteFiles,\n reconcileSvelteKitRouteGitignore,\n type SvelteKitOptions,\n} from '../vite-plugin/sveltekit-generator.js';\nimport { canonicalSvelteKitPath } from '../vite-plugin/sveltekit-path.js';\nimport {\n activeProducerKnowledgeRoutePaths,\n activeSvelteKitRouteParticipants,\n assertNoSvelteKitRouteRootSymlinkConflict,\n assertSvelteKitRouteCoordinationComplete,\n contributeSvelteKitRoutes,\n expectedSvelteKitRouteOwners,\n markSvelteKitRouteParticipant,\n producerKnowledgeRoutePaths,\n revokeSvelteKitRoutes,\n} from '../vite-plugin/sveltekit-route-coordinator.js';\nimport {\n generateWebModule,\n isCollectionManifestClass,\n resolveCollectionItemObject,\n} from '../vite-plugin/web-collections.js';\nimport { publishArtifactFiles } from './artifact-publication.js';\n\nexport {\n loadVerifiedSmrtGenerationSnapshot,\n type SerializeSmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotArtifact,\n type SmrtGenerationSnapshotOptions,\n type SmrtGenerationSnapshotView,\n serializeSmrtGenerationSnapshot,\n sha256SmrtGenerationSnapshot,\n} from '../generation-snapshot.js';\n\n/**\n * Loosely-typed view of an object definition as carried by an external\n * package's static manifest. The static manifests are read from JSON at the\n * package boundary, so only the fields this plugin consumes are typed; the\n * index signature preserves any additional fields (e.g. for spreads). This is\n * a structural superset of a manifest `SmartObjectDefinition` plus the\n * consumer-only `hasCollection` marker.\n */\ninterface ConsumerObjectDefinition {\n className?: string;\n packageName?: string;\n packageVersion?: string;\n qualifiedName?: string;\n importPath?: string;\n exportName?: string;\n collectionExportName?: string;\n hasCollection?: boolean;\n collection?: string;\n extends?: string;\n extendsQualified?: string;\n extendsTypeArg?: string;\n [key: string]: unknown;\n}\n\n/**\n * Aggregated manifest assembled by the consumer plugin from one or more\n * external package manifests. Loosely typed because the inputs originate from\n * JSON read at the package boundary.\n */\ninterface ConsumerManifest {\n version: string;\n timestamp: number;\n packageName?: string;\n packageVersion?: string;\n smrtDependencies?: string[];\n objects: Record<string, ConsumerObjectDefinition>;\n}\n\n/**\n * Minimal structural shape of a parsed `package.json` consumed here (name,\n * version, and the export map used to derive import paths). The index\n * signature keeps the remaining fields accessible.\n */\ninterface ConsumerPackageJson {\n name?: string;\n version?: string;\n main?: string;\n exports?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/**\n * SvelteKit route-hosting options for dependency models. Unlike `packages`,\n * `objects` is an HTTP exposure boundary: every entry must be an exact,\n * provider-qualified manifest key (for example, `@acme/widgets:Widget`).\n */\nexport interface SmrtConsumerSvelteKitOptions\n extends Partial<\n Pick<\n SvelteKitOptions,\n | 'routesDir'\n | 'configPath'\n | 'configFileName'\n | 'kebabRoutes'\n | 'changesRoute'\n | 'eventsRoute'\n | 'resourcesRoute'\n >\n > {\n objects: readonly string[];\n}\n\nexport interface SmrtConsumerOptions {\n /** SMRT packages to scan (e.g., ['@my-org/products', '@my-org/content']) */\n packages?: string[];\n /** Generate TypeScript declarations */\n generateTypes?: boolean;\n /** Output directory for generated types */\n typesDir?: string;\n /** Project root path (defaults to the current working directory) */\n projectRoot?: string;\n /**\n * Reuse an immutable, verified aggregated manifest instead of discovering\n * packages or writing `.smrt/manifest.json`. Registration and generated\n * types still consume the verified manifest.\n */\n generationSnapshot?: SmrtGenerationSnapshotOptions;\n /**\n * Consumer SvelteKit integration. `true` retains the historical compatibility\n * mode and does not generate dependency routes. Route hosting requires an\n * explicit, provider-qualified object allowlist.\n */\n svelteKit?: boolean | SmrtConsumerSvelteKitOptions;\n /**\n * Apply kebab-case to generated custom-method URL segments. This must match\n * the producer plugin's `svelteKit.kebabRoutes` setting. When explicit\n * consumer SvelteKit hosting is configured, its `kebabRoutes` value takes\n * precedence, including an explicit `false`.\n */\n kebabRoutes?: boolean;\n /** Use static types only (for federation builds) */\n staticTypes?: boolean;\n /** Disable file scanning */\n disableScanning?: boolean;\n}\n\n// Distinct resolved ids per plugin (#1795). smrtPlugin resolves\n// `@happyvertical/smrt-virt-*` to `\\0smrt:*`; if this consumer plugin also\n// resolved its `@smrt/*` specifiers to `\\0smrt:*` the two virtual modules would\n// share a rollup id, and in standalone/federation builds the consumer's\n// fallback `load` would non-deterministically win and shadow smrtPlugin's real\n// module. Namespacing the consumer ids (`\\0smrt-consumer:*`) keeps them\n// separate so each plugin only ever loads its own module.\nconst VIRTUAL_MODULES = {\n '@smrt/routes': 'smrt-consumer:routes',\n '@smrt/client': 'smrt-consumer:client',\n '@smrt/mcp': 'smrt-consumer:mcp',\n '@smrt/types': 'smrt-consumer:types',\n '@smrt/manifest': 'smrt-consumer:manifest',\n '@smrt/web': 'smrt-consumer:web',\n};\n\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION = 1;\nconst CONSUMER_SVELTEKIT_ROUTES_ARTIFACT = 'consumer-sveltekit-routes.json';\n\ninterface ConsumerSvelteKitRoutesArtifact {\n version: number;\n routesDir: string[];\n}\n\nfunction consumerSvelteKitRoutesArtifactPath(projectRoot: string): string {\n return path.join(projectRoot, '.smrt', CONSUMER_SVELTEKIT_ROUTES_ARTIFACT);\n}\n\n/** Persist only project-relative consumer route roots, never an output file list. */\nfunction canonicalConsumerRouteRoot(\n projectRoot: string,\n routesDir: string,\n): string {\n const root = path.resolve(projectRoot);\n const relative = path.relative(root, path.resolve(root, routesDir));\n if (\n !relative ||\n relative === '..' ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(\n `[smrt:consumer] svelteKit.routesDir must be a project-relative subdirectory (received ${JSON.stringify(routesDir)})`,\n );\n }\n return relative.split(path.sep).join('/');\n}\n\nfunction loadConsumerSvelteKitRouteRoots(projectRoot: string): string[] {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (!fs.existsSync(artifactPath)) return [];\n let parsed: ConsumerSvelteKitRoutesArtifact;\n try {\n parsed = JSON.parse(fs.readFileSync(artifactPath, 'utf-8'));\n } catch {\n throw new Error(\n `[smrt:consumer] Cannot read ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n if (\n parsed?.version !== CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION ||\n !Array.isArray(parsed.routesDir) ||\n parsed.routesDir.some((routesDir) => typeof routesDir !== 'string')\n ) {\n throw new Error(\n `[smrt:consumer] Invalid ${CONSUMER_SVELTEKIT_ROUTES_ARTIFACT}; refusing to leave hosted routes unreconciled`,\n );\n }\n return [...new Set(parsed.routesDir)].map((routesDir) =>\n canonicalConsumerRouteRoot(projectRoot, routesDir),\n );\n}\n\nfunction publishConsumerSvelteKitRouteRoots(\n projectRoot: string,\n routesDir: string[],\n): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n fs.mkdirSync(path.dirname(artifactPath), { recursive: true });\n publishArtifactFiles([\n {\n path: artifactPath,\n content: JSON.stringify(\n {\n version: CONSUMER_SVELTEKIT_ROUTES_ARTIFACT_VERSION,\n routesDir: [...new Set(routesDir)].sort(),\n } satisfies ConsumerSvelteKitRoutesArtifact,\n null,\n 2,\n ),\n },\n ]);\n}\n\nfunction removeConsumerSvelteKitRouteRoots(projectRoot: string): void {\n const artifactPath = consumerSvelteKitRoutesArtifactPath(projectRoot);\n if (fs.existsSync(artifactPath)) fs.unlinkSync(artifactPath);\n}\n\n/**\n * A hosting-to-hosting move can replace one configured root with another in a\n * fresh lifecycle. Validate every durable former root before the new target\n * journals or clears anything, otherwise a rejected move could alter the\n * prior generated surface before reconciliation notices the conflict.\n */\nasync function assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig: unknown,\n projectRoot: string,\n routesDir: readonly string[],\n env?: ConfigEnv,\n): Promise<void> {\n if (routesDir.length === 0) return;\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n const activeRoots = activeParticipants.map(\n (participant) => participant.routesDir,\n );\n for (const priorRoutesDir of routesDir) {\n assertNoSvelteKitRouteRootSymlinkConflict(\n canonicalSvelteKitPath(path.resolve(projectRoot, priorRoutesDir)),\n activeRoots,\n );\n }\n}\n\nasync function reconcileConsumerSvelteKitRouteRoots(\n lifecycle: object,\n userConfig: unknown,\n projectRoot: string,\n routesDir: string[],\n afterReconciled: () => void,\n env?: ConfigEnv,\n): Promise<void> {\n const remaining = new Set(routesDir);\n const reconcileOne = (routesDir: string) => {\n remaining.delete(routesDir);\n if (remaining.size === 0) afterReconciled();\n };\n\n if (remaining.size === 0) {\n afterReconciled();\n return;\n }\n\n for (const routesDir of [...remaining]) {\n const routeRoot = canonicalSvelteKitPath(\n path.resolve(projectRoot, routesDir),\n );\n const activeParticipants = await activeSvelteKitRouteParticipants(\n userConfig,\n projectRoot,\n env,\n );\n // The durable consumer inventory names roots, not individual handlers.\n // Check before every reconciliation branch, including an active parent\n // consumer that would otherwise compact a nested former root without a\n // sweep. A child symlink into a foreign active root makes that ownership\n // ambiguous, so retaining the inventory makes retry safe.\n assertNoSvelteKitRouteRootSymlinkConflict(\n routeRoot,\n activeParticipants.map((participant) => participant.routesDir),\n );\n const containingConsumer = activeParticipants.find(\n (participant) =>\n participant.owner === 'consumer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n // A current parent consumer root has already swept and regenerated this\n // former child root. Sweeping it again would remove the newly selected\n // handler before SvelteKit inventories it.\n if (containingConsumer) {\n reconcileOne(routesDir);\n continue;\n }\n const containingProducer = activeParticipants.find(\n (participant) =>\n participant.owner === 'producer' &&\n (routeRoot === participant.routesDir ||\n routeRoot.startsWith(`${participant.routesDir}${path.sep}`)),\n );\n if (containingProducer) {\n await revokeSvelteKitRoutes(\n lifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n containingProducer.projectRoot,\n containingProducer.routesDir,\n env,\n ),\n containingProducer.projectRoot,\n containingProducer.routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n const owners = await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routesDir,\n env,\n );\n if (owners.includes('producer')) {\n await revokeSvelteKitRoutes(\n lifecycle,\n owners,\n projectRoot,\n routesDir,\n () => reconcileOne(routesDir),\n );\n continue;\n }\n clearGeneratedSvelteKitRouteFiles(\n routeRoot,\n producerKnowledgeRoutePaths(lifecycle),\n new Set(\n activeParticipants\n .map((participant) => participant.routesDir)\n .filter((activeRoot) => activeRoot !== routeRoot),\n ),\n );\n reconcileSvelteKitRouteGitignore(projectRoot, routesDir);\n reconcileOne(routesDir);\n }\n}\n\nfunction consumerRouteOptions(\n value: SmrtConsumerOptions['svelteKit'],\n): SmrtConsumerSvelteKitOptions | undefined {\n if (!value || value === true) return undefined;\n if (!Array.isArray(value.objects) || value.objects.length === 0) {\n throw new Error(\n '[smrt:consumer] svelteKit.objects must list at least one provider-qualified object reference',\n );\n }\n for (const objectRef of value.objects) {\n if (typeof objectRef !== 'string' || !objectRef.includes(':')) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects entries must be provider-qualified (received ${JSON.stringify(objectRef)})`,\n );\n }\n }\n return value;\n}\n\nfunction consumerUtilityOption<T extends { enabled?: boolean }>(\n value: T | undefined,\n): T | { enabled: false } {\n return value?.enabled === true ? value : { enabled: false };\n}\n\nfunction consumerObjectRef(\n manifestKey: string,\n objectDef: ConsumerObjectDefinition,\n): string | undefined {\n if (manifestKey.includes(':')) return manifestKey;\n if (objectDef.qualifiedName?.includes(':')) return objectDef.qualifiedName;\n if (objectDef.packageName && objectDef.className) {\n return `${objectDef.packageName}:${objectDef.className}`;\n }\n return undefined;\n}\n\n/**\n * Select exactly the dependency objects that a consumer explicitly hosts.\n * Validation completes before the generator clears its managed files, so an\n * invalid deployment cannot erase a previously generated route surface.\n */\nfunction selectConsumerRouteManifest(\n manifest: ConsumerManifest,\n options: SmrtConsumerSvelteKitOptions,\n): SmartObjectManifest {\n const entriesByRef = new Map<string, [string, ConsumerObjectDefinition]>();\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const objectRef = consumerObjectRef(manifestKey, objectDef);\n if (objectRef) entriesByRef.set(objectRef, [manifestKey, objectDef]);\n }\n\n const selected = new Set<string>();\n const objects: Record<string, ConsumerObjectDefinition> = {};\n for (const objectRef of options.objects) {\n const entry = entriesByRef.get(objectRef);\n if (!entry) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects references unknown dependency object ${JSON.stringify(objectRef)}`,\n );\n }\n if (selected.has(objectRef)) {\n throw new Error(\n `[smrt:consumer] svelteKit.objects contains duplicate object ${JSON.stringify(objectRef)}`,\n );\n }\n selected.add(objectRef);\n const [, objectDef] = entry;\n objects[objectRef] = { ...objectDef, qualifiedName: objectRef };\n }\n\n const sourceManifest = manifest as unknown as SmartObjectManifest;\n // Use the generator's canonical ancestry resolver so a collection subclass\n // inherits the selected item's identity through any number of ancestors.\n for (const [manifestKey, objectDef] of Object.entries(manifest.objects)) {\n const candidate = objectDef as unknown as SmartObjectDefinition;\n if (!isCollectionManifestClass(sourceManifest, candidate)) continue;\n const item = resolveCollectionItemObject(sourceManifest, candidate);\n const itemEntry = item\n ? Object.entries(manifest.objects).find(\n ([, value]) => (value as unknown) === item,\n )\n : undefined;\n const itemRef = itemEntry\n ? consumerObjectRef(itemEntry[0], itemEntry[1])\n : undefined;\n if (!itemRef || !selected.has(itemRef)) continue;\n const collectionRef = consumerObjectRef(manifestKey, objectDef);\n if (collectionRef) {\n objects[collectionRef] = { ...objectDef, qualifiedName: collectionRef };\n }\n }\n\n return {\n ...manifest,\n // The generated route config imports this full registration entry point so\n // SSR retains every consumer provider, while only `objects` reach routing.\n // `smrtDependencies` is optional in verified snapshots, so derive this\n // generator signal from the immutable full manifest rather than treating\n // absent metadata as an empty provider inventory.\n smrtDependencies: [\n ...new Set(\n Object.values(manifest.objects)\n .map((objectDef) => objectDef.packageName)\n .filter(\n (packageName): packageName is string =>\n typeof packageName === 'string' &&\n packageName !== manifest.packageName,\n ),\n ),\n ].sort(),\n objects,\n } as unknown as SmartObjectManifest;\n}\n\n/**\n * Consumer plugin for projects that use SMRT packages\n */\nexport function smrtConsumer(options: SmrtConsumerOptions = {}): Plugin {\n const {\n packages = [],\n generateTypes = true,\n typesDir = 'src/types/smrt-generated',\n projectRoot = process.cwd(),\n generationSnapshot,\n disableScanning = false,\n kebabRoutes = false,\n } = options;\n const consumerSvelteKit = consumerRouteOptions(options.svelteKit);\n // Hosted routes, the generated client, and web tool definitions must expose\n // the same custom-action URLs. Nested consumer SvelteKit hosting owns this\n // policy when present, including an explicit false override.\n const effectiveKebabRoutes = consumerSvelteKit?.kebabRoutes ?? kebabRoutes;\n\n let smrtPackages: string[] = [];\n let typeManifest: ConsumerManifest | null = null;\n let typesGenerated = false;\n let producerApi: SmrtPluginApi | undefined;\n let routeLifecycleConfig: object | undefined;\n\n function loadGenerationSnapshot(): ConsumerManifest {\n if (!generationSnapshot) {\n throw new Error('[smrt:consumer] Generation snapshot is not configured');\n }\n return loadVerifiedSmrtGenerationSnapshot<ConsumerManifest>(\n generationSnapshot,\n projectRoot,\n 'dependencies',\n );\n }\n\n async function generateConfigTypes(\n manifest?: ConsumerManifest,\n ): Promise<void> {\n if (!generateTypes || typesGenerated) return;\n\n typeManifest =\n manifest ??\n (generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(\n packages.length === 0 && !disableScanning\n ? await discoverSmrtPackages(projectRoot)\n : packages,\n projectRoot,\n ));\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n\n const plugin: Plugin = {\n name: 'smrt-consumer',\n\n // SvelteKit inventories routes in its config hook. Run before it so a\n // clean consumer build sees the explicit dependency routes on its first\n // invocation, even when sveltekit() appears first in vite.config.\n enforce: 'pre',\n\n config: {\n order: 'pre',\n async handler(userConfig, env) {\n const routeLifecycle = env ?? userConfig;\n routeLifecycleConfig = routeLifecycle;\n const previousConsumerRouteRoots =\n loadConsumerSvelteKitRouteRoots(projectRoot);\n if (consumerSvelteKit) {\n await assertConsumerSvelteKitFormerRouteRootsAreSafe(\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n env,\n );\n const routePackages =\n packages.length === 0 && !disableScanning\n ? await discoverSmrtPackages(projectRoot)\n : packages;\n const routeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : await aggregateTypeManifests(routePackages, projectRoot);\n const hostedManifest = selectConsumerRouteManifest(\n routeManifest,\n consumerSvelteKit,\n );\n const routesDir = canonicalConsumerRouteRoot(\n projectRoot,\n consumerSvelteKit.routesDir ?? 'src/routes/api',\n );\n const reservedRoutePaths = await activeProducerKnowledgeRoutePaths(\n userConfig,\n projectRoot,\n env,\n );\n const routeOptions = {\n enabled: true,\n routesDir,\n objectsDir: 'src/lib/objects',\n configPath: consumerSvelteKit.configPath ?? 'src/lib/server',\n configFileName: consumerSvelteKit.configFileName ?? 'smrt.ts',\n kebabRoutes: effectiveKebabRoutes,\n // These span a model set rather than one selected object, so new\n // consumer hosting starts fail-closed. Callers can opt in with the\n // generator's established option shapes.\n changesRoute: consumerUtilityOption(consumerSvelteKit.changesRoute),\n eventsRoute: consumerUtilityOption(consumerSvelteKit.eventsRoute),\n resourcesRoute: consumerUtilityOption(\n consumerSvelteKit.resourcesRoute,\n ),\n rejectRouteCollisions: true,\n };\n let ownershipJournaled = false;\n let reconciliationScheduled = false;\n await contributeSvelteKitRoutes(\n routeLifecycle,\n await expectedSvelteKitRouteOwners(\n userConfig,\n projectRoot,\n routeOptions.routesDir,\n env,\n ),\n projectRoot,\n {\n owner: 'consumer',\n routeManifest: hostedManifest,\n semanticManifest: routeManifest as unknown as SmartObjectManifest,\n options: routeOptions,\n reservedRoutePaths,\n beforeCleanup: async () => {\n // Route selection and collision checks have succeeded, but no\n // generated output has changed. SvelteKit type checking still\n // runs after this config hook and needs these declarations.\n await generateConfigTypes(routeManifest);\n if (ownershipJournaled) return;\n ownershipJournaled = true;\n // Preflight has succeeded but no generated output has changed.\n // Keep both roots until old-root reconciliation commits.\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n ...previousConsumerRouteRoots,\n routesDir,\n ]);\n },\n afterGenerate: async () => {\n if (reconciliationScheduled) return;\n reconciliationScheduled = true;\n const priorRoots = previousConsumerRouteRoots.filter(\n (previousRoot) => previousRoot !== routesDir,\n );\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n priorRoots,\n () =>\n publishConsumerSvelteKitRouteRoots(projectRoot, [\n routesDir,\n ]),\n env,\n );\n },\n },\n );\n } else {\n // Legacy/non-hosting SvelteKit consumers have no route preflight,\n // but still need physical virtual-module declarations before their\n // SvelteKit typecheck reaches Vite's later buildStart lifecycle.\n await generateConfigTypes();\n if (previousConsumerRouteRoots.length > 0) {\n await reconcileConsumerSvelteKitRouteRoots(\n routeLifecycle,\n userConfig,\n projectRoot,\n previousConsumerRouteRoots,\n () => removeConsumerSvelteKitRouteRoots(projectRoot),\n env,\n );\n }\n }\n return {\n build: {\n rollupOptions: {\n // Runtime registration evaluates provider entry points so their\n // exact constructors can be registered. Leave optional native\n // provider binaries to Node instead of parsing them as JavaScript.\n external: [/\\.node$/],\n },\n },\n };\n },\n },\n\n configResolved(resolvedConfig) {\n if (consumerSvelteKit && routeLifecycleConfig) {\n assertSvelteKitRouteCoordinationComplete(routeLifecycleConfig);\n }\n producerApi = (resolvedConfig.plugins ?? []).find(\n (plugin) => plugin?.name === 'smrt-auto-service',\n )?.api as SmrtPluginApi | undefined;\n },\n\n async buildStart() {\n console.log('[smrt:consumer] Initializing SMRT consumer plugin');\n\n if (generationSnapshot) {\n typeManifest = loadGenerationSnapshot();\n console.log(\n `[smrt:consumer] Reusing verified generation snapshot (${generationSnapshot.provenance})`,\n );\n await generateRegistrationFile(typeManifest, projectRoot);\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n return;\n }\n\n // Discover SMRT packages if not explicitly specified\n if (packages.length === 0 && !disableScanning) {\n smrtPackages = await discoverSmrtPackages(projectRoot);\n } else {\n smrtPackages = packages;\n }\n\n if (smrtPackages.length > 0) {\n console.log(\n `[smrt:consumer] Found SMRT packages: ${smrtPackages.join(', ')}`,\n );\n\n // Aggregate type manifests from discovered packages\n typeManifest = await aggregateTypeManifests(smrtPackages, projectRoot);\n // Wait before reading .smrt/manifest.json: a producer's parallel\n // buildStart writes its current local manifest after scanning. Reading\n // first could merge an older local manifest with a newer surface.\n const agentSurface = producerApi\n ? await producerApi.resolveKnowledgeAgentSurface()\n : undefined;\n\n // Save aggregated manifest for CLI discovery\n await saveAggregatedManifest(\n typeManifest,\n projectRoot,\n producerApi?.resolveKnowledgeConfig,\n agentSurface,\n );\n\n // Generate registration file for CLI class loading\n await generateRegistrationFile(typeManifest, projectRoot);\n\n // Generate types if requested\n if (generateTypes && !typesGenerated) {\n await generateProjectTypes(typeManifest, typesDir, projectRoot);\n typesGenerated = true;\n }\n } else {\n console.log('[smrt:consumer] No SMRT packages found');\n typeManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n },\n\n resolveId(id, _importer) {\n // Resolve virtual modules to generated type declarations\n if (id in VIRTUAL_MODULES) {\n // Generated declarations are ambient TypeScript declarations, not\n // executable JavaScript. Vite must always load the consumer runtime\n // module after default type generation writes them.\n if (id !== '@smrt/types') {\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n\n const typeFileName = getTypeFileName(id);\n const typePath = path.join(projectRoot, typesDir, typeFileName);\n\n // If types file exists, resolve to it\n if (fs.existsSync(typePath)) {\n return typePath;\n }\n\n // Otherwise use virtual module ID for runtime resolution\n return `\\0${VIRTUAL_MODULES[id as keyof typeof VIRTUAL_MODULES]}`;\n }\n return null;\n },\n\n async load(id) {\n // Handle virtual modules if types aren't available\n const cleanId = id.startsWith('\\0') ? id.slice(1) : id;\n\n if (!typeManifest) {\n typeManifest = generationSnapshot\n ? loadGenerationSnapshot()\n : {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n objects: {},\n };\n }\n\n switch (cleanId) {\n case 'smrt-consumer:routes':\n return generateFallbackRoutesModule();\n\n case 'smrt-consumer:client':\n return generateFallbackClientModule(typeManifest, {\n kebabRoutes: effectiveKebabRoutes,\n });\n\n case 'smrt-consumer:mcp':\n return generateFallbackMcpModule();\n\n case 'smrt-consumer:types':\n return generateFallbackTypesModule(typeManifest);\n\n case 'smrt-consumer:manifest':\n return generateFallbackManifestModule(typeManifest);\n\n case 'smrt-consumer:web':\n return generateWebModule(\n typeManifest as unknown as SmartObjectManifest,\n {\n kebabRoutes: effectiveKebabRoutes,\n },\n );\n\n default:\n return null;\n }\n },\n };\n markSvelteKitRouteParticipant(\n plugin,\n 'consumer',\n Boolean(consumerSvelteKit),\n consumerSvelteKit?.routesDir ?? 'src/routes/api',\n undefined,\n () => projectRoot,\n );\n return plugin;\n}\n\n/**\n * Discover SMRT packages from a consumer app's dependencies.\n *\n * Intentional split (#1579): this **consumer-plugin** path is async and\n * resolves SMRT packages from the downstream app's `package.json` dependency\n * names (`@have/`/`smrt` heuristic + `hasSmrtManifest` probe) inside the Vite\n * consumer plugin. It is deliberately separate from the build-time\n * `discoverSmrtPackages()` in `src/manifest/discover-smrt-packages.ts` — a\n * synchronous, lockfile-cached `node_modules` manifest scan used for manifest\n * generation. Different inputs, contexts, and lifecycles, not duplicated logic.\n */\nasync function discoverSmrtPackages(projectRoot: string): Promise<string[]> {\n const packages: string[] = [];\n const nodeModulesPath = path.join(projectRoot, 'node_modules');\n\n if (!fs.existsSync(nodeModulesPath)) {\n return packages;\n }\n\n try {\n // Check package.json for workspace dependencies\n const packageJsonPath = path.join(projectRoot, 'package.json');\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Look for packages that likely contain SMRT objects\n for (const [name, version] of Object.entries(allDeps)) {\n if (\n typeof version === 'string' &&\n (name.includes('smrt') ||\n name.includes('@have/') ||\n (await hasSmrtManifest(nodeModulesPath, name)))\n ) {\n packages.push(name);\n }\n }\n }\n } catch (error) {\n console.warn('[smrt:consumer] Error discovering packages:', error);\n }\n\n return packages;\n}\n\n/**\n * Check if a package has SMRT manifest\n */\nasync function hasSmrtManifest(\n nodeModulesPath: string,\n packageName: string,\n): Promise<boolean> {\n const packagePath = path.join(nodeModulesPath, packageName);\n const manifestPath = path.join(\n packagePath,\n 'dist',\n 'manifest',\n 'static-manifest.js',\n );\n return fs.existsSync(manifestPath);\n}\n\n/**\n * Aggregate type manifests from multiple packages\n */\nasync function aggregateTypeManifests(\n packages: string[],\n projectRoot: string,\n): Promise<ConsumerManifest> {\n const aggregatedManifest: ConsumerManifest = {\n version: '1.0.0',\n timestamp: MANIFEST_TIMESTAMP,\n smrtDependencies: [...packages],\n objects: {},\n };\n\n for (const packageName of packages) {\n try {\n const packageDir = path.join(projectRoot, 'node_modules', packageName);\n\n // Load package.json for version and export information\n const packageJsonPath = path.join(packageDir, 'package.json');\n let packageJson: ConsumerPackageJson;\n try {\n const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf-8');\n packageJson = JSON.parse(packageJsonContent) as ConsumerPackageJson;\n } catch {\n console.warn(\n `[smrt:consumer] Could not read package.json for ${packageName}`,\n );\n continue;\n }\n\n // Try multiple manifest locations\n const manifestCandidates = [\n path.join(packageDir, 'dist', 'manifest', 'static-manifest.js'),\n path.join(packageDir, 'dist', 'manifest.json'),\n path.join(packageDir, 'manifest.json'),\n ];\n\n for (const manifestPath of manifestCandidates) {\n if (fs.existsSync(manifestPath)) {\n // Import or read the manifest\n let manifest: Partial<ConsumerManifest> | undefined;\n if (manifestPath.endsWith('.js')) {\n const manifestModule = await import(manifestPath);\n manifest = manifestModule.staticManifest || manifestModule.default;\n } else {\n const manifestContent = fs.readFileSync(manifestPath, 'utf-8');\n manifest = JSON.parse(manifestContent) as Partial<ConsumerManifest>;\n }\n\n if (manifest?.objects) {\n console.log(\n `[smrt:consumer] Loaded manifest from ${packageName} (${Object.keys(manifest.objects).length} objects)`,\n );\n\n // ENHANCED: Preserve package metadata for each object\n for (const [objectName, objectDef] of Object.entries(\n manifest.objects,\n )) {\n const def = objectDef;\n\n aggregatedManifest.objects[objectName] = {\n ...def,\n // Ensure package metadata is preserved/set\n packageName:\n def.packageName || manifest.packageName || packageName,\n packageVersion:\n def.packageVersion ||\n manifest.packageVersion ||\n packageJson.version,\n // Add fallback import paths if missing\n importPath: def.importPath || determineImportPath(packageJson),\n exportName: def.exportName || def.className || objectName,\n collectionExportName:\n def.collectionExportName ||\n `${def.className || objectName}Collection`,\n };\n }\n\n break; // Use first found manifest for this package\n }\n }\n }\n } catch (error) {\n console.warn(\n `[smrt:consumer] Error loading manifest from ${packageName}:`,\n error,\n );\n }\n }\n\n return aggregatedManifest;\n}\n\n/**\n * Determine import path from package.json\n */\nfunction determineImportPath(packageJson: ConsumerPackageJson): string {\n const packageName = packageJson.name;\n\n if (!packageName) {\n throw new Error('Package name not found in package.json');\n }\n\n // Strategy 1: Check for specific exports\n if (packageJson.exports) {\n // Check for objects export\n if (packageJson.exports['./objects']) {\n return `${packageName}/objects`;\n }\n\n // Check for main export\n const mainExport = packageJson.exports['.'];\n if (mainExport) {\n // Handle conditional exports\n if (typeof mainExport === 'object' && mainExport !== null) {\n const conditional = mainExport as Record<string, unknown>;\n if (conditional.import) {\n return packageName;\n }\n if (conditional.default) {\n return packageName;\n }\n }\n return packageName;\n }\n }\n\n // Strategy 2: Check main field\n if (packageJson.main) {\n return packageName;\n }\n\n // Strategy 3: Fallback to package name\n return packageName;\n}\n\n/**\n * Save aggregated manifest to .smrt/manifest.json for CLI discovery.\n *\n * Merge-preserving: `smrtPlugin()` writes the project's own scanned objects\n * to the same file (`writeLocalManifest`, issue #963), and both writes happen\n * in parallel `buildStart` hooks — so a plain overwrite here would clobber\n * the local objects whenever this plugin's write lands last (issue #1760\n * review). Local field metadata would then silently vanish from CLI schema\n * commands and from server runtimes that seed `.smrt/manifest.json`, dropping\n * domain columns on write. This function therefore only ADDS/refreshes the\n * external-package entries it owns and preserves everything else already in\n * the file (including the top-level `packageName` the local write sets).\n */\nasync function saveAggregatedManifest(\n manifest: ConsumerManifest,\n projectRoot: string,\n resolveKnowledgeConfig?: SmrtPluginApi['resolveKnowledgeConfig'],\n agentSurface?: DomainKnowledgeAgentSurface,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const manifestPath = path.join(smrtDir, 'manifest.json');\n\n try {\n // Create .smrt directory if it doesn't exist\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Merge with whatever is on disk: existing entries (typically the local\n // project's objects written by smrtPlugin) are preserved; aggregated\n // external entries win for the qualified names this plugin owns.\n let merged: ConsumerManifest = manifest;\n if (fs.existsSync(manifestPath)) {\n try {\n const existing = JSON.parse(\n fs.readFileSync(manifestPath, 'utf-8'),\n ) as Partial<ConsumerManifest>;\n if (existing && typeof existing.objects === 'object') {\n merged = {\n ...existing,\n ...manifest,\n // The aggregated manifest carries no packageName; keep the local\n // project's (used as the manifest cache key at runtime).\n ...(existing.packageName\n ? { packageName: existing.packageName }\n : {}),\n objects: { ...existing.objects, ...manifest.objects },\n };\n }\n } catch {\n // Unreadable/corrupt existing file — fall back to a plain write.\n }\n }\n\n // smrtPlugin writes the local knowledge artifact before this consumer\n // plugin merges external package entries into the same manifest. Refresh\n // the artifact from the merged manifest so its source hash always names\n // the manifest that CLI discovery and server runtimes actually consume.\n // The consumer deliberately does not load the scanner. Only carry a\n // surface from the current producer scan: a prior artifact can describe\n // declarations that have since changed while retaining the same path.\n // Re-hashing that current path under a stale declaration would make an\n // incorrect agent contract look fresh.\n const knowledgePath = path.join(smrtDir, 'smrt-knowledge.json');\n const packageJsonPath = path.join(projectRoot, 'package.json');\n const packageJson = fs.existsSync(packageJsonPath)\n ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n : undefined;\n const knowledgeConfig = resolveKnowledgeConfig\n ? await resolveKnowledgeConfig(merged as unknown as SmartObjectManifest)\n : await resolveFileKnowledgeConfig(\n projectRoot,\n merged.packageName ?? packageJson?.name,\n );\n if (knowledgeConfig.enabled === false) {\n publishArtifactFiles([\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n return;\n }\n const knowledge = buildDomainKnowledgeManifest({\n manifest: merged as unknown as SmartObjectManifest,\n rootDir: projectRoot,\n packageJson,\n manifestPath,\n config: knowledgeConfig,\n agentSurface,\n });\n // Stage both artifacts before replacing either. Renames are individually\n // atomic; if a synchronous later rename fails, restore every earlier\n // replacement. A process crash between renames cannot be made pair-atomic\n // with ordinary filesystem operations, so the next generation remains the\n // freshness repair path for that distinct failure mode.\n publishArtifactFiles([\n { path: knowledgePath, content: JSON.stringify(knowledge, null, 2) },\n { path: manifestPath, content: JSON.stringify(merged, null, 2) },\n ]);\n\n console.log(\n `[smrt:consumer] Saved aggregated manifest to .smrt/manifest.json (${Object.keys(merged.objects).length} objects)`,\n );\n } catch (error) {\n throw new Error('[smrt:consumer] Failed to save aggregated manifest', {\n cause: error,\n });\n }\n}\n\n/**\n * Generate registration file for CLI class loading\n *\n * Creates .smrt/register.js with static imports and registrations\n * for all external SMRT objects discovered during build.\n */\nasync function generateRegistrationFile(\n manifest: ConsumerManifest,\n projectRoot: string,\n): Promise<void> {\n const smrtDir = path.join(projectRoot, '.smrt');\n const registerPath = path.join(smrtDir, 'register.js');\n\n // Bind every imported symbol to a generated local name. Aggregated manifests\n // may contain same-named exports from different packages (and may list a\n // collection both beside its object and as its own manifest entry), so using\n // provider export names as local bindings can produce invalid duplicate\n // imports in a production consumer bundle.\n const importBindings = new Map<string, string>();\n const importsByPath = new Map<string, Map<string, string>>();\n let nextImportBinding = 0;\n const getImportBinding = (importPath: string, exportName: string): string => {\n const key = `${importPath}\\0${exportName}`;\n const existing = importBindings.get(key);\n if (existing) return existing;\n const binding = `__smrt_consumer_${nextImportBinding++}`;\n importBindings.set(key, binding);\n const specifiers =\n importsByPath.get(importPath) ?? new Map<string, string>();\n specifiers.set(exportName, binding);\n importsByPath.set(importPath, specifiers);\n return binding;\n };\n\n const registrations: string[] = [];\n const registrationManifests: Record<string, ConsumerManifest> = {};\n let importedEntryCount = 0;\n let registeredObjectCount = 0;\n\n const manifestObjects = manifest.objects;\n const manifestObjectLookup = new Map<string, ConsumerObjectDefinition>();\n for (const [key, def] of Object.entries(manifestObjects)) {\n const candidate = def;\n const lookupKeys = [\n key,\n key.includes(':') ? key.split(':').pop() : undefined,\n candidate.qualifiedName,\n candidate.className,\n candidate.exportName,\n ];\n\n for (const lookupKey of lookupKeys) {\n if (lookupKey && !manifestObjectLookup.has(lookupKey)) {\n manifestObjectLookup.set(lookupKey, candidate);\n }\n }\n }\n\n const collectionClassMemo = new WeakMap<object, boolean>();\n\n const isCollectionClass = (\n def: ConsumerObjectDefinition | undefined,\n seen = new Set<string>(),\n ): boolean => {\n if (!def || typeof def !== 'object') {\n return false;\n }\n\n const cached = collectionClassMemo.get(def);\n if (cached !== undefined) {\n return cached;\n }\n\n if (\n def?.extends === 'SmrtCollection' ||\n def?.extendsTypeArg !== undefined\n ) {\n collectionClassMemo.set(def, true);\n return true;\n }\n\n const parentName = def?.extendsQualified || def?.extends;\n if (!parentName || seen.has(parentName)) {\n collectionClassMemo.set(def, false);\n return false;\n }\n seen.add(parentName);\n\n const parentDef = manifestObjectLookup.get(parentName);\n const isCollection = parentDef ? isCollectionClass(parentDef, seen) : false;\n collectionClassMemo.set(def, isCollection);\n\n return isCollection;\n };\n\n for (const [objectName, objectDef] of Object.entries(manifestObjects)) {\n const def = objectDef;\n\n // Skip local objects (they're imported from local entry point)\n if (!def.packageName || def.packageName === manifest.packageName) {\n continue;\n }\n\n const importPath = def.importPath || def.packageName;\n const exportName = def.exportName || def.className || objectName;\n const collectionExportName = def.collectionExportName;\n const hasCollection = def.hasCollection; // Check if collection class actually exists\n const tableName = def.collection || objectName.toLowerCase();\n\n const exportBinding = getImportBinding(importPath, exportName);\n const collectionBinding =\n hasCollection && collectionExportName\n ? getImportBinding(importPath, collectionExportName)\n : undefined;\n importedEntryCount++;\n\n if (isCollectionClass(def)) {\n continue;\n }\n\n const logicalName = def.className || exportName;\n registrationManifests[objectName] = {\n ...manifest,\n packageName: def.packageName,\n packageVersion: def.packageVersion || manifest.packageVersion,\n objects: { [objectName]: def },\n };\n\n // Import evaluation triggers the provider decorator first. The explicit\n // constructor/package/key tuple then promotes that exact constructor with\n // its isolated manifest, which is stable across Rollup name deconfliction.\n registrations.push(\n `if (${exportBinding}) ObjectRegistry.register(${exportBinding}, { name: ${JSON.stringify(logicalName)}, packageName: ${JSON.stringify(def.packageName)}, _manifest: smrtRegistrationManifests[${JSON.stringify(objectName)}], _manifestKey: ${JSON.stringify(objectName)} });`,\n );\n\n // Only register collection if it exists\n if (collectionBinding) {\n registrations.push(\n `if (${collectionBinding}) ObjectRegistry.registerCollection('${tableName}', ${collectionBinding});`,\n );\n }\n\n registeredObjectCount++;\n }\n\n // Skip generation if no external entries\n if (importedEntryCount === 0) {\n console.log('[smrt:consumer] No external entries - skipping register.js');\n return;\n }\n\n const registeredObjectLabel =\n registeredObjectCount === 1 ? 'object' : 'objects';\n const sortedImports = Array.from(importsByPath.entries()).sort(\n ([left], [right]) => left.localeCompare(right),\n );\n const imports = sortedImports.map(\n ([importPath], index) =>\n `import * as __smrt_provider_${index} from '${importPath}';`,\n );\n const importDeclarations = sortedImports.flatMap(([, specifiers], index) =>\n Array.from(specifiers.entries())\n .sort(([left], [right]) => left.localeCompare(right))\n .map(\n ([exportName, binding]) =>\n `const ${binding} = getSmrtExport(__smrt_provider_${index}, ${JSON.stringify(exportName)});`,\n ),\n );\n const registrationManifestLiteral = JSON.stringify(\n JSON.stringify(registrationManifests),\n );\n\n // Generate file content\n const content = `/**\n * Auto-generated by @happyvertical/smrt-core/consumer-plugin\n * DO NOT EDIT - This file is regenerated on every build\n *\n * Registers SMRT objects from external packages for CLI discovery.\n * Generated at: ${new Date().toISOString()}\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n${imports.join('\\n')}\n\n/**\n * @param {Record<string, unknown>} provider\n * @param {string} exportName\n * @returns {any}\n */\nconst getSmrtExport = (provider, exportName) =>\n typeof provider[exportName] === 'function' ? provider[exportName] : undefined;\n${importDeclarations.join('\\n')}\n\nconst smrtRegistrationManifests = JSON.parse(${registrationManifestLiteral});\n\n// Register all objects (executed during module evaluation)\n${registrations.join('\\n')}\n\nexport function registerAll() {\n // Objects are already registered during module evaluation\n console.log('[smrt:register] Registered ${registeredObjectCount} external ${registeredObjectLabel}');\n}\n`;\n\n // Create .smrt directory if needed\n if (!fs.existsSync(smrtDir)) {\n fs.mkdirSync(smrtDir, { recursive: true });\n }\n\n // Write registration file\n fs.writeFileSync(registerPath, content, 'utf-8');\n\n console.log(\n `[smrt:consumer] Generated .smrt/register.js with ${importedEntryCount} external entries (${registeredObjectCount} registered ${registeredObjectLabel})`,\n );\n}\n\n/**\n * Generate project-specific types\n */\nasync function generateProjectTypes(\n typeManifest: ConsumerManifest,\n typesDir: string,\n projectRoot: string,\n): Promise<void> {\n if (!typeManifest || Object.keys(typeManifest.objects).length === 0) {\n console.log(\n '[smrt:consumer] No SMRT objects found, skipping type generation',\n );\n return;\n }\n\n await generateDeclarations({\n // The aggregated manifest is a runtime SMRT manifest assembled from external\n // package manifests; it is intentionally typed loosely at the JSON boundary,\n // so narrow it to the declaration generator's strict manifest shape here.\n manifest: typeManifest as unknown as SmartObjectManifest,\n outDir: typesDir,\n projectRoot,\n includeVirtualModules: true,\n includeObjectTypes: true,\n });\n\n console.log(\n `[smrt:consumer] Generated types for ${Object.keys(typeManifest.objects).length} objects`,\n );\n}\n\n/**\n * Get type file name for virtual module\n */\nfunction getTypeFileName(virtualModule: string): string {\n const moduleMap: Record<string, string> = {\n '@smrt/routes': 'smrt-routes.d.ts',\n '@smrt/client': 'smrt-client.d.ts',\n '@smrt/mcp': 'smrt-mcp.d.ts',\n '@smrt/types': 'smrt-types.d.ts',\n '@smrt/manifest': 'smrt-manifest.d.ts',\n '@smrt/web': 'smrt-web.d.ts',\n };\n return moduleMap[virtualModule] || 'smrt-unknown.d.ts';\n}\n\n/**\n * Fallback modules for when types aren't available\n */\nfunction generateFallbackRoutesModule(): string {\n return `\n// Fallback routes module\nexport function setupRoutes(app) {\n console.warn('[smrt:consumer] No routes available - SMRT packages may not be properly configured');\n}\nexport default setupRoutes;\n`;\n}\n\nfunction generateFallbackClientModule(\n manifest: ConsumerManifest,\n options: { kebabRoutes?: boolean } = {},\n): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `\n// Fallback client module\nexport function createClient(basePath = '/api/v1') {\n console.warn('[smrt:consumer] No API client available - SMRT packages may not be properly configured');\n return {};\n}\nexport default createClient;\n`;\n }\n\n return generateClientModule(manifest as unknown as SmartObjectManifest, {\n kebabRoutes: options.kebabRoutes,\n });\n}\n\nfunction generateFallbackMcpModule(): string {\n return `\n// Fallback MCP module\nexport const tools = [];\nexport function createMCPServer() {\n console.warn('[smrt:consumer] No MCP tools available - SMRT packages may not be properly configured');\n return { name: 'smrt-consumer', version: '1.0.0', tools: [] };\n}\nexport default createMCPServer;\n`;\n}\n\nfunction generateFallbackTypesModule(manifest: ConsumerManifest): string {\n const objects = Object.entries(manifest?.objects || {});\n if (objects.length === 0) {\n return `// No types available`;\n }\n\n // Generate basic interfaces\n const interfaces = objects.map(([_name, obj]) => {\n return `export interface ${obj.className}Data {\n id?: string;\n created_at?: string;\n updated_at?: string;\n [key: string]: any;\n}`;\n });\n\n return interfaces.join('\\n\\n');\n}\n\nfunction generateFallbackManifestModule(manifest: ConsumerManifest): string {\n return `\n// Auto-generated manifest from SMRT consumer\nexport const manifest = ${JSON.stringify(manifest, null, 2)};\nexport default manifest;\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0KA,IAAM,kBAAkB;CACtB,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,aAAa;AACf;AAEA,IAAM,6CAA6C;AACnD,IAAM,qCAAqC;AAO3C,SAAS,oCAAoC,aAA6B;CACxE,OAAO,KAAK,KAAK,aAAa,SAAS,kCAAkC;AAC3E;;AAGA,SAAS,2BACP,aACA,WACQ;CACR,MAAM,OAAO,KAAK,QAAQ,WAAW;CACrC,MAAM,WAAW,KAAK,SAAS,MAAM,KAAK,QAAQ,MAAM,SAAS,CAAC;CAClE,IACE,CAAC,YACD,aAAa,QACb,SAAS,WAAW,KAAK,KAAK,KAAK,KACnC,KAAK,WAAW,QAAQ,GAExB,MAAM,IAAI,MACR,yFAAyF,KAAK,U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EAAE;;;AAG5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"static-manifest.d.ts","sourceRoot":"","sources":["../../src/manifest/static-manifest.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,eAAO,MAAM,cAAc,EAAE,
|
|
1
|
+
{"version":3,"file":"static-manifest.d.ts","sourceRoot":"","sources":["../../src/manifest/static-manifest.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAE/D,eAAO,MAAM,cAAc,EAAE,mBA4qDnB,CAAC;AAEX,eAAe,cAAc,CAAC"}
|
|
@@ -3,7 +3,7 @@ var staticManifest = {
|
|
|
3
3
|
"version": "1.0.0",
|
|
4
4
|
"timestamp": 0,
|
|
5
5
|
"packageName": "@happyvertical/smrt-core",
|
|
6
|
-
"packageVersion": "0.49.
|
|
6
|
+
"packageVersion": "0.49.7",
|
|
7
7
|
"objects": {
|
|
8
8
|
"@happyvertical/smrt-core:SmrtClass": {
|
|
9
9
|
"name": "smrtclass",
|
|
@@ -121,7 +121,8 @@ var staticManifest = {
|
|
|
121
121
|
"columns": ["created_at"]
|
|
122
122
|
}],
|
|
123
123
|
"version": "234a72b0"
|
|
124
|
-
}
|
|
124
|
+
},
|
|
125
|
+
"importPath": "@happyvertical/smrt-core"
|
|
125
126
|
},
|
|
126
127
|
"@happyvertical/smrt-core:SmrtCollection": {
|
|
127
128
|
"name": "smrtcollection",
|
|
@@ -674,7 +675,8 @@ var staticManifest = {
|
|
|
674
675
|
"columns": ["created_at"]
|
|
675
676
|
}],
|
|
676
677
|
"version": "295b0a80"
|
|
677
|
-
}
|
|
678
|
+
},
|
|
679
|
+
"importPath": "@happyvertical/smrt-core"
|
|
678
680
|
},
|
|
679
681
|
"@happyvertical/smrt-core:SmrtHierarchical": {
|
|
680
682
|
"name": "smrthierarchical",
|
|
@@ -749,7 +751,8 @@ var staticManifest = {
|
|
|
749
751
|
"decoratorConfig": {},
|
|
750
752
|
"extends": "SmrtObject",
|
|
751
753
|
"exportName": "SmrtHierarchical",
|
|
752
|
-
"collectionExportName": "SmrtHierarchicalCollection"
|
|
754
|
+
"collectionExportName": "SmrtHierarchicalCollection",
|
|
755
|
+
"importPath": "@happyvertical/smrt-core"
|
|
753
756
|
},
|
|
754
757
|
"@happyvertical/smrt-core:SmrtJunction": {
|
|
755
758
|
"name": "smrtjunction",
|
|
@@ -869,7 +872,8 @@ var staticManifest = {
|
|
|
869
872
|
"extends": "SmrtCollection",
|
|
870
873
|
"extendsTypeArg": "TItem",
|
|
871
874
|
"exportName": "SmrtJunction",
|
|
872
|
-
"collectionExportName": "SmrtJunctionCollection"
|
|
875
|
+
"collectionExportName": "SmrtJunctionCollection",
|
|
876
|
+
"importPath": "@happyvertical/smrt-core"
|
|
873
877
|
},
|
|
874
878
|
"@happyvertical/smrt-core:SmrtObject": {
|
|
875
879
|
"name": "smrtobject",
|
|
@@ -1412,7 +1416,8 @@ var staticManifest = {
|
|
|
1412
1416
|
"columns": ["created_at"]
|
|
1413
1417
|
}],
|
|
1414
1418
|
"version": "204bf3c4"
|
|
1415
|
-
}
|
|
1419
|
+
},
|
|
1420
|
+
"importPath": "@happyvertical/smrt-core"
|
|
1416
1421
|
},
|
|
1417
1422
|
"@happyvertical/smrt-core:SmrtPolymorphicAssociation": {
|
|
1418
1423
|
"name": "smrtpolymorphicassociation",
|
|
@@ -1471,7 +1476,8 @@ var staticManifest = {
|
|
|
1471
1476
|
"rule": "required",
|
|
1472
1477
|
"fieldType": "text"
|
|
1473
1478
|
}
|
|
1474
|
-
]
|
|
1479
|
+
],
|
|
1480
|
+
"importPath": "@happyvertical/smrt-core"
|
|
1475
1481
|
}
|
|
1476
1482
|
},
|
|
1477
1483
|
"moduleType": "smrt"
|