@agimon-ai/po-build 0.0.0-alpha.3 → 0.0.0-alpha.4

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["fs","path","renderServerEntry","renderWebEntry","renderNativeEntry","renderMcpEntry","GENERATED_ENTRY_FILENAMES","scanExtensions","renderMcpWidgets","GENERATED_DIR","BUILD_TARGET_PLATFORMS","RETIRED_PLATFORM_NOTICE","resolveTarget","renderApiClient","GENERATED_CLIENT_NAME","renderNativeApiClient","GENERATED_NATIVE_CLIENT_NAME","API_ROUTES_MODULE","GENERATED_ENTRY_NAMES","writeGenerated","require_runtime","require_layout","require_index","require_index$1","require_index$2","require_index$3","require_index$4","require_index$5","node_fs","node_path","defaultPluginId","packageName","readPackageName","manifest","packageDir","RENDERERS","ENTRY_FILENAME","generateExtension","options","pluginId","graph","notices","files","targets","mcpWidgets","entry","retired","notice","requestedTargets","target","resolution","render","source","hasRouteTable","hasBrowserHalf","client","hasNativeHalf","nativeClient","managed","name"],"sources":["../../../src/services/generate/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n API_ROUTES_MODULE,\n BUILD_TARGET_PLATFORMS,\n GENERATED_CLIENT_NAME,\n GENERATED_DIR,\n GENERATED_ENTRY_FILENAMES,\n GENERATED_ENTRY_NAMES,\n GENERATED_NATIVE_CLIENT_NAME,\n} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient, renderNativeApiClient } from '../renderClient';\nimport { renderMcpEntry, renderNativeEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { renderMcpWidgets } from '../renderMcpWidgets';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { RETIRED_PLATFORM_NOTICE, scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/po-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^po-/u, '');\n}\n\nfunction readPackageName(packageDir: string): string {\n const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8')) as { name?: unknown };\n if (typeof manifest.name !== 'string') throw new Error(`${packageDir}/package.json has no name`);\n return manifest.name;\n}\n\nconst RENDERERS: Readonly<Record<BuildTarget, typeof renderServerEntry>> = {\n server: renderServerEntry,\n web: renderWebEntry,\n native: renderNativeEntry,\n mcp: renderMcpEntry,\n};\n\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\n\n/**\n * Scans a package and renders every entry its tree calls for.\n *\n * A target with nothing in it produces no file, so a backend-only package\n * never grows an empty cockpit entry. Notices from the scan and from each\n * resolution are gathered rather than thrown: an unrecognised folder costs\n * that folder, never the build.\n */\nexport function generateExtension(options: GenerateOptions): GenerateResult {\n const packageName = options.packageName ?? readPackageName(options.packageDir);\n const pluginId = options.pluginId ?? defaultPluginId(packageName);\n\n const graph: ExtensionGraph = scanExtensions(options);\n const notices: ExtensionNotice[] = [...graph.notices];\n const files = new Map<string, string>();\n const targets: BuildTarget[] = [];\n const mcpWidgets = options.target === 'mcp' ? renderMcpWidgets(graph, packageName, GENERATED_DIR) : undefined;\n if (mcpWidgets?.source !== undefined) files.set(`${GENERATED_DIR}/mcp-ui.ts`, mcpWidgets.source);\n\n // Here rather than in the scan, deliberately. The doomRoutedFilePosition lint\n // rule calls scanExtensions() directly, so a scan notice would make `.ios` a\n // hard preflight failure and cost us the forward-looking platforms we kept on\n // purpose. resolveTarget runs once per target, which would repeat it per target.\n for (const entry of graph.entries) {\n if (entry.platform === undefined || BUILD_TARGET_PLATFORMS.includes(entry.platform)) continue;\n notices.push({\n path: entry.file,\n message: `'${entry.platform}' is a forward-looking platform with no build target; this file is not emitted for server, web, native or mcp`,\n });\n }\n\n const retired = graph.notices.filter((notice) => notice.message === RETIRED_PLATFORM_NOTICE);\n if (retired.length > 0) {\n throw new Error(\n `${packageName}: ${RETIRED_PLATFORM_NOTICE}\\n${retired.map((notice) => ` ${notice.path}`).join('\\n')}`,\n );\n }\n\n const requestedTargets = options.target === undefined ? (['server', 'web', 'native'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n if (resolution.contributions.length === 0 && resolution.escapeHatches.length === 0 && resolution.roots.length === 0)\n continue;\n\n targets.push(target);\n const render = RENDERERS[target];\n const source = render(resolution, {\n packageName,\n pluginId,\n root: graph.root,\n entryDir: GENERATED_DIR,\n mcpWidgets: mcpWidgets?.declarations,\n });\n files.set(`${GENERATED_DIR}/${ENTRY_FILENAME[target]}.ts`, source);\n }\n\n // Not another build target: no host loads it as an entry, and adding one to\n // the target loop would mean a resolution pass and a contribution field for\n // something that is only ever imported by a routed frontend file.\n //\n // Only for a package that has a browser half. The client exists to be called\n // from a page and it carries the sealed transport, so emitting one into a\n // node-only package asks that package to depend on a browser runtime it never\n // loads, to satisfy a file nothing imports.\n const hasRouteTable = options.target === undefined && fs.existsSync(path.join(options.packageDir, API_ROUTES_MODULE));\n const hasBrowserHalf = targets.includes('web');\n const client =\n hasRouteTable && hasBrowserHalf\n ? renderApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (client !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_CLIENT_NAME}.ts`, client);\n\n // The native half gets its own file rather than a shared one, because the\n // browser client's two imports are exactly what the native host refuses.\n const hasNativeHalf = targets.includes('native');\n const nativeClient =\n hasRouteTable && hasNativeHalf\n ? renderNativeApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (nativeClient !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_NATIVE_CLIENT_NAME}.ts`, nativeClient);\n if (hasRouteTable && (hasBrowserHalf || hasNativeHalf) && client === undefined && nativeClient === undefined) {\n notices.push({\n path: API_ROUTES_MODULE,\n message: 'declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted',\n });\n }\n\n const managed =\n options.target === undefined\n ? GENERATED_ENTRY_NAMES.filter(\n (name) => name !== 'mcp' || !fs.existsSync(path.join(options.packageDir, 'tsdown.mcp.config.ts')),\n ).map((name) => `${GENERATED_DIR}/${name}.ts`)\n : [\n `${GENERATED_DIR}/${ENTRY_FILENAME[options.target]}.ts`,\n ...(options.target === 'mcp' ? [`${GENERATED_DIR}/mcp-ui.ts`] : []),\n ];\n const { changed } = writeGenerated(options.packageDir, files, options.check, managed);\n return { graph, packageName, pluginId, files, changed, notices, targets };\n}\n"],"mappings":"8ZAuBA,SAAgB8B,EAAgB,EAA6B,CAC3D,OAAOC,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,QAAS,EAAE,CAClE,CAEA,SAASC,EAAgB,EAA4B,CACnD,IAAMC,EAAW,KAAK,MAAMjC,EAAAA,QAAG,aAAaC,EAAAA,QAAK,KAAKiC,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAOD,EAAS,MAAS,SAAU,MAAU,MAAM,GAAGC,EAAW,0BAA0B,EAC/F,OAAOD,EAAS,IAClB,CAEA,MAAME,EAAqE,CACzE,OAAQjC,EAAAA,kBACR,IAAKC,EAAAA,eACL,OAAQC,EAAAA,kBACR,IAAKC,EAAAA,cACP,EAEM+B,EAAwD9B,EAAAA,0BAU9D,SAAgB+B,EAAkB,EAA0C,CAC1E,IAAMN,EAAcO,EAAQ,aAAeN,EAAgBM,EAAQ,UAAU,EACvEC,EAAWD,EAAQ,UAAYR,EAAgBC,CAAW,EAE1DS,EAAwBjC,EAAAA,eAAe+B,CAAO,EAC9CG,EAA6B,CAAC,GAAGD,EAAM,OAAO,EAC9CE,kBAAQ,IAAI,IACZC,EAAyB,CAAC,EAC1BC,EAAaN,EAAQ,SAAW,MAA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":"index.cjs","names":["fs","path","renderServerEntry","renderWebEntry","renderNativeEntry","renderMcpEntry","GENERATED_ENTRY_FILENAMES","scanExtensions","renderMcpWidgets","GENERATED_DIR","BUILD_TARGET_PLATFORMS","RETIRED_PLATFORM_NOTICE","resolveTarget","renderApiClient","GENERATED_CLIENT_NAME","renderNativeApiClient","GENERATED_NATIVE_CLIENT_NAME","API_ROUTES_MODULE","GENERATED_ENTRY_NAMES","writeGenerated","require_runtime","require_layout","require_index","require_index$1","require_index$2","require_index$3","require_index$4","require_index$5","node_fs","node_path","defaultPluginId","packageName","readPackageName","manifest","packageDir","RENDERERS","ENTRY_FILENAME","generateExtension","options","pluginId","graph","notices","files","targets","mcpWidgets","entry","retired","notice","requestedTargets","target","resolution","render","source","hasRouteTable","hasBrowserHalf","client","hasNativeHalf","nativeClient","managed","name"],"sources":["../../../src/services/generate/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n API_ROUTES_MODULE,\n BUILD_TARGET_PLATFORMS,\n GENERATED_CLIENT_NAME,\n GENERATED_DIR,\n GENERATED_ENTRY_FILENAMES,\n GENERATED_ENTRY_NAMES,\n GENERATED_NATIVE_CLIENT_NAME,\n} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient, renderNativeApiClient } from '../renderClient';\nimport { renderMcpEntry, renderNativeEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { renderMcpWidgets } from '../renderMcpWidgets';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { RETIRED_PLATFORM_NOTICE, scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/po-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^po-/u, '');\n}\n\nfunction readPackageName(packageDir: string): string {\n const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8')) as { name?: unknown };\n if (typeof manifest.name !== 'string') throw new Error(`${packageDir}/package.json has no name`);\n return manifest.name;\n}\n\nconst RENDERERS: Readonly<Record<BuildTarget, typeof renderServerEntry>> = {\n server: renderServerEntry,\n web: renderWebEntry,\n native: renderNativeEntry,\n mcp: renderMcpEntry,\n};\n\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\n\n/**\n * Scans a package and renders every entry its tree calls for.\n *\n * A target with nothing in it produces no file, so a backend-only package\n * never grows an empty cockpit entry. Notices from the scan and from each\n * resolution are gathered rather than thrown: an unrecognised folder costs\n * that folder, never the build.\n */\nexport function generateExtension(options: GenerateOptions): GenerateResult {\n const packageName = options.packageName ?? readPackageName(options.packageDir);\n const pluginId = options.pluginId ?? defaultPluginId(packageName);\n\n const graph: ExtensionGraph = scanExtensions(options);\n const notices: ExtensionNotice[] = [...graph.notices];\n const files = new Map<string, string>();\n const targets: BuildTarget[] = [];\n const mcpWidgets = options.target === 'mcp' ? renderMcpWidgets(graph, packageName, GENERATED_DIR) : undefined;\n if (mcpWidgets?.source !== undefined) files.set(`${GENERATED_DIR}/mcp-ui.ts`, mcpWidgets.source);\n\n // Here rather than in the scan, deliberately. The poRoutedFilePosition lint\n // rule calls scanExtensions() directly, so a scan notice would make `.ios` a\n // hard preflight failure and cost us the forward-looking platforms we kept on\n // purpose. resolveTarget runs once per target, which would repeat it per target.\n for (const entry of graph.entries) {\n if (entry.platform === undefined || BUILD_TARGET_PLATFORMS.includes(entry.platform)) continue;\n notices.push({\n path: entry.file,\n message: `'${entry.platform}' is a forward-looking platform with no build target; this file is not emitted for server, web, native or mcp`,\n });\n }\n\n const retired = graph.notices.filter((notice) => notice.message === RETIRED_PLATFORM_NOTICE);\n if (retired.length > 0) {\n throw new Error(\n `${packageName}: ${RETIRED_PLATFORM_NOTICE}\\n${retired.map((notice) => ` ${notice.path}`).join('\\n')}`,\n );\n }\n\n const requestedTargets = options.target === undefined ? (['server', 'web', 'native'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n if (resolution.contributions.length === 0 && resolution.escapeHatches.length === 0 && resolution.roots.length === 0)\n continue;\n\n targets.push(target);\n const render = RENDERERS[target];\n const source = render(resolution, {\n packageName,\n pluginId,\n root: graph.root,\n entryDir: GENERATED_DIR,\n mcpWidgets: mcpWidgets?.declarations,\n });\n files.set(`${GENERATED_DIR}/${ENTRY_FILENAME[target]}.ts`, source);\n }\n\n // Not another build target: no host loads it as an entry, and adding one to\n // the target loop would mean a resolution pass and a contribution field for\n // something that is only ever imported by a routed frontend file.\n //\n // Only for a package that has a browser half. The client exists to be called\n // from a page and it carries the sealed transport, so emitting one into a\n // node-only package asks that package to depend on a browser runtime it never\n // loads, to satisfy a file nothing imports.\n const hasRouteTable = options.target === undefined && fs.existsSync(path.join(options.packageDir, API_ROUTES_MODULE));\n const hasBrowserHalf = targets.includes('web');\n const client =\n hasRouteTable && hasBrowserHalf\n ? renderApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (client !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_CLIENT_NAME}.ts`, client);\n\n // The native half gets its own file rather than a shared one, because the\n // browser client's two imports are exactly what the native host refuses.\n const hasNativeHalf = targets.includes('native');\n const nativeClient =\n hasRouteTable && hasNativeHalf\n ? renderNativeApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (nativeClient !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_NATIVE_CLIENT_NAME}.ts`, nativeClient);\n if (hasRouteTable && (hasBrowserHalf || hasNativeHalf) && client === undefined && nativeClient === undefined) {\n notices.push({\n path: API_ROUTES_MODULE,\n message: 'declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted',\n });\n }\n\n const managed =\n options.target === undefined\n ? GENERATED_ENTRY_NAMES.filter(\n (name) => name !== 'mcp' || !fs.existsSync(path.join(options.packageDir, 'tsdown.mcp.config.ts')),\n ).map((name) => `${GENERATED_DIR}/${name}.ts`)\n : [\n `${GENERATED_DIR}/${ENTRY_FILENAME[options.target]}.ts`,\n ...(options.target === 'mcp' ? [`${GENERATED_DIR}/mcp-ui.ts`] : []),\n ];\n const { changed } = writeGenerated(options.packageDir, files, options.check, managed);\n return { graph, packageName, pluginId, files, changed, notices, targets };\n}\n"],"mappings":"8ZAuBA,SAAgB8B,EAAgB,EAA6B,CAC3D,OAAOC,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,QAAS,EAAE,CAClE,CAEA,SAASC,EAAgB,EAA4B,CACnD,IAAMC,EAAW,KAAK,MAAMjC,EAAAA,QAAG,aAAaC,EAAAA,QAAK,KAAKiC,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAOD,EAAS,MAAS,SAAU,MAAU,MAAM,GAAGC,EAAW,0BAA0B,EAC/F,OAAOD,EAAS,IAClB,CAEA,MAAME,EAAqE,CACzE,OAAQjC,EAAAA,kBACR,IAAKC,EAAAA,eACL,OAAQC,EAAAA,kBACR,IAAKC,EAAAA,cACP,EAEM+B,EAAwD9B,EAAAA,0BAU9D,SAAgB+B,EAAkB,EAA0C,CAC1E,IAAMN,EAAcO,EAAQ,aAAeN,EAAgBM,EAAQ,UAAU,EACvEC,EAAWD,EAAQ,UAAYR,EAAgBC,CAAW,EAE1DS,EAAwBjC,EAAAA,eAAe+B,CAAO,EAC9CG,EAA6B,CAAC,GAAGD,EAAM,OAAO,EAC9CE,kBAAQ,IAAI,IACZC,EAAyB,CAAC,EAC1BC,EAAaN,EAAQ,SAAW,MAAQ9B,EAAAA,iBAAiBgC,EAAOT,EAAatB,EAAAA,aAAa,EAAI,IAAA,GAChGmC,GAAY,SAAW,IAAA,IAAWF,EAAM,IAAI,GAAGjC,EAAAA,cAAc,YAAamC,EAAW,MAAM,EAM/F,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c,CAAC,EAC3F,IAAA,GACF8C,IAAW,IAAA,IAAWb,EAAM,IAAI,GAAGjC,EAAAA,cAAc,GAAGK,EAAAA,sBAAsB,KAAMyC,CAAM,EAI1F,IAAMC,EAAgBb,EAAQ,SAAS,QAAQ,EACzCc,EACJJ,GAAiBG,EACbzC,EAAAA,sBAAsByB,EAAO,CAAE,cAAa,WAAU,KAAMA,EAAM,KAAM,SAAU/B,EAAAA,aAAc,CAAC,EACjG,IAAA,GACFgD,IAAiB,IAAA,IAAWf,EAAM,IAAI,GAAGjC,EAAAA,cAAc,GAAGO,EAAAA,6BAA6B,KAAMyC,CAAY,EACzGJ,IAAkBC,GAAkBE,IAAkBD,IAAW,IAAA,IAAaE,IAAiB,IAAA,IACjGhB,EAAQ,KAAK,CACX,KAAMxB,EAAAA,kBACN,QAAS,2FACX,CAAC,EAGH,IAAMyC,EACJpB,EAAQ,SAAW,IAAA,GACfpB,EAAAA,sBAAsB,OACnB,GAASyC,IAAS,OAAS,CAAC3D,EAAAA,QAAG,WAAWC,EAAAA,QAAK,KAAKqC,EAAQ,WAAY,sBAAsB,CAAC,CAClG,CAAC,CAAC,IAAK,GAAS,GAAG7B,EAAAA,cAAc,GAAGkD,EAAK,IAAI,EAC7C,CACE,GAAGlD,EAAAA,cAAc,GAAG2B,EAAeE,EAAQ,QAAQ,KACnD,GAAIA,EAAQ,SAAW,MAAQ,CAAC,GAAG7B,EAAAA,cAAc,WAAW,EAAI,CAAC,CACnE,EACA,CAAE,WAAYU,EAAAA,eAAemB,EAAQ,WAAYI,EAAOJ,EAAQ,MAAOoB,CAAO,EACpF,MAAO,CAAE,QAAO,cAAa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["fs","path","defaultPluginId","packageName","readPackageName","manifest","packageDir","RENDERERS","renderServerEntry","renderWebEntry","renderNativeEntry","renderMcpEntry","ENTRY_FILENAME","GENERATED_ENTRY_FILENAMES","generateExtension","options","pluginId","graph","scanExtensions","notices","files","targets","mcpWidgets","renderMcpWidgets","GENERATED_DIR","entry","BUILD_TARGET_PLATFORMS","retired","notice","RETIRED_PLATFORM_NOTICE","requestedTargets","target","resolution","resolveTarget","render","source","hasRouteTable","hasBrowserHalf","client","renderApiClient","GENERATED_CLIENT_NAME","hasNativeHalf","nativeClient","renderNativeApiClient","GENERATED_NATIVE_CLIENT_NAME","API_ROUTES_MODULE","managed","GENERATED_ENTRY_NAMES","name","writeGenerated"],"sources":["../../../src/services/generate/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n API_ROUTES_MODULE,\n BUILD_TARGET_PLATFORMS,\n GENERATED_CLIENT_NAME,\n GENERATED_DIR,\n GENERATED_ENTRY_FILENAMES,\n GENERATED_ENTRY_NAMES,\n GENERATED_NATIVE_CLIENT_NAME,\n} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient, renderNativeApiClient } from '../renderClient';\nimport { renderMcpEntry, renderNativeEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { renderMcpWidgets } from '../renderMcpWidgets';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { RETIRED_PLATFORM_NOTICE, scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/po-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^po-/u, '');\n}\n\nfunction readPackageName(packageDir: string): string {\n const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8')) as { name?: unknown };\n if (typeof manifest.name !== 'string') throw new Error(`${packageDir}/package.json has no name`);\n return manifest.name;\n}\n\nconst RENDERERS: Readonly<Record<BuildTarget, typeof renderServerEntry>> = {\n server: renderServerEntry,\n web: renderWebEntry,\n native: renderNativeEntry,\n mcp: renderMcpEntry,\n};\n\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\n\n/**\n * Scans a package and renders every entry its tree calls for.\n *\n * A target with nothing in it produces no file, so a backend-only package\n * never grows an empty cockpit entry. Notices from the scan and from each\n * resolution are gathered rather than thrown: an unrecognised folder costs\n * that folder, never the build.\n */\nexport function generateExtension(options: GenerateOptions): GenerateResult {\n const packageName = options.packageName ?? readPackageName(options.packageDir);\n const pluginId = options.pluginId ?? defaultPluginId(packageName);\n\n const graph: ExtensionGraph = scanExtensions(options);\n const notices: ExtensionNotice[] = [...graph.notices];\n const files = new Map<string, string>();\n const targets: BuildTarget[] = [];\n const mcpWidgets = options.target === 'mcp' ? renderMcpWidgets(graph, packageName, GENERATED_DIR) : undefined;\n if (mcpWidgets?.source !== undefined) files.set(`${GENERATED_DIR}/mcp-ui.ts`, mcpWidgets.source);\n\n // Here rather than in the scan, deliberately. The doomRoutedFilePosition lint\n // rule calls scanExtensions() directly, so a scan notice would make `.ios` a\n // hard preflight failure and cost us the forward-looking platforms we kept on\n // purpose. resolveTarget runs once per target, which would repeat it per target.\n for (const entry of graph.entries) {\n if (entry.platform === undefined || BUILD_TARGET_PLATFORMS.includes(entry.platform)) continue;\n notices.push({\n path: entry.file,\n message: `'${entry.platform}' is a forward-looking platform with no build target; this file is not emitted for server, web, native or mcp`,\n });\n }\n\n const retired = graph.notices.filter((notice) => notice.message === RETIRED_PLATFORM_NOTICE);\n if (retired.length > 0) {\n throw new Error(\n `${packageName}: ${RETIRED_PLATFORM_NOTICE}\\n${retired.map((notice) => ` ${notice.path}`).join('\\n')}`,\n );\n }\n\n const requestedTargets = options.target === undefined ? (['server', 'web', 'native'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n if (resolution.contributions.length === 0 && resolution.escapeHatches.length === 0 && resolution.roots.length === 0)\n continue;\n\n targets.push(target);\n const render = RENDERERS[target];\n const source = render(resolution, {\n packageName,\n pluginId,\n root: graph.root,\n entryDir: GENERATED_DIR,\n mcpWidgets: mcpWidgets?.declarations,\n });\n files.set(`${GENERATED_DIR}/${ENTRY_FILENAME[target]}.ts`, source);\n }\n\n // Not another build target: no host loads it as an entry, and adding one to\n // the target loop would mean a resolution pass and a contribution field for\n // something that is only ever imported by a routed frontend file.\n //\n // Only for a package that has a browser half. The client exists to be called\n // from a page and it carries the sealed transport, so emitting one into a\n // node-only package asks that package to depend on a browser runtime it never\n // loads, to satisfy a file nothing imports.\n const hasRouteTable = options.target === undefined && fs.existsSync(path.join(options.packageDir, API_ROUTES_MODULE));\n const hasBrowserHalf = targets.includes('web');\n const client =\n hasRouteTable && hasBrowserHalf\n ? renderApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (client !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_CLIENT_NAME}.ts`, client);\n\n // The native half gets its own file rather than a shared one, because the\n // browser client's two imports are exactly what the native host refuses.\n const hasNativeHalf = targets.includes('native');\n const nativeClient =\n hasRouteTable && hasNativeHalf\n ? renderNativeApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (nativeClient !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_NATIVE_CLIENT_NAME}.ts`, nativeClient);\n if (hasRouteTable && (hasBrowserHalf || hasNativeHalf) && client === undefined && nativeClient === undefined) {\n notices.push({\n path: API_ROUTES_MODULE,\n message: 'declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted',\n });\n }\n\n const managed =\n options.target === undefined\n ? GENERATED_ENTRY_NAMES.filter(\n (name) => name !== 'mcp' || !fs.existsSync(path.join(options.packageDir, 'tsdown.mcp.config.ts')),\n ).map((name) => `${GENERATED_DIR}/${name}.ts`)\n : [\n `${GENERATED_DIR}/${ENTRY_FILENAME[options.target]}.ts`,\n ...(options.target === 'mcp' ? [`${GENERATED_DIR}/mcp-ui.ts`] : []),\n ];\n const { changed } = writeGenerated(options.packageDir, files, options.check, managed);\n return { graph, packageName, pluginId, files, changed, notices, targets };\n}\n"],"mappings":"ivBAuBA,SAAgBE,EAAgB,EAA6B,CAC3D,OAAOC,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,QAAS,EAAE,CAClE,CAEA,SAASC,EAAgB,EAA4B,CACnD,IAAMC,EAAW,KAAK,MAAML,EAAG,aAAaC,EAAK,KAAKK,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAOD,EAAS,MAAS,SAAU,MAAU,MAAM,GAAGC,EAAW,0BAA0B,EAC/F,OAAOD,EAAS,IAClB,CAEA,MAAME,EAAqE,CACzE,OAAQC,EACR,IAAKC,EACL,OAAQC,EACR,IAAKC,CACP,EAEMC,EAAwDC,EAU9D,SAAgBC,EAAkB,EAA0C,CAC1E,IAAMX,EAAcY,EAAQ,aAAeX,EAAgBW,EAAQ,UAAU,EACvEC,EAAWD,EAAQ,UAAYb,EAAgBC,CAAW,EAE1Dc,EAAwBC,EAAeH,CAAO,EAC9CI,EAA6B,CAAC,GAAGF,EAAM,OAAO,EAC9CG,kBAAQ,IAAI,IACZC,EAAyB,CAAC,EAC1BC,EAAaP,EAAQ,SAAW,MAAQQ,EAAiBN,EAAOd,EAAaqB,CAAa,EAAI,IAAA,GAChGF,GAAY,SAAW,IAAA,IAAWF,EAAM,IAAI,GAAGI,EAAc,YAAaF,EAAW,MAAM,EAM/F,IAAK,IAAMG,KAASR,EAAM,QACpBQ,EAAM,WAAa,IAAA,IAAaC,EAAuB,SAASD,EAAM,QAAQ,GAClFN,EAAQ,KAAK,CACX,KAAMM,EAAM,KACZ,QAAS,IAAIA,EAAM,SAAS,8GAC9B,CAAC,EAGH,IAAME,EAAUV,EAAM,QAAQ,OAAQ,GAAWW,EAAO,UAAYC,CAAuB,EAC3F,GAAIF,EAAQ,OAAS,EACnB,MAAU,MACR,GAAGxB,EAAY,IAAI0B,EA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A,IAAaI,IAAiB,IAAA,IACjGvB,EAAQ,KAAK,CACX,KAAM0B,EACN,QAAS,2FACX,CAAC,EAGH,IAAMC,EACJ/B,EAAQ,SAAW,IAAA,GACfgC,EAAsB,OACnB,GAASC,IAAS,OAAS,CAAChD,EAAG,WAAWC,EAAK,KAAKc,EAAQ,WAAY,sBAAsB,CAAC,CAClG,CAAC,CAAC,IAAK,GAAS,GAAGS,EAAc,GAAGwB,EAAK,IAAI,EAC7C,CACE,GAAGxB,EAAc,GAAGZ,EAAeG,EAAQ,QAAQ,KACnD,GAAIA,EAAQ,SAAW,MAAQ,CAAC,GAAGS,EAAc,WAAW,EAAI,CAAC,CACnE,EACA,CAAE,WAAYyB,EAAelC,EAAQ,WAAYK,EAAOL,EAAQ,MAAO+B,CAAO,EACpF,MAAO,CAAE,QAAO,cAAa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
1
+ {"version":3,"file":"index.mjs","names":["fs","path","defaultPluginId","packageName","readPackageName","manifest","packageDir","RENDERERS","renderServerEntry","renderWebEntry","renderNativeEntry","renderMcpEntry","ENTRY_FILENAME","GENERATED_ENTRY_FILENAMES","generateExtension","options","pluginId","graph","scanExtensions","notices","files","targets","mcpWidgets","renderMcpWidgets","GENERATED_DIR","entry","BUILD_TARGET_PLATFORMS","retired","notice","RETIRED_PLATFORM_NOTICE","requestedTargets","target","resolution","resolveTarget","render","source","hasRouteTable","hasBrowserHalf","client","renderApiClient","GENERATED_CLIENT_NAME","hasNativeHalf","nativeClient","renderNativeApiClient","GENERATED_NATIVE_CLIENT_NAME","API_ROUTES_MODULE","managed","GENERATED_ENTRY_NAMES","name","writeGenerated"],"sources":["../../../src/services/generate/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n API_ROUTES_MODULE,\n BUILD_TARGET_PLATFORMS,\n GENERATED_CLIENT_NAME,\n GENERATED_DIR,\n GENERATED_ENTRY_FILENAMES,\n GENERATED_ENTRY_NAMES,\n GENERATED_NATIVE_CLIENT_NAME,\n} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient, renderNativeApiClient } from '../renderClient';\nimport { renderMcpEntry, renderNativeEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { renderMcpWidgets } from '../renderMcpWidgets';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { RETIRED_PLATFORM_NOTICE, scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/po-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^po-/u, '');\n}\n\nfunction readPackageName(packageDir: string): string {\n const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8')) as { name?: unknown };\n if (typeof manifest.name !== 'string') throw new Error(`${packageDir}/package.json has no name`);\n return manifest.name;\n}\n\nconst RENDERERS: Readonly<Record<BuildTarget, typeof renderServerEntry>> = {\n server: renderServerEntry,\n web: renderWebEntry,\n native: renderNativeEntry,\n mcp: renderMcpEntry,\n};\n\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\n\n/**\n * Scans a package and renders every entry its tree calls for.\n *\n * A target with nothing in it produces no file, so a backend-only package\n * never grows an empty cockpit entry. Notices from the scan and from each\n * resolution are gathered rather than thrown: an unrecognised folder costs\n * that folder, never the build.\n */\nexport function generateExtension(options: GenerateOptions): GenerateResult {\n const packageName = options.packageName ?? readPackageName(options.packageDir);\n const pluginId = options.pluginId ?? defaultPluginId(packageName);\n\n const graph: ExtensionGraph = scanExtensions(options);\n const notices: ExtensionNotice[] = [...graph.notices];\n const files = new Map<string, string>();\n const targets: BuildTarget[] = [];\n const mcpWidgets = options.target === 'mcp' ? renderMcpWidgets(graph, packageName, GENERATED_DIR) : undefined;\n if (mcpWidgets?.source !== undefined) files.set(`${GENERATED_DIR}/mcp-ui.ts`, mcpWidgets.source);\n\n // Here rather than in the scan, deliberately. The poRoutedFilePosition lint\n // rule calls scanExtensions() directly, so a scan notice would make `.ios` a\n // hard preflight failure and cost us the forward-looking platforms we kept on\n // purpose. resolveTarget runs once per target, which would repeat it per target.\n for (const entry of graph.entries) {\n if (entry.platform === undefined || BUILD_TARGET_PLATFORMS.includes(entry.platform)) continue;\n notices.push({\n path: entry.file,\n message: `'${entry.platform}' is a forward-looking platform with no build target; this file is not emitted for server, web, native or mcp`,\n });\n }\n\n const retired = graph.notices.filter((notice) => notice.message === RETIRED_PLATFORM_NOTICE);\n if (retired.length > 0) {\n throw new Error(\n `${packageName}: ${RETIRED_PLATFORM_NOTICE}\\n${retired.map((notice) => ` ${notice.path}`).join('\\n')}`,\n );\n }\n\n const requestedTargets = options.target === undefined ? (['server', 'web', 'native'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n if (resolution.contributions.length === 0 && resolution.escapeHatches.length === 0 && resolution.roots.length === 0)\n continue;\n\n targets.push(target);\n const render = RENDERERS[target];\n const source = render(resolution, {\n packageName,\n pluginId,\n root: graph.root,\n entryDir: GENERATED_DIR,\n mcpWidgets: mcpWidgets?.declarations,\n });\n files.set(`${GENERATED_DIR}/${ENTRY_FILENAME[target]}.ts`, source);\n }\n\n // Not another build target: no host loads it as an entry, and adding one to\n // the target loop would mean a resolution pass and a contribution field for\n // something that is only ever imported by a routed frontend file.\n //\n // Only for a package that has a browser half. The client exists to be called\n // from a page and it carries the sealed transport, so emitting one into a\n // node-only package asks that package to depend on a browser runtime it never\n // loads, to satisfy a file nothing imports.\n const hasRouteTable = options.target === undefined && fs.existsSync(path.join(options.packageDir, API_ROUTES_MODULE));\n const hasBrowserHalf = targets.includes('web');\n const client =\n hasRouteTable && hasBrowserHalf\n ? renderApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (client !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_CLIENT_NAME}.ts`, client);\n\n // The native half gets its own file rather than a shared one, because the\n // browser client's two imports are exactly what the native host refuses.\n const hasNativeHalf = targets.includes('native');\n const nativeClient =\n hasRouteTable && hasNativeHalf\n ? renderNativeApiClient(graph, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR })\n : undefined;\n if (nativeClient !== undefined) files.set(`${GENERATED_DIR}/${GENERATED_NATIVE_CLIENT_NAME}.ts`, nativeClient);\n if (hasRouteTable && (hasBrowserHalf || hasNativeHalf) && client === undefined && nativeClient === undefined) {\n notices.push({\n path: API_ROUTES_MODULE,\n message: 'declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted',\n });\n }\n\n const managed =\n options.target === undefined\n ? GENERATED_ENTRY_NAMES.filter(\n (name) => name !== 'mcp' || !fs.existsSync(path.join(options.packageDir, 'tsdown.mcp.config.ts')),\n ).map((name) => `${GENERATED_DIR}/${name}.ts`)\n : [\n `${GENERATED_DIR}/${ENTRY_FILENAME[options.target]}.ts`,\n ...(options.target === 'mcp' ? [`${GENERATED_DIR}/mcp-ui.ts`] : []),\n ];\n const { changed } = writeGenerated(options.packageDir, files, options.check, managed);\n return { graph, packageName, pluginId, files, changed, notices, targets };\n}\n"],"mappings":"ivBAuBA,SAAgBE,EAAgB,EAA6B,CAC3D,OAAOC,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,QAAS,EAAE,CAClE,CAEA,SAASC,EAAgB,EAA4B,CACnD,IAAMC,EAAW,KAAK,MAAML,EAAG,aAAaC,EAAK,KAAKK,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAOD,EAAS,MAAS,SAAU,MAAU,MAAM,GAAGC,EAAW,0BAA0B,EAC/F,OAAOD,EAAS,IAClB,CAEA,MAAME,EAAqE,CACzE,OAAQC,EACR,IAAKC,EACL,OAAQC,EACR,IAAKC,CACP,EAEMC,EAAwDC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Aa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["toKebab","posix","require_index","node_path","SCOPE_ORDER","identifierFor","multiple","camel","basePath","word","index","baseSegmentOf","first","entry","mountsOf","scopesByBase","graph","held","bases","declared","shallowest","scope","routesSpecifier","relative","entryDir","BROWSER_CLIENT","NATIVE_CLIENT","renderMount","scopes","mount","suffix","flavor","renderClient","mounts","options","renderApiClient","renderNativeApiClient"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `DoomApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\n/** What differs between the browser and native clients: where the runtime comes from, and how a call leaves. */\ninterface ClientFlavor {\n readonly imports: readonly string[];\n readonly transport: string;\n}\n\nconst BROWSER_CLIENT: ClientFlavor = {\n imports: [\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/po-web-security/browser';\",\n ],\n transport: '(input, init) => sealedTransport.fetch(input, init)',\n};\n\n/**\n * Only `@agimon-ai/po-core/native`, the one Po module on the native host list.\n * The phone's sealed channel and step-up live in the app shell, which binds\n * them behind `nativeApiTransport`.\n */\nconst NATIVE_CLIENT: ClientFlavor = {\n imports: [\"import { createApiClient, nativeApiTransport, sessionApiAddress } from '@agimon-ai/po-core/native';\"],\n transport: 'nativeApiTransport',\n};\n\nfunction renderMount(mount: ClientMount, flavor: ClientFlavor): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ` transport: ${flavor.transport},`,\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\nfunction renderClient(graph: ExtensionGraph, options: RenderOptions, flavor: ClientFlavor): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n ...flavor.imports,\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount, flavor)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, BROWSER_CLIENT);\n}\n\n/**\n * The same mounts and the same route table for a `.native` file.\n *\n * The route table is imported, never restated, so it must itself import only\n * what the native host provides: a table that imports `@agimon-ai/po-core/web`\n * is refused by the native composition build, which is the intended failure.\n */\nexport function renderNativeApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, NATIVE_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node_path","SCOPE_ORDER","identifierFor","multiple","camel","basePath","word","index","baseSegmentOf","first","entry","mountsOf","scopesByBase","graph","held","bases","declared","shallowest","scope","routesSpecifier","relative","entryDir","BROWSER_CLIENT","NATIVE_CLIENT","renderMount","scopes","mount","suffix","flavor","renderClient","mounts","options","renderApiClient","renderNativeApiClient"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `PoApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\n/** What differs between the browser and native clients: where the runtime comes from, and how a call leaves. */\ninterface ClientFlavor {\n readonly imports: readonly string[];\n readonly transport: string;\n}\n\nconst BROWSER_CLIENT: ClientFlavor = {\n imports: [\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/po-web-security/browser';\",\n ],\n transport: '(input, init) => sealedTransport.fetch(input, init)',\n};\n\n/**\n * Only `@agimon-ai/po-core/native`, the one Po module on the native host list.\n * The phone's sealed channel and step-up live in the app shell, which binds\n * them behind `nativeApiTransport`.\n */\nconst NATIVE_CLIENT: ClientFlavor = {\n imports: [\"import { createApiClient, nativeApiTransport, sessionApiAddress } from '@agimon-ai/po-core/native';\"],\n transport: 'nativeApiTransport',\n};\n\nfunction renderMount(mount: ClientMount, flavor: ClientFlavor): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ` transport: ${flavor.transport},`,\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\nfunction renderClient(graph: ExtensionGraph, options: RenderOptions, flavor: ClientFlavor): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n ...flavor.imports,\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount, flavor)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, BROWSER_CLIENT);\n}\n\n/**\n * The same mounts and the same route table for a `.native` file.\n *\n * The route table is imported, never restated, so it must itself import only\n * what the native host provides: a table that imports `@agimon-ai/po-core/web`\n * is refused by the native composition build, which is the intended failure.\n */\nexport function renderNativeApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, NATIVE_CLIENT);\n}\n"],"mappings":"0GAsBA,MAGMI,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAASC,EAAc,EAAkB,EAA2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,WAAW,GAAG,EAAIA,EAAW,KAAKA,GACpD,CAQA,MAAME,EAA+B,CACnC,QAAS,CACP,+EACA,uEACF,EACA,UAAW,qDACb,EAOMC,EAA8B,CAClC,QAAS,CAAC,qGAAqG,EAC/G,UAAW,oBACb,EAEA,SAASC,EAAY,EAAoB,EAAgC,CACvE,IAAMC,EAASC,EAAM,OAAO,IAAK,GAAU,IAAIR,EAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAC5DS,EAASD,EAAM,aAAe,MAAQ,GAAK,YAAYA,EAAM,SAAS,QAC5E,MAAO,CACL,+BAA+BA,EAAM,SAAS,MAAMC,EAAO,MAC3D,gBAAgBD,EAAM,WAAW,YAAYD,EAAO,aACpD,GACA,gBAAgBC,EAAM,WAAW,8BACjC,aAAaA,EAAM,WAAW,SAC9B,gBAAgBA,EAAM,SAAS,IAC/B,gBAAgBE,EAAO,UAAU,GACjC,uCACA,MACA,EACF,CACF,CAEA,SAASC,EAAa,EAAuB,EAAwB,EAA0C,CAC7G,IAAMC,EAASnB,EAASE,CAAK,EAC7B,GAAIiB,EAAO,SAAW,EAUtB,MAAO,GAAG,CAPR,4DACA,GAAGF,EAAO,QACV,GACA,uBAAuBT,EAAgBY,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAGD,EAAO,QAAS,GAAUN,EAAYE,EAAOE,CAAM,CAAC,CAE3C,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD,CAQA,SAAgBI,EAAgB,EAAuB,EAA4C,CACjG,OAAOH,EAAahB,EAAOkB,EAAST,CAAc,CACpD,CASA,SAAgBW,EAAsB,EAAuB,EAA4C,CACvG,OAAOJ,EAAahB,EAAOkB,EAASR,CAAa,CACnD"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["SCOPE_ORDER","identifierFor","multiple","camel","toKebab","basePath","word","index","baseSegmentOf","first","entry","mountsOf","scopesByBase","graph","held","bases","declared","shallowest","scope","routesSpecifier","relative","posix","entryDir","BROWSER_CLIENT","NATIVE_CLIENT","renderMount","scopes","mount","suffix","flavor","renderClient","mounts","options","renderApiClient","renderNativeApiClient"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `DoomApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\n/** What differs between the browser and native clients: where the runtime comes from, and how a call leaves. */\ninterface ClientFlavor {\n readonly imports: readonly string[];\n readonly transport: string;\n}\n\nconst BROWSER_CLIENT: ClientFlavor = {\n imports: [\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/po-web-security/browser';\",\n ],\n transport: '(input, init) => sealedTransport.fetch(input, init)',\n};\n\n/**\n * Only `@agimon-ai/po-core/native`, the one Po module on the native host list.\n * The phone's sealed channel and step-up live in the app shell, which binds\n * them behind `nativeApiTransport`.\n */\nconst NATIVE_CLIENT: ClientFlavor = {\n imports: [\"import { createApiClient, nativeApiTransport, sessionApiAddress } from '@agimon-ai/po-core/native';\"],\n transport: 'nativeApiTransport',\n};\n\nfunction renderMount(mount: ClientMount, flavor: ClientFlavor): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ` transport: ${flavor.transport},`,\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\nfunction renderClient(graph: ExtensionGraph, options: RenderOptions, flavor: ClientFlavor): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n ...flavor.imports,\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount, flavor)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, BROWSER_CLIENT);\n}\n\n/**\n * The same mounts and the same route table for a `.native` file.\n *\n * The route table is imported, never restated, so it must itself import only\n * what the native host provides: a table that imports `@agimon-ai/po-core/web`\n * is refused by the native composition build, which is the intended failure.\n */\nexport function renderNativeApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, NATIVE_CLIENT);\n}\n"],"mappings":"qHAsBA,MAGMA,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAASC,EAAc,EAAkB,EAA2B,CAClE,GAAI,CAACC,EAAU,MAAO,MACtB,IAAMC,EAAQC,EAAQC,CAAQ,CAAC,CAC5B,MAAM,GAAG,CAA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,EAA8B,CAClC,QAAS,CAAC,qGAAqG,EAC/G,UAAW,oBACb,EAEA,SAASC,EAAY,EAAoB,EAAgC,CACvE,IAAMC,EAASC,EAAM,OAAO,IAAK,GAAU,IAAIT,EAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAC5DU,EAASD,EAAM,aAAe,MAAQ,GAAK,YAAYA,EAAM,SAAS,QAC5E,MAAO,CACL,+BAA+BA,EAAM,SAAS,MAAMC,EAAO,MAC3D,gBAAgBD,EAAM,WAAW,YAAYD,EAAO,aACpD,GACA,gBAAgBC,EAAM,WAAW,8BACjC,aAAaA,EAAM,WAAW,SAC9B,gBAAgBA,EAAM,SAAS,IAC/B,gBAAgBE,EAAO,UAAU,GACjC,uCACA,MACA,EACF,CACF,CAEA,SAASC,EAAa,EAAuB,EAAwB,EAA0C,CAC7G,IAAMC,EAASpB,EAASE,CAAK,EAC7B,GAAIkB,EAAO,SAAW,EAUtB,MAAO,GAAG,CAPR,4DACA,GAAGF,EAAO,QACV,GACA,uBAAuBV,EAAgBa,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAGD,EAAO,QAAS,GAAUN,EAAYE,EAAOE,CAAM,CAAC,CAE3C,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD,CAQA,SAAgBI,EAAgB,EAAuB,EAA4C,CACjG,OAAOH,EAAajB,EAAOmB,EAAST,CAAc,CACpD,CASA,SAAgBW,EAAsB,EAAuB,EAA4C,CACvG,OAAOJ,EAAajB,EAAOmB,EAASR,CAAa,CACnD"}
1
+ {"version":3,"file":"index.mjs","names":["SCOPE_ORDER","identifierFor","multiple","camel","toKebab","basePath","word","index","baseSegmentOf","first","entry","mountsOf","scopesByBase","graph","held","bases","declared","shallowest","scope","routesSpecifier","relative","posix","entryDir","BROWSER_CLIENT","NATIVE_CLIENT","renderMount","scopes","mount","suffix","flavor","renderClient","mounts","options","renderApiClient","renderNativeApiClient"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `PoApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\n/** What differs between the browser and native clients: where the runtime comes from, and how a call leaves. */\ninterface ClientFlavor {\n readonly imports: readonly string[];\n readonly transport: string;\n}\n\nconst BROWSER_CLIENT: ClientFlavor = {\n imports: [\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/po-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/po-web-security/browser';\",\n ],\n transport: '(input, init) => sealedTransport.fetch(input, init)',\n};\n\n/**\n * Only `@agimon-ai/po-core/native`, the one Po module on the native host list.\n * The phone's sealed channel and step-up live in the app shell, which binds\n * them behind `nativeApiTransport`.\n */\nconst NATIVE_CLIENT: ClientFlavor = {\n imports: [\"import { createApiClient, nativeApiTransport, sessionApiAddress } from '@agimon-ai/po-core/native';\"],\n transport: 'nativeApiTransport',\n};\n\nfunction renderMount(mount: ClientMount, flavor: ClientFlavor): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ` transport: ${flavor.transport},`,\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\nfunction renderClient(graph: ExtensionGraph, options: RenderOptions, flavor: ClientFlavor): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n ...flavor.imports,\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount, flavor)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, BROWSER_CLIENT);\n}\n\n/**\n * The same mounts and the same route table for a `.native` file.\n *\n * The route table is imported, never restated, so it must itself import only\n * what the native host provides: a table that imports `@agimon-ai/po-core/web`\n * is refused by the native composition build, which is the intended failure.\n */\nexport function renderNativeApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n return renderClient(graph, options, NATIVE_CLIENT);\n}\n"],"mappings":"qHAsBA,MAGMA,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAASC,EAAc,EAAkB,EAA2B,CAClE,GAAI,CAACC,EAAU,MAAO,MACtB,IAAMC,EAAQC,EAAQC,CAAQ,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,OAAQ,GAASC,EAAK,OAAS,CAAC,CAAC,CACjC,KAAK,EAAM,IAAWC,IAAU,EAAID,EAAOA,EAAK,EAAE,EAAE,YAAY,EAAIA,EAAK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AAU,IAAIT,EAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAC5DU,EAASD,EAAM,aAAe,MAAQ,GAAK,YAAYA,EAAM,SAAS,QAC5E,MAAO,CACL,+BAA+BA,EAAM,SAAS,MAAMC,EAAO,MAC3D,gBAAgBD,EAAM,WAAW,YAAYD,EAAO,aACpD,GACA,gBAAgBC,EAAM,WAAW,8BACjC,aAAaA,EAAM,WAAW,SAC9B,gBAAgBA,EAAM,SAAS,IAC/B,gBAAgBE,EAAO,UAAU,GACjC,uCACA,MACA,EACF,CACF,CAEA,SAASC,EAAa,EAAuB,EAAwB,EAA0C,CAC7G,IAAMC,EAASpB,EAASE,CAAK,EAC7B,GAAIkB,EAAO,SAAW,EAUtB,MAAO,GAAG,CAPR,4DACA,GAAGF,EAAO,QACV,GACA,uBAAuBV,EAAgBa,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAGD,EAAO,QAAS,GAAUN,EAAYE,EAAOE,CAAM,CAAC,CAE3C,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD,CAQA,SAAgBI,EAAgB,EAAuB,EAA4C,CACjG,OAAOH,EAAajB,EAAOmB,EAAST,CAAc,CACpD,CASA,SAAgBW,EAAsB,EAAuB,EAA4C,CACvG,OAAOJ,EAAajB,EAAOmB,EAASR,CAAa,CACnD"}
@@ -1,7 +1,7 @@
1
- const e=require("../resolveTarget/index.cjs"),t=require("../identity/index.cjs");let n=require("node:path");const r=`// Generated by @agimon-ai/po-build. Do not edit by hand.`,i=[`fileLinks`,`repositorySettingsPanel`,`start`],a={server:[`channels`],web:[],native:[],mcp:[]},o=[`services`],s=[`global`,`workspace`,`session`],c={server:`DoomServerSessionPlugin`,web:`WebPluginContributions`,native:`WebPluginContributions`,mcp:`DoomMcpSessionPlugin`};function l(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
1
+ const e=require("../resolveTarget/index.cjs"),t=require("../identity/index.cjs");let n=require("node:path");const r=`// Generated by @agimon-ai/po-build. Do not edit by hand.`,i=[`fileLinks`,`repositorySettingsPanel`,`start`],a={server:[`channels`],web:[],native:[],mcp:[]},o=[`services`],s=[`global`,`workspace`,`session`],c={server:`PoServerSessionPlugin`,web:`WebPluginContributions`,native:`WebPluginContributions`,mcp:`PoMcpSessionPlugin`};function l(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
2
2
  `)}function u(){return[`type ManyFactory<T, C> = (context: C) => T | readonly T[];`,`const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {`,` const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;`,` return Array.isArray(resolved) ? resolved : [resolved as T];`,`};`].join(`
3
3
  `)}function d(){return[`/* v8 ignore next -- generated normalization branch */`,`const defined = <T>(values: readonly (T | undefined)[]): T[] =>`,` values.filter((value): value is T => value !== undefined);`].join(`
4
4
  `)}const f=[`const via = <T>(identity: Record<string, unknown>, value: unknown): T =>`,` (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;`].join(`
5
- `);function p(e,n){return n===void 0?{id:t.toKebab(e)}:{slot:n,id:t.toKebab(e)}}const m={tool:e=>({name:t.toSnake(e)}),command:e=>({name:t.toKebab(e)}),channel:e=>({frameType:t.toSnake(e)}),hook:e=>({event:t.toSnake(e)}),mode:e=>({name:t.toKebab(e)})},h={tool:e=>({tools:[t.toSnake(e)]}),channel:e=>({channel:t.toSnake(e)}),slot:(e,n)=>({slot:`${n.pluginId}.${t.toKebab(e)}`}),command:e=>({id:t.toKebab(e)}),tab:e=>({id:t.toKebab(e)}),template:e=>({id:t.toKebab(e)}),dock:e=>({id:t.toKebab(e)}),setting:e=>({id:t.toKebab(e)}),action:e=>({id:t.toKebab(e)}),mode:e=>({name:t.toKebab(e)}),"activity-group":e=>({name:t.toKebab(e)}),"selection-axis":e=>({name:t.toKebab(e)}),leader:(e,n)=>({id:`${n.pluginId}.${t.toKebab(e)}`})};function g(t,n,r){let{entry:i}=t,a=i.surface;if(a!==void 0)return e.isFrontendTarget(n)?a===`fill`?p(i.name,i.target):h[a]?.(i.name,r):m[a]?.(i.name)}function _(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function v(e,t){return _([e.entry.surface??`extra`,e.entry.name],t)}function y(e,t){let r=e.replace(/\.[^.]+$/u,``),i=n.posix.relative(t,r);return i.startsWith(`.`)?i:`./${i}`}function b(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function x(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=v(r,n),a=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(a!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(a))throw Error(`Invalid MCP widget key '${a}'`);return{identifier:i,contribution:r,identity:g(r,e.target,t),mcpWidget:a}})}const S={global:0,workspace:1,session:2};function C(e){return e.map(e=>{let t=e.scope[0]?.toUpperCase()+e.scope.slice(1);return{identifier:`root${t}`,declaration:`scope${t}`,context:`context${t}`,entry:e}})}function w(e,t,n){let r=[],i=t;for(let[t,a]of e.entries())r.push(`const ${a.declaration} = await ${a.identifier}(${i});`),(t<e.length-1||n.some(e=>e.includes(a.context)))&&r.push(`const ${a.context} = { ...${i}, root: ${a.declaration}.value };`),i=a.context;return r}function T(e,t,n){let r=n;for(let n of e)S[n.entry.scope]<=S[t]&&(r=n.context);return r}function E(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function D(n,r,i){if(o.includes(n.contribution.field))return`${n.identifier}(${r})`;let s=e.isFrontendTarget(i)?n.identifier:`at(${n.identifier}, ${r})`,c=a[i].includes(n.contribution.field);if(n.contribution.entry.cardinality===`collection`)return s;if(n.identity===void 0)return c?n.identifier:s;let l=t.renderIdentity(n.identity);if(c)return`() => via({ ${l} }, ${n.identifier}())`;let u=`via({ ${l} }, ${s})`;return n.mcpWidget===void 0?u:`withWidget(${b(n.mcpWidget)}, ${u})`}function O(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/po-core/serverFacet';`}function k(e,t,n){if(e===`services`||t.startsWith(`...`))return t;let[r,...i]=t.split(`: `);return`get ${r}(): ${`${c[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function A(e,t,n,r){let a=/* @__PURE__ */ new Map;for(let t of e){let e=a.get(t.contribution.field);e===void 0?a.set(t.contribution.field,[t]):e.push(t)}let o=[];for(let e of[...a.keys()].sort()){let s=a.get(e);if(i.includes(e)){let i=s[0];if(i){let a=D(i,n(i),r);o.push(`${t}${k(e,`${e}: ${a},`,r)}`)}continue}let c=`[${s.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${n(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${b(e.mcpWidget)}, tool))`}`:D(e,n(e),r)).join(`, `)}]`,l=s.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${c})`:c;o.push(`${t}${k(e,`${e}: ${l},`,r)}`)}return o}function j(e,t,n,r,i){if(t.length===0)return[...e];let a=[...e],o=a.findIndex(e=>e.startsWith(`${r}services: [`)),s=o<0?``:a.splice(o,1)[0]?.match(/services: \[(.*)\],$/u)?.[1]??``,c=[...t.map(e=>`...(${e.declaration}.services ?? [])`),s].filter(Boolean).join(`, `);if(a.push(`${r}services: [${c}],`),n===`server`&&i===`session`){let e=a.findIndex(e=>e.startsWith(`${r}get activities()`)),n=e<0?``:a.splice(e,1)[0]?.match(/return \[(.*)\]; \},$/u)?.[1]??``,i=[...t.map(e=>`...(${e.declaration}.activities ?? [])`),n].filter(Boolean).join(`, `);a.push(`${r}get activities(): DoomServerSessionPlugin['activities'] { return [${i}]; },`)}return a}function M(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`),...e.map(e=>`import ${e.identifier} from '${y(e.contribution.entry.file,r)}';`),...t.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`)]}function N(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
6
- `)}function P(e){let t=[];return e.some(e=>e.includes(`at(`))&&t.push(l()),e.some(e=>e.includes(`many(`))&&t.push(u()),e.some(e=>e.includes(`defined(`))&&t.push(d()),e.some(e=>e.includes(`via(`))&&t.push(f),t.length>0?[...t,``]:[]}function F(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function I(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${F(n)} => ({`,...i,`${r}}),`]:[`${a}${F([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function L(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function R(e,t){let n=x(e,t),i=E(e.escapeHatches),a=C(e.roots),o=[],c=!1;for(let[e,t]of s.entries()){let r=n.filter(t=>s.indexOf(t.contribution.entry.scope)<=e),l=i.filter(t=>s.indexOf(t.entry.scope)<=e),u=a.filter(t=>s.indexOf(t.entry.scope)<=e),d=u[u.length-1]?.context??`context`,f=[...j(A(r,` `,e=>T(u,e.contribution.entry.scope,`context`),`server`),u,`server`,` `,t),...l.map(e=>` ...await at(${e.identifier}, ${d}),`)];if(f.length===0&&u.length===0)continue;u.length>0&&(c=!0);let p=I(w(u,`context`,f),L(u),f,` `);o.push(` ${t}: ${p[0]}`,...p.slice(1))}return N([r,O(o),...a.length?[`import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';`]:[],...c?[`import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';`]:[],``,...M(n,i,a,t.entryDir),``,...P(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...a.length?[` providerOverrides: composeServerProviderOverrides(${a.map(e=>e.identifier).join(`, `)}),`]:[],...o,`});`,``,`export default facet;`,``])}function z(e,t){let n=x(e,t),i=A(n,` `,()=>`context`,`mcp`);return N([r,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';`,``,...M(n,[],[],t.entryDir),``,...P(i),...n.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["po/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...i,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}const B={web:{module:`@agimon-ai/po-core/web`,define:`defineWebPlugin`,exportName:`webPlugin`},native:{module:`@agimon-ai/po-core/native`,define:`defineNativePlugin`,exportName:`nativePlugin`}};function V(e,t,n){let i=B[n],a=x(e,t),o=E(e.escapeHatches),l=[];for(let e of s){let t=a.filter(t=>t.contribution.entry.scope===e),r=o.filter(t=>t.entry.scope===e),i=[...A(t,` `,()=>`undefined`,n),...r.map(e=>` ...${e.identifier},`)];i.length!==0&&l.push(` ${e}: {`,...i,` },`)}let u=l.some(e=>e.includes(`get `))?`${i.define}, type ${c[n]}`:i.define;return N([r,`import { ${u} } from '${i.module}';`,``,...M(a,o,[],t.entryDir),``,...P(l),`export const ${i.exportName} = ${i.define}({`,` id: '${t.pluginId}',`,...l,`});`,``])}function H(e,t){return V(e,t,`web`)}function U(e,t){return V(e,t,`native`)}exports.renderMcpEntry=z,exports.renderNativeEntry=U,exports.renderServerEntry=R,exports.renderWebEntry=H;
5
+ `);function p(e,n){return n===void 0?{id:t.toKebab(e)}:{slot:n,id:t.toKebab(e)}}const m={tool:e=>({name:t.toSnake(e)}),command:e=>({name:t.toKebab(e)}),channel:e=>({frameType:t.toSnake(e)}),hook:e=>({event:t.toSnake(e)}),mode:e=>({name:t.toKebab(e)})},h={tool:e=>({tools:[t.toSnake(e)]}),channel:e=>({channel:t.toSnake(e)}),slot:(e,n)=>({slot:`${n.pluginId}.${t.toKebab(e)}`}),command:e=>({id:t.toKebab(e)}),tab:e=>({id:t.toKebab(e)}),template:e=>({id:t.toKebab(e)}),dock:e=>({id:t.toKebab(e)}),setting:e=>({id:t.toKebab(e)}),action:e=>({id:t.toKebab(e)}),mode:e=>({name:t.toKebab(e)}),"activity-group":e=>({name:t.toKebab(e)}),"selection-axis":e=>({name:t.toKebab(e)}),leader:(e,n)=>({id:`${n.pluginId}.${t.toKebab(e)}`})};function g(t,n,r){let{entry:i}=t,a=i.surface;if(a!==void 0)return e.isFrontendTarget(n)?a===`fill`?p(i.name,i.target):h[a]?.(i.name,r):m[a]?.(i.name)}function _(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function v(e,t){return _([e.entry.surface??`extra`,e.entry.name],t)}function y(e,t){let r=e.replace(/\.[^.]+$/u,``),i=n.posix.relative(t,r);return i.startsWith(`.`)?i:`./${i}`}function b(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function x(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=v(r,n),a=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(a!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(a))throw Error(`Invalid MCP widget key '${a}'`);return{identifier:i,contribution:r,identity:g(r,e.target,t),mcpWidget:a}})}const S={global:0,workspace:1,session:2};function C(e){return e.map(e=>{let t=e.scope[0]?.toUpperCase()+e.scope.slice(1);return{identifier:`root${t}`,declaration:`scope${t}`,context:`context${t}`,entry:e}})}function w(e,t,n){let r=[],i=t;for(let[t,a]of e.entries())r.push(`const ${a.declaration} = await ${a.identifier}(${i});`),(t<e.length-1||n.some(e=>e.includes(a.context)))&&r.push(`const ${a.context} = { ...${i}, root: ${a.declaration}.value };`),i=a.context;return r}function T(e,t,n){let r=n;for(let n of e)S[n.entry.scope]<=S[t]&&(r=n.context);return r}function E(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function D(n,r,i){if(o.includes(n.contribution.field))return`${n.identifier}(${r})`;let s=e.isFrontendTarget(i)?n.identifier:`at(${n.identifier}, ${r})`,c=a[i].includes(n.contribution.field);if(n.contribution.entry.cardinality===`collection`)return s;if(n.identity===void 0)return c?n.identifier:s;let l=t.renderIdentity(n.identity);if(c)return`() => via({ ${l} }, ${n.identifier}())`;let u=`via({ ${l} }, ${s})`;return n.mcpWidget===void 0?u:`withWidget(${b(n.mcpWidget)}, ${u})`}function O(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type PoServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/po-core/serverFacet';`}function k(e,t,n){if(e===`services`||t.startsWith(`...`))return t;let[r,...i]=t.split(`: `);return`get ${r}(): ${`${c[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function A(e,t,n,r){let a=/* @__PURE__ */ new Map;for(let t of e){let e=a.get(t.contribution.field);e===void 0?a.set(t.contribution.field,[t]):e.push(t)}let o=[];for(let e of[...a.keys()].sort()){let s=a.get(e);if(i.includes(e)){let i=s[0];if(i){let a=D(i,n(i),r);o.push(`${t}${k(e,`${e}: ${a},`,r)}`)}continue}let c=`[${s.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${n(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${b(e.mcpWidget)}, tool))`}`:D(e,n(e),r)).join(`, `)}]`,l=s.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${c})`:c;o.push(`${t}${k(e,`${e}: ${l},`,r)}`)}return o}function j(e,t,n,r,i){if(t.length===0)return[...e];let a=[...e],o=a.findIndex(e=>e.startsWith(`${r}services: [`)),s=o<0?``:a.splice(o,1)[0]?.match(/services: \[(.*)\],$/u)?.[1]??``,c=[...t.map(e=>`...(${e.declaration}.services ?? [])`),s].filter(Boolean).join(`, `);if(a.push(`${r}services: [${c}],`),n===`server`&&i===`session`){let e=a.findIndex(e=>e.startsWith(`${r}get activities()`)),n=e<0?``:a.splice(e,1)[0]?.match(/return \[(.*)\]; \},$/u)?.[1]??``,i=[...t.map(e=>`...(${e.declaration}.activities ?? [])`),n].filter(Boolean).join(`, `);a.push(`${r}get activities(): PoServerSessionPlugin['activities'] { return [${i}]; },`)}return a}function M(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`),...e.map(e=>`import ${e.identifier} from '${y(e.contribution.entry.file,r)}';`),...t.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`)]}function N(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
6
+ `)}function P(e){let t=[];return e.some(e=>e.includes(`at(`))&&t.push(l()),e.some(e=>e.includes(`many(`))&&t.push(u()),e.some(e=>e.includes(`defined(`))&&t.push(d()),e.some(e=>e.includes(`via(`))&&t.push(f),t.length>0?[...t,``]:[]}function F(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function I(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${F(n)} => ({`,...i,`${r}}),`]:[`${a}${F([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function L(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function R(e,t){let n=x(e,t),i=E(e.escapeHatches),a=C(e.roots),o=[],c=!1;for(let[e,t]of s.entries()){let r=n.filter(t=>s.indexOf(t.contribution.entry.scope)<=e),l=i.filter(t=>s.indexOf(t.entry.scope)<=e),u=a.filter(t=>s.indexOf(t.entry.scope)<=e),d=u[u.length-1]?.context??`context`,f=[...j(A(r,` `,e=>T(u,e.contribution.entry.scope,`context`),`server`),u,`server`,` `,t),...l.map(e=>` ...await at(${e.identifier}, ${d}),`)];if(f.length===0&&u.length===0)continue;u.length>0&&(c=!0);let p=I(w(u,`context`,f),L(u),f,` `);o.push(` ${t}: ${p[0]}`,...p.slice(1))}return N([r,O(o),...a.length?[`import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';`]:[],...c?[`import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';`]:[],``,...M(n,i,a,t.entryDir),``,...P(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...a.length?[` providerOverrides: composeServerProviderOverrides(${a.map(e=>e.identifier).join(`, `)}),`]:[],...o,`});`,``,`export default facet;`,``])}function z(e,t){let n=x(e,t),i=A(n,` `,()=>`context`,`mcp`);return N([r,`import { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';`,``,...M(n,[],[],t.entryDir),``,...P(i),...n.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["po/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...i,` }) satisfies PoMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}const B={web:{module:`@agimon-ai/po-core/web`,define:`defineWebPlugin`,exportName:`webPlugin`},native:{module:`@agimon-ai/po-core/native`,define:`defineNativePlugin`,exportName:`nativePlugin`}};function V(e,t,n){let i=B[n],a=x(e,t),o=E(e.escapeHatches),l=[];for(let e of s){let t=a.filter(t=>t.contribution.entry.scope===e),r=o.filter(t=>t.entry.scope===e),i=[...A(t,` `,()=>`undefined`,n),...r.map(e=>` ...${e.identifier},`)];i.length!==0&&l.push(` ${e}: {`,...i,` },`)}let u=l.some(e=>e.includes(`get `))?`${i.define}, type ${c[n]}`:i.define;return N([r,`import { ${u} } from '${i.module}';`,``,...M(a,o,[],t.entryDir),``,...P(l),`export const ${i.exportName} = ${i.define}({`,` id: '${t.pluginId}',`,...l,`});`,``])}function H(e,t){return V(e,t,`web`)}function U(e,t){return V(e,t,`native`)}exports.renderMcpEntry=z,exports.renderNativeEntry=U,exports.renderServerEntry=R,exports.renderWebEntry=H;
7
7
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["toKebab","toSnake","isFrontendTarget","posix","renderIdentity","require_index","require_index$1","node_path","HEADER","SINGLETON_FIELDS","FACTORY_FIELDS","ALWAYS_FACTORY_FIELDS","SCOPE_ORDER","CONTRIBUTIONS_TYPE","resolver","manyResolver","definedResolver","IDENTITY_HELPER","fillIdentity","target","name","BACKEND_IDENTITY","FRONTEND_IDENTITY","options","identityFor","contribution","surface","entry","uniqueIdentifier","head","parts","word","index","base","candidate","suffix","taken","identifierFor","specifierFor","file","relative","entryDir","widgetLiteral","key","bind","resolution","left","right","identifier","mcpWidget","DEPTH","rootBindings","entries","rootPrologue","lines","enclosing","root","roots","body","line","contextForScope","found","scope","hatchBindings","member","binding","contextExpression","resolved","isFactory","identity","value","serverImport","scopes","defer","field","rendered","bodyFor","grouped","bindings","held","members","contextOf","indent","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","usesRoots","visible","here","innermost","hatch","factory","renderMcpEntry","FRONTEND_ENTRY","renderFrontendEntry","shape","names","renderWebEntry","renderNativeEntry"],"sources":["../../../src/services/renderEntry/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionEntry, ExtensionScope } from '../../types/extensionGraph';\nimport { type Identity, renderIdentity, toKebab, toSnake } from '../identity';\nimport { isFrontendTarget } from '../resolveTarget';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Fields that accept one declaration rather than an array of declarations. */\nconst SINGLETON_FIELDS: readonly string[] = ['fileLinks', 'repositorySettingsPanel', 'start'];\n\n/**\n * Fields whose members are factories rather than declarations.\n *\n * Keyed by target, not by field name alone, because `channels` means two\n * different things. A server facet's array holds `() => DoomHubChannel`, so\n * the host can build one per mount. The cockpit's holds the contribution\n * itself. Treating them alike called a plain object as a function.\n */\nconst FACTORY_FIELDS: Readonly<Record<BuildTarget, readonly string[]>> = {\n server: ['channels'],\n web: [],\n native: [],\n mcp: [],\n};\n\n/**\n * Fields whose member is always a factory of the value, never the value.\n *\n * A Cordis plugin is itself a function, so nothing at runtime separates one\n * from a `(context) => plugin` factory. Rather than guess, the service surface\n * is uniformly a factory and is always called. That is also what lets a\n * package with shared per-mount state decompose: the service builds the graph\n * from the mount and publishes it, and every other contribution is a getter,\n * so it is built after the service fibers are up and can inject it.\n */\nconst ALWAYS_FACTORY_FIELDS: readonly string[] = ['services'];\n\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/**\n * Resolves a routed file's default export, which may be the declaration or a\n * factory of one. Both host helpers already accept either shape, so a\n * generated entry has to as well. Emitted rather than imported, so a generated\n * entry carries no runtime dependency beyond the helper it is calling.\n */\n/** The contribution set each host reads, used to annotate the emitted getters. */\nconst CONTRIBUTIONS_TYPE: Readonly<Record<BuildTarget, string>> = {\n server: 'DoomServerSessionPlugin',\n web: 'WebPluginContributions',\n // The native app reuses the cockpit's plugin registry, so its contributions\n // are the same type, re-exported from the native SDK.\n native: 'WebPluginContributions',\n mcp: 'DoomMcpSessionPlugin',\n};\n\n/**\n * Resolves a routed file's default export without imposing one host context on\n * every factory. The generated mount supplies the concrete context, and `at`\n * preserves that type while still accepting declaration objects.\n */\nfunction resolver(): string {\n return [\n 'type Factory<T, C> = (context: C) => T;',\n 'const at = <T, C>(value: T | Factory<T, C>, context: C): T =>',\n \" typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\",\n ].join('\\n');\n}\n\n/** Resolves a zero-many catalog contribution without flattening tuple declarations. */\nfunction manyResolver(): string {\n return [\n 'type ManyFactory<T, C> = (context: C) => T | readonly T[];',\n 'const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {',\n \" const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;\",\n ' return Array.isArray(resolved) ? resolved : [resolved as T];',\n '};',\n ].join('\\n');\n}\n\nfunction definedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const defined = <T>(values: readonly (T | undefined)[]): T[] =>',\n ' values.filter((value): value is T => value !== undefined);',\n ].join('\\n');\n}\n\n/**\n * Applies the identity the path derived, letting the authored value win.\n *\n * A call rather than an object literal on purpose. `{ name: 'x', ...value }`\n * is what this means, but TypeScript reports TS2783 whenever the spread's type\n * also declares the key, which is the common case here.\n *\n * The parameters are deliberately untyped so `T` is inferred from the\n * contribution array this sits in rather than from either argument: the\n * authored file supplies only the half the path cannot. The cost is that the\n * merged shape is not checked against `T`, only its position is.\n */\n// Preserve absence before applying a path-derived name. Otherwise optional routes\n// become incomplete placeholder tools or hooks that the `defined` filter cannot remove.\nconst IDENTITY_HELPER = [\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T =>',\n ' (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;',\n].join('\\n');\n\n/**\n * Every fill is a slot fill. There is no host-region special case.\n *\n * The cockpit's own regions are slots like any other: an activity section\n * already renders into `activity.<group>`, which is why naming the target\n * directly works for a host region and a plugin's slot alike. Keeping this\n * uniform is what lets a layout package declare new regions without the build\n * tooling learning about them.\n */\nfunction fillIdentity(name: string, target: string | undefined): Identity {\n if (target === undefined) return { id: toKebab(name) };\n return { slot: target, id: toKebab(name) };\n}\n\n/** What the path can tell each host, keyed by the folder the author typed. */\nconst BACKEND_IDENTITY: Readonly<Record<string, (name: string) => Identity>> = {\n tool: (name) => ({ name: toSnake(name) }),\n // Kebab, unlike a tool. A command name is what the user types after the\n // slash and it reaches registerCommand verbatim, so `subagents-doctor` must\n // stay `/subagents-doctor` rather than becoming `/subagents_doctor`.\n command: (name) => ({ name: toKebab(name) }),\n channel: (name) => ({ frameType: toSnake(name) }),\n hook: (name) => ({ event: toSnake(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n};\n\nconst FRONTEND_IDENTITY: Readonly<Record<string, (name: string, options: RenderOptions) => Identity>> = {\n tool: (name) => ({ tools: [toSnake(name)] }),\n channel: (name) => ({ channel: toSnake(name) }),\n slot: (name, options) => ({ slot: `${options.pluginId}.${toKebab(name)}` }),\n command: (name) => ({ id: toKebab(name) }),\n tab: (name) => ({ id: toKebab(name) }),\n template: (name) => ({ id: toKebab(name) }),\n dock: (name) => ({ id: toKebab(name) }),\n setting: (name) => ({ id: toKebab(name) }),\n action: (name) => ({ id: toKebab(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n 'activity-group': (name) => ({ name: toKebab(name) }),\n 'selection-axis': (name) => ({ name: toKebab(name) }),\n // A leader binding's id is namespaced like a slot, because the key tree is\n // shared and two plugins must not collide on one path's identity.\n leader: (name, options) => ({ id: `${options.pluginId}.${toKebab(name)}` }),\n};\n\n/**\n * What the path knows about a contribution's identity.\n *\n * Keyed by surface, because the folder is what the author types. A surface\n * absent from the table, or an identity the path cannot supply such as a tab's\n * human label, is left entirely to the authored file.\n */\nfunction identityFor(\n contribution: ResolvedContribution,\n target: BuildTarget,\n options: RenderOptions,\n): Identity | undefined {\n const { entry } = contribution;\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n if (!isFrontendTarget(target)) return BACKEND_IDENTITY[surface]?.(entry.name);\n if (surface === 'fill') return fillIdentity(entry.name, entry.target);\n return FRONTEND_IDENTITY[surface]?.(entry.name, options);\n}\n\n/** A stable, unique, valid identifier built from path words. */\nfunction uniqueIdentifier(parts: readonly string[], taken: Set<string>): string {\n const words = parts\n .join('-')\n .split(/[^A-Za-z0-9]+/u)\n .filter((word) => word.length > 0);\n const head = words.map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1))).join('');\n const base = /^[A-Za-z_]/u.test(head) ? head : `x${head}`;\n let candidate = base;\n let suffix = 2;\n while (taken.has(candidate)) candidate = `${base}${suffix++}`;\n taken.add(candidate);\n return candidate;\n}\n\n/** A stable, unique, valid identifier: surface and name, disambiguated by scope when needed. */\nfunction identifierFor(contribution: ResolvedContribution, taken: Set<string>): string {\n return uniqueIdentifier([contribution.entry.surface ?? 'extra', contribution.entry.name], taken);\n}\n\n/** The extensionless relative specifier from a generated entry to a routed file. */\nfunction specifierFor(file: string, entryDir: string): string {\n const target = file.replace(/\\.[^.]+$/u, '');\n const relative = posix.relative(entryDir, target);\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\ninterface Binding {\n readonly identifier: string;\n readonly contribution: ResolvedContribution;\n readonly identity: Identity | undefined;\n readonly mcpWidget: string | undefined;\n}\n\n/** Encode data for generated JavaScript, including the HTML script boundary. */\nfunction widgetLiteral(key: string): string {\n return JSON.stringify(key).replaceAll('<', '\\\\u003c').replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029');\n}\n\nfunction bind(resolution: TargetResolution, options: RenderOptions): Binding[] {\n const taken = new Set<string>();\n return [...resolution.contributions]\n .sort((left, right) => left.entry.file.localeCompare(right.entry.file))\n .map((contribution) => {\n // The contribution takes its identifier first, so the plain name stays\n // with the tool rather than going to whichever file sorted earlier.\n const identifier = identifierFor(contribution, taken);\n const mcpWidget = resolution.target === 'mcp' ? options.mcpWidgets?.[contribution.entry.file] : undefined;\n if (mcpWidget !== undefined && !/^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*\\/[a-z0-9_]+$/u.test(mcpWidget))\n throw new Error(`Invalid MCP widget key '${mcpWidget}'`);\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n mcpWidget,\n };\n });\n}\n\n/** Scope nesting depth, so a contribution can find the root that encloses it. */\nconst DEPTH: Readonly<Record<ExtensionScope, number>> = { global: 0, workspace: 1, session: 2 };\n\ninterface RootBinding {\n /** The imported factory. */\n readonly identifier: string;\n /** The declaration it returned: `value` plus this scope's lifecycle hooks. */\n readonly declaration: string;\n /** The mount context contributions beneath this root receive. */\n readonly context: string;\n readonly entry: ExtensionEntry;\n}\n\nfunction rootBindings(entries: readonly ExtensionEntry[]): RootBinding[] {\n return entries.map((entry) => {\n const suffix = entry.scope[0]?.toUpperCase() + entry.scope.slice(1);\n return { identifier: `root${suffix}`, declaration: `scope${suffix}`, context: `context${suffix}`, entry };\n });\n}\n\n/**\n * Constructs each scope before anything it contains, outermost first.\n *\n * Every root is handed the context its enclosing root produced. Root factories\n * may be async, so the generated host factory awaits each one before exposing\n * its value to narrower contributions.\n */\nfunction rootPrologue(roots: readonly RootBinding[], base: string, body: readonly string[]): string[] {\n const lines: string[] = [];\n let enclosing = base;\n for (const [index, root] of roots.entries()) {\n lines.push(`const ${root.declaration} = await ${root.identifier}(${enclosing});`);\n const contextIsUsed = index < roots.length - 1 || body.some((line) => line.includes(root.context));\n if (contextIsUsed) lines.push(`const ${root.context} = { ...${enclosing}, root: ${root.declaration}.value };`);\n enclosing = root.context;\n }\n return lines;\n}\n\n/** The context a contribution sees: the nearest enclosing root's, or the mount's. */\nfunction contextForScope(roots: readonly RootBinding[], scope: ExtensionScope, base: string): string {\n let found = base;\n for (const root of roots) {\n if (DEPTH[root.entry.scope] <= DEPTH[scope]) found = root.context;\n }\n return found;\n}\n\nfunction hatchBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n return [...entries]\n .sort((left, right) => left.file.localeCompare(right.file))\n .map((entry, index) => ({ identifier: `extra${index === 0 ? '' : index + 1}`, entry }));\n}\n\n/**\n * One contribution as it appears inside its array, identity first so the file wins.\n *\n * The browser half is never resolved. The cockpit builds its definition as\n * data and starts it separately, so a frontend file has no mount context to\n * receive, and resolving anyway would call any export that happens to be a\n * function. A React component is a function, so that is not hypothetical.\n */\nfunction member(binding: Binding, contextExpression: string, target: BuildTarget): string {\n if (ALWAYS_FACTORY_FIELDS.includes(binding.contribution.field)) {\n return `${binding.identifier}(${contextExpression})`;\n }\n\n const resolved = isFrontendTarget(target) ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n const isFactory = FACTORY_FIELDS[target].includes(binding.contribution.field);\n // A live collection is the contribution container itself. Applying a path\n // identity would spread class instances into plain objects and can erase\n // prototype-backed snapshot/subscribe methods.\n if (binding.contribution.entry.cardinality === 'collection') return resolved;\n if (binding.identity === undefined) return isFactory ? binding.identifier : resolved;\n\n const identity = renderIdentity(binding.identity);\n // A channel array holds factories, so the identity is applied inside one.\n if (isFactory) return `() => via({ ${identity} }, ${binding.identifier}())`;\n const value = `via({ ${identity} }, ${resolved})`;\n return binding.mcpWidget === undefined ? value : `withWidget(${widgetLiteral(binding.mcpWidget)}, ${value})`;\n}\n\n/** The server entry imports only the types its scopes actually use. */\nfunction serverImport(scopes: readonly string[]): string {\n const types = scopes.some((line) => line.includes('get ')) ? ['type DoomServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverFacet';`;\n}\n\n/**\n * Emits a contribution as a getter, so it is built after services mount.\n *\n * Both host helpers register `services` first and read every other field\n * afterwards. A plain property would be evaluated when the entry's factory\n * returns, which is before any service exists, so a routed file could never\n * inject one at construction and every package with shared per-mount state\n * would be stuck in one closure.\n *\n * `services` itself stays a plain property: it is what the helper reads first,\n * and a getter for it would buy nothing.\n */\nfunction defer(field: string, rendered: string, target: BuildTarget): string {\n if (field === 'services' || rendered.startsWith('...')) return rendered;\n const [name, ...value] = rendered.split(': ');\n // Annotated, because a getter gets no contextual type from the object\n // literal it sits in, so the identity helper's T would widen to unknown and\n // the contribution would stop type checking against the array it joins.\n const type = `${CONTRIBUTIONS_TYPE[target]}['${name}']`;\n return `get ${name}(): ${type} { return ${value.join(': ').replace(/,$/u, '')}; },`;\n}\n\n/**\n * The contributions object's body.\n *\n * The mount context is resolved per contribution rather than once, because a\n * root rebinds it for everything beneath it and two contributions at different\n * scopes can therefore see different contexts in the same object.\n */\nfunction bodyFor(\n bindings: readonly Binding[],\n indent: string,\n contextOf: (binding: Binding) => string,\n target: BuildTarget,\n): string[] {\n const grouped = new Map<string, Binding[]>();\n for (const binding of bindings) {\n const held = grouped.get(binding.contribution.field);\n if (held === undefined) grouped.set(binding.contribution.field, [binding]);\n else held.push(binding);\n }\n\n const lines: string[] = [];\n for (const field of [...grouped.keys()].sort()) {\n const members = grouped.get(field) as Binding[];\n if (SINGLETON_FIELDS.includes(field)) {\n const entry = members[0];\n if (entry) {\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n continue;\n }\n const renderedMembers = members.map((entry) =>\n entry.contribution.entry.cardinality === 'many'\n ? `...many(${entry.identifier}, ${contextOf(entry)})${entry.mcpWidget === undefined ? '' : `.map((tool) => withWidget(${widgetLiteral(entry.mcpWidget)}, tool))`}`\n : member(entry, contextOf(entry), target),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const rendered = members.some((entry) => entry.contribution.entry.cardinality === 'optional')\n ? `defined(${entries})`\n : entries;\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n return lines;\n}\n\n/** Root-owned registrations join routed registrations in the host's usual fields. */\nfunction withRootRegistrations(\n body: readonly string[],\n roots: readonly RootBinding[],\n target: 'server',\n indent: string,\n scope: ExtensionScope,\n): string[] {\n if (roots.length === 0) return [...body];\n const lines = [...body];\n const servicesIndex = lines.findIndex((line) => line.startsWith(`${indent}services: [`));\n const routedServices =\n servicesIndex < 0 ? '' : (lines.splice(servicesIndex, 1)[0]?.match(/services: \\[(.*)\\],$/u)?.[1] ?? '');\n const services = [...roots.map((root) => `...(${root.declaration}.services ?? [])`), routedServices]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}services: [${services}],`);\n\n if (target === 'server' && scope === 'session') {\n const activitiesIndex = lines.findIndex((line) => line.startsWith(`${indent}get activities()`));\n const routedActivities =\n activitiesIndex < 0 ? '' : (lines.splice(activitiesIndex, 1)[0]?.match(/return \\[(.*)\\]; \\},$/u)?.[1] ?? '');\n const activities = [...roots.map((root) => `...(${root.declaration}.activities ?? [])`), routedActivities]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}get activities(): DoomServerSessionPlugin['activities'] { return [${activities}]; },`);\n }\n return lines;\n}\n\nfunction importsFor(\n bindings: readonly Binding[],\n hatches: readonly { identifier: string; entry: ExtensionEntry }[],\n roots: readonly RootBinding[],\n entryDir: string,\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...bindings.map((b) => `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`),\n ...hatches.map((h) => `import ${h.identifier} from '${specifierFor(h.entry.file, entryDir)}';`),\n ];\n}\n\nfunction compact(lines: readonly string[]): string {\n return lines.filter((line, index, all) => !(line === '' && all[index - 1] === '')).join('\\n');\n}\n\n/**\n * Emits the resolver only when something calls it.\n *\n * Extension packages compile with noUnusedLocals, so a generated entry whose\n * every contribution is a factory would otherwise fail to typecheck on an\n * unused helper.\n */\nfunction resolverFor(body: readonly string[]): string[] {\n const lines: string[] = [];\n if (body.some((line) => line.includes('at('))) lines.push(resolver());\n if (body.some((line) => line.includes('many('))) lines.push(manyResolver());\n if (body.some((line) => line.includes('defined('))) lines.push(definedResolver());\n if (body.some((line) => line.includes('via('))) lines.push(IDENTITY_HELPER);\n return lines.length > 0 ? [...lines, ''] : [];\n}\n\n/** `noUnusedParameters` means a scope that never threads context takes none. */\nfunction parameterFor(lines: readonly string[]): string {\n return lines.some((line) => line.includes(', context)') || line.includes('(context)')) ? '(context)' : '()';\n}\n\n/**\n * The scope's factory: an expression body, or a block when roots come first.\n *\n * A root has to be constructed before the object that reads it, so a scope\n * that has one becomes statements followed by a return rather than a bare\n * object literal.\n */\nfunction scopeBody(\n prologue: readonly string[],\n hooks: string | undefined,\n body: readonly string[],\n indent: string,\n): string[] {\n const object = [...(hooks === undefined ? [] : [`${indent} ${hooks}`]), ...body];\n const asynchronous = [...prologue, ...body].some((line) => line.includes('await '));\n const prefix = asynchronous ? 'async ' : '';\n if (prologue.length === 0) return [`${prefix}${parameterFor(body)} => ({`, ...object, `${indent}}),`];\n return [\n `${prefix}${parameterFor([...prologue, ...body])} => {`,\n ...prologue.map((line) => `${indent} ${line}`),\n `${indent} return {`,\n ...object.map((line) => ` ${line}`),\n `${indent} };`,\n `${indent}},`,\n ];\n}\n\n/** Folds every enclosing root's lifecycle hooks into the one set the host reads. */\nfunction rootHooks(roots: readonly RootBinding[]): string | undefined {\n if (roots.length === 0) return undefined;\n return `...composeRootHooks(${roots.map((root) => root.declaration).join(', ')}),`;\n}\n\n/**\n * The headless entry, one declaration per scope.\n *\n * Contributions cascade downward here because the server does not do it\n * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the\n * scopes above it. Emitting the repetition is what lets an author declare a\n * channel once and have it mount at all three scopes.\n */\nexport function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n const allRoots = rootBindings(resolution.roots);\n\n const scopes: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = bindings.filter((b) => SCOPE_ORDER.indexOf(b.contribution.entry.scope) <= index);\n const here = hatches.filter((h) => SCOPE_ORDER.indexOf(h.entry.scope) <= index);\n // Each scope is an independent mount, so it constructs the roots that\n // enclose it from scratch rather than sharing the deeper scope's.\n const roots = allRoots.filter((root) => SCOPE_ORDER.indexOf(root.entry.scope) <= index);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(visible, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'server'),\n roots,\n 'server',\n ' ',\n scope,\n ),\n ...here.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n if (body.length === 0 && roots.length === 0) continue;\n if (roots.length > 0) usesRoots = true;\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...scopes,\n '});',\n '',\n 'export default facet;',\n '',\n ]);\n}\n\n/** The explicit remote-MCP entry. It intentionally imports only .mcp declarations. */\nexport function renderMcpEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const body = bodyFor(bindings, ' ', () => 'context', 'mcp');\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\n ...(bindings.some((binding) => binding.mcpWidget !== undefined)\n ? [\n 'const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({',\n ' ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },',\n '});',\n '',\n ]\n : []),\n 'export const mcp = defineMcpPlugin({',\n ` name: '${options.packageName}',`,\n ' session: (context) => ({',\n ...body,\n ' }) satisfies DoomMcpSessionPlugin,',\n '});',\n '',\n 'export default mcp;',\n '',\n ]);\n}\n\n/** What differs between the two frontend entries: the SDK they import and the name they export. */\ninterface FrontendEntryShape {\n readonly module: string;\n readonly define: string;\n readonly exportName: string;\n}\n\nconst FRONTEND_ENTRY: Readonly<Record<FrontendTarget, FrontendEntryShape>> = {\n web: { module: '@agimon-ai/po-core/web', define: 'defineWebPlugin', exportName: 'webPlugin' },\n native: { module: '@agimon-ai/po-core/native', define: 'defineNativePlugin', exportName: 'nativePlugin' },\n};\n\n/**\n * A frontend entry, one contributions object per scope.\n *\n * No cascade here, unlike the server: the registry already folds global into\n * workspace into session before install, so repeating a contribution would\n * install it twice.\n */\nfunction renderFrontendEntry(resolution: TargetResolution, options: RenderOptions, target: FrontendTarget): string {\n const shape = FRONTEND_ENTRY[target];\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n\n const scopes: string[] = [];\n for (const scope of SCOPE_ORDER) {\n const visible = bindings.filter((b) => b.contribution.entry.scope === scope);\n const here = hatches.filter((h) => h.entry.scope === scope);\n const body = [\n ...bodyFor(visible, ' ', () => 'undefined', target),\n // Frontend escape hatches are contribution data. Calling them would also\n // call React components, so merge the authored object directly.\n ...here.map((hatch) => ` ...${hatch.identifier},`),\n ];\n if (body.length === 0) continue;\n scopes.push(` ${scope}: {`, ...body, ' },');\n }\n\n const names = scopes.some((line) => line.includes('get '))\n ? `${shape.define}, type ${CONTRIBUTIONS_TYPE[target]}`\n : shape.define;\n return compact([\n HEADER,\n `import { ${names} } from '${shape.module}';`,\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n `export const ${shape.exportName} = ${shape.define}({`,\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n\n/** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'web');\n}\n\n/** The native app entry, built from `.native` files only. */\nexport function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'native');\n}\n"],"mappings":"4GAQA,MAAMQ,EAAS,4DAGTC,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtFC,EAAmE,CACvE,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,OAAQ,CAAC,EACT,IAAK,CAAC,CACR,EAYMC,EAA2C,CAAC,UAAU,EAEtDC,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1EC,EAA4D,CAChE,OAAQ,0BACR,IAAK,yBAGL,OAAQ,yBACR,IAAK,sBACP,EAOA,SAASC,GAAmB,CAC1B,MAAO,CACL,0CACA,gEACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CAGA,SAASC,GAAuB,CAC9B,MAAO,CACL,6DACA,kGACA,kGACA,iEACA,IACF,CAAC,CAAC,KAAK;CAAI,CACb,CAEA,SAASC,GAA0B,CACjC,MAAO,CACL,yDACA,kEACA,8DACF,CAAC,CAAC,KAAK;CAAI,CACb,CAgBA,MAAMC,EAAkB,CACtB,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GAAGyD,EAAM,OAAO,SAASvG,EAAmBM,KAC5CiG,EAAM,OACV,OAAOrB,EAAQ,CACbvF,EACA,YAAY6G,EAAM,WAAWD,EAAM,OAAO,IAC1C,GACA,GAAG1B,EAAWZ,EAAUe,EAAS,CAAC,EAAGtE,EAAQ,QAAQ,EACrD,GACA,GAAG0E,EAAYzB,CAAM,EACrB,gBAAgB4C,EAAM,WAAW,KAAKA,EAAM,OAAO,IACnD,UAAU7F,EAAQ,SAAS,IAC3B,GAAGiD,EACH,MACA,EACF,CAAC,CACH,CAGA,SAAgB8C,EAAe,EAA8B,EAAgC,CAC3F,OAAOH,EAAoBtE,EAAYtB,EAAS,KAAK,CACvD,CAGA,SAAgBgG,EAAkB,EAA8B,EAAgC,CAC9F,OAAOJ,EAAoBtE,EAAYtB,EAAS,QAAQ,CAC1D"}
1
+ {"version":3,"file":"index.cjs","names":["toKebab","toSnake","isFrontendTarget","posix","renderIdentity","require_index","require_index$1","node_path","HEADER","SINGLETON_FIELDS","FACTORY_FIELDS","ALWAYS_FACTORY_FIELDS","SCOPE_ORDER","CONTRIBUTIONS_TYPE","resolver","manyResolver","definedResolver","IDENTITY_HELPER","fillIdentity","target","name","BACKEND_IDENTITY","FRONTEND_IDENTITY","options","identityFor","contribution","surface","entry","uniqueIdentifier","head","parts","word","index","base","candidate","suffix","taken","identifierFor","specifierFor","file","relative","entryDir","widgetLiteral","key","bind","resolution","left","right","identifier","mcpWidget","DEPTH","rootBindings","entries","rootPrologue","lines","enclosing","root","roots","body","line","contextForScope","found","scope","hatchBindings","member","binding","contextExpression","resolved","isFactory","identity","value","serverImport","scopes","defer","field","rendered","bodyFor","grouped","bindings","held","members","contextOf","indent","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","usesRoots","visible","here","innermost","hatch","factory","renderMcpEntry","FRONTEND_ENTRY","renderFrontendEntry","shape","names","renderWebEntry","renderNativeEntry"],"sources":["../../../src/services/renderEntry/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionEntry, ExtensionScope } from '../../types/extensionGraph';\nimport { type Identity, renderIdentity, toKebab, toSnake } from '../identity';\nimport { isFrontendTarget } from '../resolveTarget';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Fields that accept one declaration rather than an array of declarations. */\nconst SINGLETON_FIELDS: readonly string[] = ['fileLinks', 'repositorySettingsPanel', 'start'];\n\n/**\n * Fields whose members are factories rather than declarations.\n *\n * Keyed by target, not by field name alone, because `channels` means two\n * different things. A server facet's array holds `() => PoHubChannel`, so\n * the host can build one per mount. The cockpit's holds the contribution\n * itself. Treating them alike called a plain object as a function.\n */\nconst FACTORY_FIELDS: Readonly<Record<BuildTarget, readonly string[]>> = {\n server: ['channels'],\n web: [],\n native: [],\n mcp: [],\n};\n\n/**\n * Fields whose member is always a factory of the value, never the value.\n *\n * A Cordis plugin is itself a function, so nothing at runtime separates one\n * from a `(context) => plugin` factory. Rather than guess, the service surface\n * is uniformly a factory and is always called. That is also what lets a\n * package with shared per-mount state decompose: the service builds the graph\n * from the mount and publishes it, and every other contribution is a getter,\n * so it is built after the service fibers are up and can inject it.\n */\nconst ALWAYS_FACTORY_FIELDS: readonly string[] = ['services'];\n\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/**\n * Resolves a routed file's default export, which may be the declaration or a\n * factory of one. Both host helpers already accept either shape, so a\n * generated entry has to as well. Emitted rather than imported, so a generated\n * entry carries no runtime dependency beyond the helper it is calling.\n */\n/** The contribution set each host reads, used to annotate the emitted getters. */\nconst CONTRIBUTIONS_TYPE: Readonly<Record<BuildTarget, string>> = {\n server: 'PoServerSessionPlugin',\n web: 'WebPluginContributions',\n // The native app reuses the cockpit's plugin registry, so its contributions\n // are the same type, re-exported from the native SDK.\n native: 'WebPluginContributions',\n mcp: 'PoMcpSessionPlugin',\n};\n\n/**\n * Resolves a routed file's default export without imposing one host context on\n * every factory. The generated mount supplies the concrete context, and `at`\n * preserves that type while still accepting declaration objects.\n */\nfunction resolver(): string {\n return [\n 'type Factory<T, C> = (context: C) => T;',\n 'const at = <T, C>(value: T | Factory<T, C>, context: C): T =>',\n \" typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\",\n ].join('\\n');\n}\n\n/** Resolves a zero-many catalog contribution without flattening tuple declarations. */\nfunction manyResolver(): string {\n return [\n 'type ManyFactory<T, C> = (context: C) => T | readonly T[];',\n 'const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {',\n \" const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;\",\n ' return Array.isArray(resolved) ? resolved : [resolved as T];',\n '};',\n ].join('\\n');\n}\n\nfunction definedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const defined = <T>(values: readonly (T | undefined)[]): T[] =>',\n ' values.filter((value): value is T => value !== undefined);',\n ].join('\\n');\n}\n\n/**\n * Applies the identity the path derived, letting the authored value win.\n *\n * A call rather than an object literal on purpose. `{ name: 'x', ...value }`\n * is what this means, but TypeScript reports TS2783 whenever the spread's type\n * also declares the key, which is the common case here.\n *\n * The parameters are deliberately untyped so `T` is inferred from the\n * contribution array this sits in rather than from either argument: the\n * authored file supplies only the half the path cannot. The cost is that the\n * merged shape is not checked against `T`, only its position is.\n */\n// Preserve absence before applying a path-derived name. Otherwise optional routes\n// become incomplete placeholder tools or hooks that the `defined` filter cannot remove.\nconst IDENTITY_HELPER = [\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T =>',\n ' (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;',\n].join('\\n');\n\n/**\n * Every fill is a slot fill. There is no host-region special case.\n *\n * The cockpit's own regions are slots like any other: an activity section\n * already renders into `activity.<group>`, which is why naming the target\n * directly works for a host region and a plugin's slot alike. Keeping this\n * uniform is what lets a layout package declare new regions without the build\n * tooling learning about them.\n */\nfunction fillIdentity(name: string, target: string | undefined): Identity {\n if (target === undefined) return { id: toKebab(name) };\n return { slot: target, id: toKebab(name) };\n}\n\n/** What the path can tell each host, keyed by the folder the author typed. */\nconst BACKEND_IDENTITY: Readonly<Record<string, (name: string) => Identity>> = {\n tool: (name) => ({ name: toSnake(name) }),\n // Kebab, unlike a tool. A command name is what the user types after the\n // slash and it reaches registerCommand verbatim, so `subagents-doctor` must\n // stay `/subagents-doctor` rather than becoming `/subagents_doctor`.\n command: (name) => ({ name: toKebab(name) }),\n channel: (name) => ({ frameType: toSnake(name) }),\n hook: (name) => ({ event: toSnake(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n};\n\nconst FRONTEND_IDENTITY: Readonly<Record<string, (name: string, options: RenderOptions) => Identity>> = {\n tool: (name) => ({ tools: [toSnake(name)] }),\n channel: (name) => ({ channel: toSnake(name) }),\n slot: (name, options) => ({ slot: `${options.pluginId}.${toKebab(name)}` }),\n command: (name) => ({ id: toKebab(name) }),\n tab: (name) => ({ id: toKebab(name) }),\n template: (name) => ({ id: toKebab(name) }),\n dock: (name) => ({ id: toKebab(name) }),\n setting: (name) => ({ id: toKebab(name) }),\n action: (name) => ({ id: toKebab(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n 'activity-group': (name) => ({ name: toKebab(name) }),\n 'selection-axis': (name) => ({ name: toKebab(name) }),\n // A leader binding's id is namespaced like a slot, because the key tree is\n // shared and two plugins must not collide on one path's identity.\n leader: (name, options) => ({ id: `${options.pluginId}.${toKebab(name)}` }),\n};\n\n/**\n * What the path knows about a contribution's identity.\n *\n * Keyed by surface, because the folder is what the author types. A surface\n * absent from the table, or an identity the path cannot supply such as a tab's\n * human label, is left entirely to the authored file.\n */\nfunction identityFor(\n contribution: ResolvedContribution,\n target: BuildTarget,\n options: RenderOptions,\n): Identity | undefined {\n const { entry } = contribution;\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n if (!isFrontendTarget(target)) return BACKEND_IDENTITY[surface]?.(entry.name);\n if (surface === 'fill') return fillIdentity(entry.name, entry.target);\n return FRONTEND_IDENTITY[surface]?.(entry.name, options);\n}\n\n/** A stable, unique, valid identifier built from path words. */\nfunction uniqueIdentifier(parts: readonly string[], taken: Set<string>): string {\n const words = parts\n .join('-')\n .split(/[^A-Za-z0-9]+/u)\n .filter((word) => word.length > 0);\n const head = words.map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1))).join('');\n const base = /^[A-Za-z_]/u.test(head) ? head : `x${head}`;\n let candidate = base;\n let suffix = 2;\n while (taken.has(candidate)) candidate = `${base}${suffix++}`;\n taken.add(candidate);\n return candidate;\n}\n\n/** A stable, unique, valid identifier: surface and name, disambiguated by scope when needed. */\nfunction identifierFor(contribution: ResolvedContribution, taken: Set<string>): string {\n return uniqueIdentifier([contribution.entry.surface ?? 'extra', contribution.entry.name], taken);\n}\n\n/** The extensionless relative specifier from a generated entry to a routed file. */\nfunction specifierFor(file: string, entryDir: string): string {\n const target = file.replace(/\\.[^.]+$/u, '');\n const relative = posix.relative(entryDir, target);\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\ninterface Binding {\n readonly identifier: string;\n readonly contribution: ResolvedContribution;\n readonly identity: Identity | undefined;\n readonly mcpWidget: string | undefined;\n}\n\n/** Encode data for generated JavaScript, including the HTML script boundary. */\nfunction widgetLiteral(key: string): string {\n return JSON.stringify(key).replaceAll('<', '\\\\u003c').replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029');\n}\n\nfunction bind(resolution: TargetResolution, options: RenderOptions): Binding[] {\n const taken = new Set<string>();\n return [...resolution.contributions]\n .sort((left, right) => left.entry.file.localeCompare(right.entry.file))\n .map((contribution) => {\n // The contribution takes its identifier first, so the plain name stays\n // with the tool rather than going to whichever file sorted earlier.\n const identifier = identifierFor(contribution, taken);\n const mcpWidget = resolution.target === 'mcp' ? options.mcpWidgets?.[contribution.entry.file] : undefined;\n if (mcpWidget !== undefined && !/^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*\\/[a-z0-9_]+$/u.test(mcpWidget))\n throw new Error(`Invalid MCP widget key '${mcpWidget}'`);\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n mcpWidget,\n };\n });\n}\n\n/** Scope nesting depth, so a contribution can find the root that encloses it. */\nconst DEPTH: Readonly<Record<ExtensionScope, number>> = { global: 0, workspace: 1, session: 2 };\n\ninterface RootBinding {\n /** The imported factory. */\n readonly identifier: string;\n /** The declaration it returned: `value` plus this scope's lifecycle hooks. */\n readonly declaration: string;\n /** The mount context contributions beneath this root receive. */\n readonly context: string;\n readonly entry: ExtensionEntry;\n}\n\nfunction rootBindings(entries: readonly ExtensionEntry[]): RootBinding[] {\n return entries.map((entry) => {\n const suffix = entry.scope[0]?.toUpperCase() + entry.scope.slice(1);\n return { identifier: `root${suffix}`, declaration: `scope${suffix}`, context: `context${suffix}`, entry };\n });\n}\n\n/**\n * Constructs each scope before anything it contains, outermost first.\n *\n * Every root is handed the context its enclosing root produced. Root factories\n * may be async, so the generated host factory awaits each one before exposing\n * its value to narrower contributions.\n */\nfunction rootPrologue(roots: readonly RootBinding[], base: string, body: readonly string[]): string[] {\n const lines: string[] = [];\n let enclosing = base;\n for (const [index, root] of roots.entries()) {\n lines.push(`const ${root.declaration} = await ${root.identifier}(${enclosing});`);\n const contextIsUsed = index < roots.length - 1 || body.some((line) => line.includes(root.context));\n if (contextIsUsed) lines.push(`const ${root.context} = { ...${enclosing}, root: ${root.declaration}.value };`);\n enclosing = root.context;\n }\n return lines;\n}\n\n/** The context a contribution sees: the nearest enclosing root's, or the mount's. */\nfunction contextForScope(roots: readonly RootBinding[], scope: ExtensionScope, base: string): string {\n let found = base;\n for (const root of roots) {\n if (DEPTH[root.entry.scope] <= DEPTH[scope]) found = root.context;\n }\n return found;\n}\n\nfunction hatchBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n return [...entries]\n .sort((left, right) => left.file.localeCompare(right.file))\n .map((entry, index) => ({ identifier: `extra${index === 0 ? '' : index + 1}`, entry }));\n}\n\n/**\n * One contribution as it appears inside its array, identity first so the file wins.\n *\n * The browser half is never resolved. The cockpit builds its definition as\n * data and starts it separately, so a frontend file has no mount context to\n * receive, and resolving anyway would call any export that happens to be a\n * function. A React component is a function, so that is not hypothetical.\n */\nfunction member(binding: Binding, contextExpression: string, target: BuildTarget): string {\n if (ALWAYS_FACTORY_FIELDS.includes(binding.contribution.field)) {\n return `${binding.identifier}(${contextExpression})`;\n }\n\n const resolved = isFrontendTarget(target) ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n const isFactory = FACTORY_FIELDS[target].includes(binding.contribution.field);\n // A live collection is the contribution container itself. Applying a path\n // identity would spread class instances into plain objects and can erase\n // prototype-backed snapshot/subscribe methods.\n if (binding.contribution.entry.cardinality === 'collection') return resolved;\n if (binding.identity === undefined) return isFactory ? binding.identifier : resolved;\n\n const identity = renderIdentity(binding.identity);\n // A channel array holds factories, so the identity is applied inside one.\n if (isFactory) return `() => via({ ${identity} }, ${binding.identifier}())`;\n const value = `via({ ${identity} }, ${resolved})`;\n return binding.mcpWidget === undefined ? value : `withWidget(${widgetLiteral(binding.mcpWidget)}, ${value})`;\n}\n\n/** The server entry imports only the types its scopes actually use. */\nfunction serverImport(scopes: readonly string[]): string {\n const types = scopes.some((line) => line.includes('get ')) ? ['type PoServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverFacet';`;\n}\n\n/**\n * Emits a contribution as a getter, so it is built after services mount.\n *\n * Both host helpers register `services` first and read every other field\n * afterwards. A plain property would be evaluated when the entry's factory\n * returns, which is before any service exists, so a routed file could never\n * inject one at construction and every package with shared per-mount state\n * would be stuck in one closure.\n *\n * `services` itself stays a plain property: it is what the helper reads first,\n * and a getter for it would buy nothing.\n */\nfunction defer(field: string, rendered: string, target: BuildTarget): string {\n if (field === 'services' || rendered.startsWith('...')) return rendered;\n const [name, ...value] = rendered.split(': ');\n // Annotated, because a getter gets no contextual type from the object\n // literal it sits in, so the identity helper's T would widen to unknown and\n // the contribution would stop type checking against the array it joins.\n const type = `${CONTRIBUTIONS_TYPE[target]}['${name}']`;\n return `get ${name}(): ${type} { return ${value.join(': ').replace(/,$/u, '')}; },`;\n}\n\n/**\n * The contributions object's body.\n *\n * The mount context is resolved per contribution rather than once, because a\n * root rebinds it for everything beneath it and two contributions at different\n * scopes can therefore see different contexts in the same object.\n */\nfunction bodyFor(\n bindings: readonly Binding[],\n indent: string,\n contextOf: (binding: Binding) => string,\n target: BuildTarget,\n): string[] {\n const grouped = new Map<string, Binding[]>();\n for (const binding of bindings) {\n const held = grouped.get(binding.contribution.field);\n if (held === undefined) grouped.set(binding.contribution.field, [binding]);\n else held.push(binding);\n }\n\n const lines: string[] = [];\n for (const field of [...grouped.keys()].sort()) {\n const members = grouped.get(field) as Binding[];\n if (SINGLETON_FIELDS.includes(field)) {\n const entry = members[0];\n if (entry) {\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n continue;\n }\n const renderedMembers = members.map((entry) =>\n entry.contribution.entry.cardinality === 'many'\n ? `...many(${entry.identifier}, ${contextOf(entry)})${entry.mcpWidget === undefined ? '' : `.map((tool) => withWidget(${widgetLiteral(entry.mcpWidget)}, tool))`}`\n : member(entry, contextOf(entry), target),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const rendered = members.some((entry) => entry.contribution.entry.cardinality === 'optional')\n ? `defined(${entries})`\n : entries;\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n return lines;\n}\n\n/** Root-owned registrations join routed registrations in the host's usual fields. */\nfunction withRootRegistrations(\n body: readonly string[],\n roots: readonly RootBinding[],\n target: 'server',\n indent: string,\n scope: ExtensionScope,\n): string[] {\n if (roots.length === 0) return [...body];\n const lines = [...body];\n const servicesIndex = lines.findIndex((line) => line.startsWith(`${indent}services: [`));\n const routedServices =\n servicesIndex < 0 ? '' : (lines.splice(servicesIndex, 1)[0]?.match(/services: \\[(.*)\\],$/u)?.[1] ?? '');\n const services = [...roots.map((root) => `...(${root.declaration}.services ?? [])`), routedServices]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}services: [${services}],`);\n\n if (target === 'server' && scope === 'session') {\n const activitiesIndex = lines.findIndex((line) => line.startsWith(`${indent}get activities()`));\n const routedActivities =\n activitiesIndex < 0 ? '' : (lines.splice(activitiesIndex, 1)[0]?.match(/return \\[(.*)\\]; \\},$/u)?.[1] ?? '');\n const activities = [...roots.map((root) => `...(${root.declaration}.activities ?? [])`), routedActivities]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}get activities(): PoServerSessionPlugin['activities'] { return [${activities}]; },`);\n }\n return lines;\n}\n\nfunction importsFor(\n bindings: readonly Binding[],\n hatches: readonly { identifier: string; entry: ExtensionEntry }[],\n roots: readonly RootBinding[],\n entryDir: string,\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...bindings.map((b) => `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`),\n ...hatches.map((h) => `import ${h.identifier} from '${specifierFor(h.entry.file, entryDir)}';`),\n ];\n}\n\nfunction compact(lines: readonly string[]): string {\n return lines.filter((line, index, all) => !(line === '' && all[index - 1] === '')).join('\\n');\n}\n\n/**\n * Emits the resolver only when something calls it.\n *\n * Extension packages compile with noUnusedLocals, so a generated entry whose\n * every contribution is a factory would otherwise fail to typecheck on an\n * unused helper.\n */\nfunction resolverFor(body: readonly string[]): string[] {\n const lines: string[] = [];\n if (body.some((line) => line.includes('at('))) lines.push(resolver());\n if (body.some((line) => line.includes('many('))) lines.push(manyResolver());\n if (body.some((line) => line.includes('defined('))) lines.push(definedResolver());\n if (body.some((line) => line.includes('via('))) lines.push(IDENTITY_HELPER);\n return lines.length > 0 ? [...lines, ''] : [];\n}\n\n/** `noUnusedParameters` means a scope that never threads context takes none. */\nfunction parameterFor(lines: readonly string[]): string {\n return lines.some((line) => line.includes(', context)') || line.includes('(context)')) ? '(context)' : '()';\n}\n\n/**\n * The scope's factory: an expression body, or a block when roots come first.\n *\n * A root has to be constructed before the object that reads it, so a scope\n * that has one becomes statements followed by a return rather than a bare\n * object literal.\n */\nfunction scopeBody(\n prologue: readonly string[],\n hooks: string | undefined,\n body: readonly string[],\n indent: string,\n): string[] {\n const object = [...(hooks === undefined ? [] : [`${indent} ${hooks}`]), ...body];\n const asynchronous = [...prologue, ...body].some((line) => line.includes('await '));\n const prefix = asynchronous ? 'async ' : '';\n if (prologue.length === 0) return [`${prefix}${parameterFor(body)} => ({`, ...object, `${indent}}),`];\n return [\n `${prefix}${parameterFor([...prologue, ...body])} => {`,\n ...prologue.map((line) => `${indent} ${line}`),\n `${indent} return {`,\n ...object.map((line) => ` ${line}`),\n `${indent} };`,\n `${indent}},`,\n ];\n}\n\n/** Folds every enclosing root's lifecycle hooks into the one set the host reads. */\nfunction rootHooks(roots: readonly RootBinding[]): string | undefined {\n if (roots.length === 0) return undefined;\n return `...composeRootHooks(${roots.map((root) => root.declaration).join(', ')}),`;\n}\n\n/**\n * The headless entry, one declaration per scope.\n *\n * Contributions cascade downward here because the server does not do it\n * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the\n * scopes above it. Emitting the repetition is what lets an author declare a\n * channel once and have it mount at all three scopes.\n */\nexport function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n const allRoots = rootBindings(resolution.roots);\n\n const scopes: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = bindings.filter((b) => SCOPE_ORDER.indexOf(b.contribution.entry.scope) <= index);\n const here = hatches.filter((h) => SCOPE_ORDER.indexOf(h.entry.scope) <= index);\n // Each scope is an independent mount, so it constructs the roots that\n // enclose it from scratch rather than sharing the deeper scope's.\n const roots = allRoots.filter((root) => SCOPE_ORDER.indexOf(root.entry.scope) <= index);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(visible, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'server'),\n roots,\n 'server',\n ' ',\n scope,\n ),\n ...here.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n if (body.length === 0 && roots.length === 0) continue;\n if (roots.length > 0) usesRoots = true;\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...scopes,\n '});',\n '',\n 'export default facet;',\n '',\n ]);\n}\n\n/** The explicit remote-MCP entry. It intentionally imports only .mcp declarations. */\nexport function renderMcpEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const body = bodyFor(bindings, ' ', () => 'context', 'mcp');\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\n ...(bindings.some((binding) => binding.mcpWidget !== undefined)\n ? [\n 'const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({',\n ' ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },',\n '});',\n '',\n ]\n : []),\n 'export const mcp = defineMcpPlugin({',\n ` name: '${options.packageName}',`,\n ' session: (context) => ({',\n ...body,\n ' }) satisfies PoMcpSessionPlugin,',\n '});',\n '',\n 'export default mcp;',\n '',\n ]);\n}\n\n/** What differs between the two frontend entries: the SDK they import and the name they export. */\ninterface FrontendEntryShape {\n readonly module: string;\n readonly define: string;\n readonly exportName: string;\n}\n\nconst FRONTEND_ENTRY: Readonly<Record<FrontendTarget, FrontendEntryShape>> = {\n web: { module: '@agimon-ai/po-core/web', define: 'defineWebPlugin', exportName: 'webPlugin' },\n native: { module: '@agimon-ai/po-core/native', define: 'defineNativePlugin', exportName: 'nativePlugin' },\n};\n\n/**\n * A frontend entry, one contributions object per scope.\n *\n * No cascade here, unlike the server: the registry already folds global into\n * workspace into session before install, so repeating a contribution would\n * install it twice.\n */\nfunction renderFrontendEntry(resolution: TargetResolution, options: RenderOptions, target: FrontendTarget): string {\n const shape = FRONTEND_ENTRY[target];\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n\n const scopes: string[] = [];\n for (const scope of SCOPE_ORDER) {\n const visible = bindings.filter((b) => b.contribution.entry.scope === scope);\n const here = hatches.filter((h) => h.entry.scope === scope);\n const body = [\n ...bodyFor(visible, ' ', () => 'undefined', target),\n // Frontend escape hatches are contribution data. Calling them would also\n // call React components, so merge the authored object directly.\n ...here.map((hatch) => ` ...${hatch.identifier},`),\n ];\n if (body.length === 0) continue;\n scopes.push(` ${scope}: {`, ...body, ' },');\n }\n\n const names = scopes.some((line) => line.includes('get '))\n ? `${shape.define}, type ${CONTRIBUTIONS_TYPE[target]}`\n : shape.define;\n return compact([\n HEADER,\n `import { ${names} } from '${shape.module}';`,\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n `export const ${shape.exportName} = ${shape.define}({`,\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n\n/** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'web');\n}\n\n/** The native app entry, built from `.native` files only. */\nexport function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'native');\n}\n"],"mappings":"4GAQA,MAAMQ,EAAS,4DAGTC,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtFC,EAAmE,CACvE,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,OAAQ,CAAC,EACT,IAAK,CAAC,CACR,EAYMC,EAA2C,CAAC,UAAU,EAEtDC,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1EC,EAA4D,CAChE,OAAQ,wBACR,IAAK,yBAGL,OAAQ,yBACR,IAAK,oBACP,EAOA,SAASC,GAAmB,CAC1B,MAAO,CACL,0CACA,gEACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CAGA,SAASC,GAAuB,CAC9B,MAAO,CACL,6DACA,kGACA,kGACA,iEACA,IACF,CAAC,CAAC,KAAK;CAAI,CACb,CAEA,SAASC,GAA0B,CACjC,MAAO,CACL,yDACA,kEACA,8DACF,CAAC,CAAC,KAAK;CAAI,CACb,CAgBA,MAAMC,EAAkB,CACtB,2EACA,mFACF,CAAC,CAAC,KAAK;CAAI,EAWX,SAASC,EAAa,EAAc,EAAsC,CAExE,OADIC,IAAW,IAAA,GAAkB,CAAE,GAAInB,EAAAA,QAAQoB,CAAI,CAAE,EAC9C,CAAE,KAAMD,EAAQ,GAAInB,EAAAA,QAAQoB,CAAI,CAAE,CAC3C,CAGA,MAAMC,EAAyE,CAC7E,KAAO,IAAU,CAAE,KAAMpB,EAAAA,QAAQmB,CAAI,CAAE,GAIvC,QAAU,IAAU,CAAE,KAAMpB,EAAA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AAC,CACH,CAGA,SAAgB8C,EAAe,EAA8B,EAAgC,CAC3F,OAAOH,EAAoBtE,EAAYtB,EAAS,KAAK,CACvD,CAGA,SAAgBgG,EAAkB,EAA8B,EAAgC,CAC9F,OAAOJ,EAAoBtE,EAAYtB,EAAS,QAAQ,CAC1D"}
@@ -1,7 +1,7 @@
1
- import{isFrontendTarget as e}from"../resolveTarget/index.mjs";import{renderIdentity as t,toKebab as n,toSnake as r}from"../identity/index.mjs";import{posix as i}from"node:path";const a=`// Generated by @agimon-ai/po-build. Do not edit by hand.`,o=[`fileLinks`,`repositorySettingsPanel`,`start`],s={server:[`channels`],web:[],native:[],mcp:[]},c=[`services`],l=[`global`,`workspace`,`session`],u={server:`DoomServerSessionPlugin`,web:`WebPluginContributions`,native:`WebPluginContributions`,mcp:`DoomMcpSessionPlugin`};function d(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
1
+ import{isFrontendTarget as e}from"../resolveTarget/index.mjs";import{renderIdentity as t,toKebab as n,toSnake as r}from"../identity/index.mjs";import{posix as i}from"node:path";const a=`// Generated by @agimon-ai/po-build. Do not edit by hand.`,o=[`fileLinks`,`repositorySettingsPanel`,`start`],s={server:[`channels`],web:[],native:[],mcp:[]},c=[`services`],l=[`global`,`workspace`,`session`],u={server:`PoServerSessionPlugin`,web:`WebPluginContributions`,native:`WebPluginContributions`,mcp:`PoMcpSessionPlugin`};function d(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
2
2
  `)}function f(){return[`type ManyFactory<T, C> = (context: C) => T | readonly T[];`,`const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {`,` const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;`,` return Array.isArray(resolved) ? resolved : [resolved as T];`,`};`].join(`
3
3
  `)}function p(){return[`/* v8 ignore next -- generated normalization branch */`,`const defined = <T>(values: readonly (T | undefined)[]): T[] =>`,` values.filter((value): value is T => value !== undefined);`].join(`
4
4
  `)}const m=[`const via = <T>(identity: Record<string, unknown>, value: unknown): T =>`,` (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;`].join(`
5
- `);function h(e,t){return t===void 0?{id:n(e)}:{slot:t,id:n(e)}}const g={tool:e=>({name:r(e)}),command:e=>({name:n(e)}),channel:e=>({frameType:r(e)}),hook:e=>({event:r(e)}),mode:e=>({name:n(e)})},_={tool:e=>({tools:[r(e)]}),channel:e=>({channel:r(e)}),slot:(e,t)=>({slot:`${t.pluginId}.${n(e)}`}),command:e=>({id:n(e)}),tab:e=>({id:n(e)}),template:e=>({id:n(e)}),dock:e=>({id:n(e)}),setting:e=>({id:n(e)}),action:e=>({id:n(e)}),mode:e=>({name:n(e)}),"activity-group":e=>({name:n(e)}),"selection-axis":e=>({name:n(e)}),leader:(e,t)=>({id:`${t.pluginId}.${n(e)}`})};function v(t,n,r){let{entry:i}=t,a=i.surface;if(a!==void 0)return e(n)?a===`fill`?h(i.name,i.target):_[a]?.(i.name,r):g[a]?.(i.name)}function y(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function b(e,t){return y([e.entry.surface??`extra`,e.entry.name],t)}function x(e,t){let n=e.replace(/\.[^.]+$/u,``),r=i.relative(t,n);return r.startsWith(`.`)?r:`./${r}`}function S(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function C(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=b(r,n),a=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(a!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(a))throw Error(`Invalid MCP widget key '${a}'`);return{identifier:i,contribution:r,identity:v(r,e.target,t),mcpWidget:a}})}const w={global:0,workspace:1,session:2};function T(e){return e.map(e=>{let t=e.scope[0]?.toUpperCase()+e.scope.slice(1);return{identifier:`root${t}`,declaration:`scope${t}`,context:`context${t}`,entry:e}})}function E(e,t,n){let r=[],i=t;for(let[t,a]of e.entries())r.push(`const ${a.declaration} = await ${a.identifier}(${i});`),(t<e.length-1||n.some(e=>e.includes(a.context)))&&r.push(`const ${a.context} = { ...${i}, root: ${a.declaration}.value };`),i=a.context;return r}function D(e,t,n){let r=n;for(let n of e)w[n.entry.scope]<=w[t]&&(r=n.context);return r}function O(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function k(n,r,i){if(c.includes(n.contribution.field))return`${n.identifier}(${r})`;let a=e(i)?n.identifier:`at(${n.identifier}, ${r})`,o=s[i].includes(n.contribution.field);if(n.contribution.entry.cardinality===`collection`)return a;if(n.identity===void 0)return o?n.identifier:a;let l=t(n.identity);if(o)return`() => via({ ${l} }, ${n.identifier}())`;let u=`via({ ${l} }, ${a})`;return n.mcpWidget===void 0?u:`withWidget(${S(n.mcpWidget)}, ${u})`}function A(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/po-core/serverFacet';`}function j(e,t,n){if(e===`services`||t.startsWith(`...`))return t;let[r,...i]=t.split(`: `);return`get ${r}(): ${`${u[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function M(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.contribution.field);e===void 0?i.set(t.contribution.field,[t]):e.push(t)}let a=[];for(let e of[...i.keys()].sort()){let s=i.get(e);if(o.includes(e)){let i=s[0];if(i){let o=k(i,n(i),r);a.push(`${t}${j(e,`${e}: ${o},`,r)}`)}continue}let c=`[${s.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${n(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${S(e.mcpWidget)}, tool))`}`:k(e,n(e),r)).join(`, `)}]`,l=s.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${c})`:c;a.push(`${t}${j(e,`${e}: ${l},`,r)}`)}return a}function N(e,t,n,r,i){if(t.length===0)return[...e];let a=[...e],o=a.findIndex(e=>e.startsWith(`${r}services: [`)),s=o<0?``:a.splice(o,1)[0]?.match(/services: \[(.*)\],$/u)?.[1]??``,c=[...t.map(e=>`...(${e.declaration}.services ?? [])`),s].filter(Boolean).join(`, `);if(a.push(`${r}services: [${c}],`),n===`server`&&i===`session`){let e=a.findIndex(e=>e.startsWith(`${r}get activities()`)),n=e<0?``:a.splice(e,1)[0]?.match(/return \[(.*)\]; \},$/u)?.[1]??``,i=[...t.map(e=>`...(${e.declaration}.activities ?? [])`),n].filter(Boolean).join(`, `);a.push(`${r}get activities(): DoomServerSessionPlugin['activities'] { return [${i}]; },`)}return a}function P(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`),...e.map(e=>`import ${e.identifier} from '${x(e.contribution.entry.file,r)}';`),...t.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`)]}function F(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
6
- `)}function I(e){let t=[];return e.some(e=>e.includes(`at(`))&&t.push(d()),e.some(e=>e.includes(`many(`))&&t.push(f()),e.some(e=>e.includes(`defined(`))&&t.push(p()),e.some(e=>e.includes(`via(`))&&t.push(m),t.length>0?[...t,``]:[]}function L(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function R(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${L(n)} => ({`,...i,`${r}}),`]:[`${a}${L([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function z(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function B(e,t){let n=C(e,t),r=O(e.escapeHatches),i=T(e.roots),o=[],s=!1;for(let[e,t]of l.entries()){let a=n.filter(t=>l.indexOf(t.contribution.entry.scope)<=e),c=r.filter(t=>l.indexOf(t.entry.scope)<=e),u=i.filter(t=>l.indexOf(t.entry.scope)<=e),d=u[u.length-1]?.context??`context`,f=[...N(M(a,` `,e=>D(u,e.contribution.entry.scope,`context`),`server`),u,`server`,` `,t),...c.map(e=>` ...await at(${e.identifier}, ${d}),`)];if(f.length===0&&u.length===0)continue;u.length>0&&(s=!0);let p=R(E(u,`context`,f),z(u),f,` `);o.push(` ${t}: ${p[0]}`,...p.slice(1))}return F([a,A(o),...i.length?[`import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';`]:[],...s?[`import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';`]:[],``,...P(n,r,i,t.entryDir),``,...I(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...i.length?[` providerOverrides: composeServerProviderOverrides(${i.map(e=>e.identifier).join(`, `)}),`]:[],...o,`});`,``,`export default facet;`,``])}function V(e,t){let n=C(e,t),r=M(n,` `,()=>`context`,`mcp`);return F([a,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';`,``,...P(n,[],[],t.entryDir),``,...I(r),...n.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["po/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...r,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}const H={web:{module:`@agimon-ai/po-core/web`,define:`defineWebPlugin`,exportName:`webPlugin`},native:{module:`@agimon-ai/po-core/native`,define:`defineNativePlugin`,exportName:`nativePlugin`}};function U(e,t,n){let r=H[n],i=C(e,t),o=O(e.escapeHatches),s=[];for(let e of l){let t=i.filter(t=>t.contribution.entry.scope===e),r=o.filter(t=>t.entry.scope===e),a=[...M(t,` `,()=>`undefined`,n),...r.map(e=>` ...${e.identifier},`)];a.length!==0&&s.push(` ${e}: {`,...a,` },`)}let c=s.some(e=>e.includes(`get `))?`${r.define}, type ${u[n]}`:r.define;return F([a,`import { ${c} } from '${r.module}';`,``,...P(i,o,[],t.entryDir),``,...I(s),`export const ${r.exportName} = ${r.define}({`,` id: '${t.pluginId}',`,...s,`});`,``])}function W(e,t){return U(e,t,`web`)}function G(e,t){return U(e,t,`native`)}export{V as renderMcpEntry,G as renderNativeEntry,B as renderServerEntry,W as renderWebEntry};
5
+ `);function h(e,t){return t===void 0?{id:n(e)}:{slot:t,id:n(e)}}const g={tool:e=>({name:r(e)}),command:e=>({name:n(e)}),channel:e=>({frameType:r(e)}),hook:e=>({event:r(e)}),mode:e=>({name:n(e)})},_={tool:e=>({tools:[r(e)]}),channel:e=>({channel:r(e)}),slot:(e,t)=>({slot:`${t.pluginId}.${n(e)}`}),command:e=>({id:n(e)}),tab:e=>({id:n(e)}),template:e=>({id:n(e)}),dock:e=>({id:n(e)}),setting:e=>({id:n(e)}),action:e=>({id:n(e)}),mode:e=>({name:n(e)}),"activity-group":e=>({name:n(e)}),"selection-axis":e=>({name:n(e)}),leader:(e,t)=>({id:`${t.pluginId}.${n(e)}`})};function v(t,n,r){let{entry:i}=t,a=i.surface;if(a!==void 0)return e(n)?a===`fill`?h(i.name,i.target):_[a]?.(i.name,r):g[a]?.(i.name)}function y(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function b(e,t){return y([e.entry.surface??`extra`,e.entry.name],t)}function x(e,t){let n=e.replace(/\.[^.]+$/u,``),r=i.relative(t,n);return r.startsWith(`.`)?r:`./${r}`}function S(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function C(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=b(r,n),a=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(a!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(a))throw Error(`Invalid MCP widget key '${a}'`);return{identifier:i,contribution:r,identity:v(r,e.target,t),mcpWidget:a}})}const w={global:0,workspace:1,session:2};function T(e){return e.map(e=>{let t=e.scope[0]?.toUpperCase()+e.scope.slice(1);return{identifier:`root${t}`,declaration:`scope${t}`,context:`context${t}`,entry:e}})}function E(e,t,n){let r=[],i=t;for(let[t,a]of e.entries())r.push(`const ${a.declaration} = await ${a.identifier}(${i});`),(t<e.length-1||n.some(e=>e.includes(a.context)))&&r.push(`const ${a.context} = { ...${i}, root: ${a.declaration}.value };`),i=a.context;return r}function D(e,t,n){let r=n;for(let n of e)w[n.entry.scope]<=w[t]&&(r=n.context);return r}function O(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function k(n,r,i){if(c.includes(n.contribution.field))return`${n.identifier}(${r})`;let a=e(i)?n.identifier:`at(${n.identifier}, ${r})`,o=s[i].includes(n.contribution.field);if(n.contribution.entry.cardinality===`collection`)return a;if(n.identity===void 0)return o?n.identifier:a;let l=t(n.identity);if(o)return`() => via({ ${l} }, ${n.identifier}())`;let u=`via({ ${l} }, ${a})`;return n.mcpWidget===void 0?u:`withWidget(${S(n.mcpWidget)}, ${u})`}function A(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type PoServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/po-core/serverFacet';`}function j(e,t,n){if(e===`services`||t.startsWith(`...`))return t;let[r,...i]=t.split(`: `);return`get ${r}(): ${`${u[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function M(e,t,n,r){let i=/* @__PURE__ */ new Map;for(let t of e){let e=i.get(t.contribution.field);e===void 0?i.set(t.contribution.field,[t]):e.push(t)}let a=[];for(let e of[...i.keys()].sort()){let s=i.get(e);if(o.includes(e)){let i=s[0];if(i){let o=k(i,n(i),r);a.push(`${t}${j(e,`${e}: ${o},`,r)}`)}continue}let c=`[${s.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${n(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${S(e.mcpWidget)}, tool))`}`:k(e,n(e),r)).join(`, `)}]`,l=s.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${c})`:c;a.push(`${t}${j(e,`${e}: ${l},`,r)}`)}return a}function N(e,t,n,r,i){if(t.length===0)return[...e];let a=[...e],o=a.findIndex(e=>e.startsWith(`${r}services: [`)),s=o<0?``:a.splice(o,1)[0]?.match(/services: \[(.*)\],$/u)?.[1]??``,c=[...t.map(e=>`...(${e.declaration}.services ?? [])`),s].filter(Boolean).join(`, `);if(a.push(`${r}services: [${c}],`),n===`server`&&i===`session`){let e=a.findIndex(e=>e.startsWith(`${r}get activities()`)),n=e<0?``:a.splice(e,1)[0]?.match(/return \[(.*)\]; \},$/u)?.[1]??``,i=[...t.map(e=>`...(${e.declaration}.activities ?? [])`),n].filter(Boolean).join(`, `);a.push(`${r}get activities(): PoServerSessionPlugin['activities'] { return [${i}]; },`)}return a}function P(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`),...e.map(e=>`import ${e.identifier} from '${x(e.contribution.entry.file,r)}';`),...t.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`)]}function F(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
6
+ `)}function I(e){let t=[];return e.some(e=>e.includes(`at(`))&&t.push(d()),e.some(e=>e.includes(`many(`))&&t.push(f()),e.some(e=>e.includes(`defined(`))&&t.push(p()),e.some(e=>e.includes(`via(`))&&t.push(m),t.length>0?[...t,``]:[]}function L(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function R(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${L(n)} => ({`,...i,`${r}}),`]:[`${a}${L([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function z(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function B(e,t){let n=C(e,t),r=O(e.escapeHatches),i=T(e.roots),o=[],s=!1;for(let[e,t]of l.entries()){let a=n.filter(t=>l.indexOf(t.contribution.entry.scope)<=e),c=r.filter(t=>l.indexOf(t.entry.scope)<=e),u=i.filter(t=>l.indexOf(t.entry.scope)<=e),d=u[u.length-1]?.context??`context`,f=[...N(M(a,` `,e=>D(u,e.contribution.entry.scope,`context`),`server`),u,`server`,` `,t),...c.map(e=>` ...await at(${e.identifier}, ${d}),`)];if(f.length===0&&u.length===0)continue;u.length>0&&(s=!0);let p=R(E(u,`context`,f),z(u),f,` `);o.push(` ${t}: ${p[0]}`,...p.slice(1))}return F([a,A(o),...i.length?[`import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';`]:[],...s?[`import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';`]:[],``,...P(n,r,i,t.entryDir),``,...I(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...i.length?[` providerOverrides: composeServerProviderOverrides(${i.map(e=>e.identifier).join(`, `)}),`]:[],...o,`});`,``,`export default facet;`,``])}function V(e,t){let n=C(e,t),r=M(n,` `,()=>`context`,`mcp`);return F([a,`import { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';`,``,...P(n,[],[],t.entryDir),``,...I(r),...n.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["po/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...r,` }) satisfies PoMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}const H={web:{module:`@agimon-ai/po-core/web`,define:`defineWebPlugin`,exportName:`webPlugin`},native:{module:`@agimon-ai/po-core/native`,define:`defineNativePlugin`,exportName:`nativePlugin`}};function U(e,t,n){let r=H[n],i=C(e,t),o=O(e.escapeHatches),s=[];for(let e of l){let t=i.filter(t=>t.contribution.entry.scope===e),r=o.filter(t=>t.entry.scope===e),a=[...M(t,` `,()=>`undefined`,n),...r.map(e=>` ...${e.identifier},`)];a.length!==0&&s.push(` ${e}: {`,...a,` },`)}let c=s.some(e=>e.includes(`get `))?`${r.define}, type ${u[n]}`:r.define;return F([a,`import { ${c} } from '${r.module}';`,``,...P(i,o,[],t.entryDir),``,...I(s),`export const ${r.exportName} = ${r.define}({`,` id: '${t.pluginId}',`,...s,`});`,``])}function W(e,t){return U(e,t,`web`)}function G(e,t){return U(e,t,`native`)}export{V as renderMcpEntry,G as renderNativeEntry,B as renderServerEntry,W as renderWebEntry};
7
7
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["HEADER","SINGLETON_FIELDS","FACTORY_FIELDS","ALWAYS_FACTORY_FIELDS","SCOPE_ORDER","CONTRIBUTIONS_TYPE","resolver","manyResolver","definedResolver","IDENTITY_HELPER","fillIdentity","target","toKebab","name","BACKEND_IDENTITY","toSnake","FRONTEND_IDENTITY","options","identityFor","contribution","surface","entry","isFrontendTarget","uniqueIdentifier","head","parts","word","index","base","candidate","suffix","taken","identifierFor","specifierFor","file","relative","posix","entryDir","widgetLiteral","key","bind","resolution","left","right","identifier","mcpWidget","DEPTH","rootBindings","entries","rootPrologue","lines","enclosing","root","roots","body","line","contextForScope","found","scope","hatchBindings","member","binding","contextExpression","resolved","isFactory","identity","renderIdentity","value","serverImport","scopes","defer","field","rendered","bodyFor","grouped","bindings","held","members","contextOf","indent","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","usesRoots","visible","here","innermost","hatch","factory","renderMcpEntry","FRONTEND_ENTRY","renderFrontendEntry","shape","names","renderWebEntry","renderNativeEntry"],"sources":["../../../src/services/renderEntry/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionEntry, ExtensionScope } from '../../types/extensionGraph';\nimport { type Identity, renderIdentity, toKebab, toSnake } from '../identity';\nimport { isFrontendTarget } from '../resolveTarget';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Fields that accept one declaration rather than an array of declarations. */\nconst SINGLETON_FIELDS: readonly string[] = ['fileLinks', 'repositorySettingsPanel', 'start'];\n\n/**\n * Fields whose members are factories rather than declarations.\n *\n * Keyed by target, not by field name alone, because `channels` means two\n * different things. A server facet's array holds `() => DoomHubChannel`, so\n * the host can build one per mount. The cockpit's holds the contribution\n * itself. Treating them alike called a plain object as a function.\n */\nconst FACTORY_FIELDS: Readonly<Record<BuildTarget, readonly string[]>> = {\n server: ['channels'],\n web: [],\n native: [],\n mcp: [],\n};\n\n/**\n * Fields whose member is always a factory of the value, never the value.\n *\n * A Cordis plugin is itself a function, so nothing at runtime separates one\n * from a `(context) => plugin` factory. Rather than guess, the service surface\n * is uniformly a factory and is always called. That is also what lets a\n * package with shared per-mount state decompose: the service builds the graph\n * from the mount and publishes it, and every other contribution is a getter,\n * so it is built after the service fibers are up and can inject it.\n */\nconst ALWAYS_FACTORY_FIELDS: readonly string[] = ['services'];\n\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/**\n * Resolves a routed file's default export, which may be the declaration or a\n * factory of one. Both host helpers already accept either shape, so a\n * generated entry has to as well. Emitted rather than imported, so a generated\n * entry carries no runtime dependency beyond the helper it is calling.\n */\n/** The contribution set each host reads, used to annotate the emitted getters. */\nconst CONTRIBUTIONS_TYPE: Readonly<Record<BuildTarget, string>> = {\n server: 'DoomServerSessionPlugin',\n web: 'WebPluginContributions',\n // The native app reuses the cockpit's plugin registry, so its contributions\n // are the same type, re-exported from the native SDK.\n native: 'WebPluginContributions',\n mcp: 'DoomMcpSessionPlugin',\n};\n\n/**\n * Resolves a routed file's default export without imposing one host context on\n * every factory. The generated mount supplies the concrete context, and `at`\n * preserves that type while still accepting declaration objects.\n */\nfunction resolver(): string {\n return [\n 'type Factory<T, C> = (context: C) => T;',\n 'const at = <T, C>(value: T | Factory<T, C>, context: C): T =>',\n \" typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\",\n ].join('\\n');\n}\n\n/** Resolves a zero-many catalog contribution without flattening tuple declarations. */\nfunction manyResolver(): string {\n return [\n 'type ManyFactory<T, C> = (context: C) => T | readonly T[];',\n 'const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {',\n \" const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;\",\n ' return Array.isArray(resolved) ? resolved : [resolved as T];',\n '};',\n ].join('\\n');\n}\n\nfunction definedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const defined = <T>(values: readonly (T | undefined)[]): T[] =>',\n ' values.filter((value): value is T => value !== undefined);',\n ].join('\\n');\n}\n\n/**\n * Applies the identity the path derived, letting the authored value win.\n *\n * A call rather than an object literal on purpose. `{ name: 'x', ...value }`\n * is what this means, but TypeScript reports TS2783 whenever the spread's type\n * also declares the key, which is the common case here.\n *\n * The parameters are deliberately untyped so `T` is inferred from the\n * contribution array this sits in rather than from either argument: the\n * authored file supplies only the half the path cannot. The cost is that the\n * merged shape is not checked against `T`, only its position is.\n */\n// Preserve absence before applying a path-derived name. Otherwise optional routes\n// become incomplete placeholder tools or hooks that the `defined` filter cannot remove.\nconst IDENTITY_HELPER = [\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T =>',\n ' (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;',\n].join('\\n');\n\n/**\n * Every fill is a slot fill. There is no host-region special case.\n *\n * The cockpit's own regions are slots like any other: an activity section\n * already renders into `activity.<group>`, which is why naming the target\n * directly works for a host region and a plugin's slot alike. Keeping this\n * uniform is what lets a layout package declare new regions without the build\n * tooling learning about them.\n */\nfunction fillIdentity(name: string, target: string | undefined): Identity {\n if (target === undefined) return { id: toKebab(name) };\n return { slot: target, id: toKebab(name) };\n}\n\n/** What the path can tell each host, keyed by the folder the author typed. */\nconst BACKEND_IDENTITY: Readonly<Record<string, (name: string) => Identity>> = {\n tool: (name) => ({ name: toSnake(name) }),\n // Kebab, unlike a tool. A command name is what the user types after the\n // slash and it reaches registerCommand verbatim, so `subagents-doctor` must\n // stay `/subagents-doctor` rather than becoming `/subagents_doctor`.\n command: (name) => ({ name: toKebab(name) }),\n channel: (name) => ({ frameType: toSnake(name) }),\n hook: (name) => ({ event: toSnake(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n};\n\nconst FRONTEND_IDENTITY: Readonly<Record<string, (name: string, options: RenderOptions) => Identity>> = {\n tool: (name) => ({ tools: [toSnake(name)] }),\n channel: (name) => ({ channel: toSnake(name) }),\n slot: (name, options) => ({ slot: `${options.pluginId}.${toKebab(name)}` }),\n command: (name) => ({ id: toKebab(name) }),\n tab: (name) => ({ id: toKebab(name) }),\n template: (name) => ({ id: toKebab(name) }),\n dock: (name) => ({ id: toKebab(name) }),\n setting: (name) => ({ id: toKebab(name) }),\n action: (name) => ({ id: toKebab(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n 'activity-group': (name) => ({ name: toKebab(name) }),\n 'selection-axis': (name) => ({ name: toKebab(name) }),\n // A leader binding's id is namespaced like a slot, because the key tree is\n // shared and two plugins must not collide on one path's identity.\n leader: (name, options) => ({ id: `${options.pluginId}.${toKebab(name)}` }),\n};\n\n/**\n * What the path knows about a contribution's identity.\n *\n * Keyed by surface, because the folder is what the author types. A surface\n * absent from the table, or an identity the path cannot supply such as a tab's\n * human label, is left entirely to the authored file.\n */\nfunction identityFor(\n contribution: ResolvedContribution,\n target: BuildTarget,\n options: RenderOptions,\n): Identity | undefined {\n const { entry } = contribution;\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n if (!isFrontendTarget(target)) return BACKEND_IDENTITY[surface]?.(entry.name);\n if (surface === 'fill') return fillIdentity(entry.name, entry.target);\n return FRONTEND_IDENTITY[surface]?.(entry.name, options);\n}\n\n/** A stable, unique, valid identifier built from path words. */\nfunction uniqueIdentifier(parts: readonly string[], taken: Set<string>): string {\n const words = parts\n .join('-')\n .split(/[^A-Za-z0-9]+/u)\n .filter((word) => word.length > 0);\n const head = words.map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1))).join('');\n const base = /^[A-Za-z_]/u.test(head) ? head : `x${head}`;\n let candidate = base;\n let suffix = 2;\n while (taken.has(candidate)) candidate = `${base}${suffix++}`;\n taken.add(candidate);\n return candidate;\n}\n\n/** A stable, unique, valid identifier: surface and name, disambiguated by scope when needed. */\nfunction identifierFor(contribution: ResolvedContribution, taken: Set<string>): string {\n return uniqueIdentifier([contribution.entry.surface ?? 'extra', contribution.entry.name], taken);\n}\n\n/** The extensionless relative specifier from a generated entry to a routed file. */\nfunction specifierFor(file: string, entryDir: string): string {\n const target = file.replace(/\\.[^.]+$/u, '');\n const relative = posix.relative(entryDir, target);\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\ninterface Binding {\n readonly identifier: string;\n readonly contribution: ResolvedContribution;\n readonly identity: Identity | undefined;\n readonly mcpWidget: string | undefined;\n}\n\n/** Encode data for generated JavaScript, including the HTML script boundary. */\nfunction widgetLiteral(key: string): string {\n return JSON.stringify(key).replaceAll('<', '\\\\u003c').replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029');\n}\n\nfunction bind(resolution: TargetResolution, options: RenderOptions): Binding[] {\n const taken = new Set<string>();\n return [...resolution.contributions]\n .sort((left, right) => left.entry.file.localeCompare(right.entry.file))\n .map((contribution) => {\n // The contribution takes its identifier first, so the plain name stays\n // with the tool rather than going to whichever file sorted earlier.\n const identifier = identifierFor(contribution, taken);\n const mcpWidget = resolution.target === 'mcp' ? options.mcpWidgets?.[contribution.entry.file] : undefined;\n if (mcpWidget !== undefined && !/^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*\\/[a-z0-9_]+$/u.test(mcpWidget))\n throw new Error(`Invalid MCP widget key '${mcpWidget}'`);\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n mcpWidget,\n };\n });\n}\n\n/** Scope nesting depth, so a contribution can find the root that encloses it. */\nconst DEPTH: Readonly<Record<ExtensionScope, number>> = { global: 0, workspace: 1, session: 2 };\n\ninterface RootBinding {\n /** The imported factory. */\n readonly identifier: string;\n /** The declaration it returned: `value` plus this scope's lifecycle hooks. */\n readonly declaration: string;\n /** The mount context contributions beneath this root receive. */\n readonly context: string;\n readonly entry: ExtensionEntry;\n}\n\nfunction rootBindings(entries: readonly ExtensionEntry[]): RootBinding[] {\n return entries.map((entry) => {\n const suffix = entry.scope[0]?.toUpperCase() + entry.scope.slice(1);\n return { identifier: `root${suffix}`, declaration: `scope${suffix}`, context: `context${suffix}`, entry };\n });\n}\n\n/**\n * Constructs each scope before anything it contains, outermost first.\n *\n * Every root is handed the context its enclosing root produced. Root factories\n * may be async, so the generated host factory awaits each one before exposing\n * its value to narrower contributions.\n */\nfunction rootPrologue(roots: readonly RootBinding[], base: string, body: readonly string[]): string[] {\n const lines: string[] = [];\n let enclosing = base;\n for (const [index, root] of roots.entries()) {\n lines.push(`const ${root.declaration} = await ${root.identifier}(${enclosing});`);\n const contextIsUsed = index < roots.length - 1 || body.some((line) => line.includes(root.context));\n if (contextIsUsed) lines.push(`const ${root.context} = { ...${enclosing}, root: ${root.declaration}.value };`);\n enclosing = root.context;\n }\n return lines;\n}\n\n/** The context a contribution sees: the nearest enclosing root's, or the mount's. */\nfunction contextForScope(roots: readonly RootBinding[], scope: ExtensionScope, base: string): string {\n let found = base;\n for (const root of roots) {\n if (DEPTH[root.entry.scope] <= DEPTH[scope]) found = root.context;\n }\n return found;\n}\n\nfunction hatchBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n return [...entries]\n .sort((left, right) => left.file.localeCompare(right.file))\n .map((entry, index) => ({ identifier: `extra${index === 0 ? '' : index + 1}`, entry }));\n}\n\n/**\n * One contribution as it appears inside its array, identity first so the file wins.\n *\n * The browser half is never resolved. The cockpit builds its definition as\n * data and starts it separately, so a frontend file has no mount context to\n * receive, and resolving anyway would call any export that happens to be a\n * function. A React component is a function, so that is not hypothetical.\n */\nfunction member(binding: Binding, contextExpression: string, target: BuildTarget): string {\n if (ALWAYS_FACTORY_FIELDS.includes(binding.contribution.field)) {\n return `${binding.identifier}(${contextExpression})`;\n }\n\n const resolved = isFrontendTarget(target) ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n const isFactory = FACTORY_FIELDS[target].includes(binding.contribution.field);\n // A live collection is the contribution container itself. Applying a path\n // identity would spread class instances into plain objects and can erase\n // prototype-backed snapshot/subscribe methods.\n if (binding.contribution.entry.cardinality === 'collection') return resolved;\n if (binding.identity === undefined) return isFactory ? binding.identifier : resolved;\n\n const identity = renderIdentity(binding.identity);\n // A channel array holds factories, so the identity is applied inside one.\n if (isFactory) return `() => via({ ${identity} }, ${binding.identifier}())`;\n const value = `via({ ${identity} }, ${resolved})`;\n return binding.mcpWidget === undefined ? value : `withWidget(${widgetLiteral(binding.mcpWidget)}, ${value})`;\n}\n\n/** The server entry imports only the types its scopes actually use. */\nfunction serverImport(scopes: readonly string[]): string {\n const types = scopes.some((line) => line.includes('get ')) ? ['type DoomServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverFacet';`;\n}\n\n/**\n * Emits a contribution as a getter, so it is built after services mount.\n *\n * Both host helpers register `services` first and read every other field\n * afterwards. A plain property would be evaluated when the entry's factory\n * returns, which is before any service exists, so a routed file could never\n * inject one at construction and every package with shared per-mount state\n * would be stuck in one closure.\n *\n * `services` itself stays a plain property: it is what the helper reads first,\n * and a getter for it would buy nothing.\n */\nfunction defer(field: string, rendered: string, target: BuildTarget): string {\n if (field === 'services' || rendered.startsWith('...')) return rendered;\n const [name, ...value] = rendered.split(': ');\n // Annotated, because a getter gets no contextual type from the object\n // literal it sits in, so the identity helper's T would widen to unknown and\n // the contribution would stop type checking against the array it joins.\n const type = `${CONTRIBUTIONS_TYPE[target]}['${name}']`;\n return `get ${name}(): ${type} { return ${value.join(': ').replace(/,$/u, '')}; },`;\n}\n\n/**\n * The contributions object's body.\n *\n * The mount context is resolved per contribution rather than once, because a\n * root rebinds it for everything beneath it and two contributions at different\n * scopes can therefore see different contexts in the same object.\n */\nfunction bodyFor(\n bindings: readonly Binding[],\n indent: string,\n contextOf: (binding: Binding) => string,\n target: BuildTarget,\n): string[] {\n const grouped = new Map<string, Binding[]>();\n for (const binding of bindings) {\n const held = grouped.get(binding.contribution.field);\n if (held === undefined) grouped.set(binding.contribution.field, [binding]);\n else held.push(binding);\n }\n\n const lines: string[] = [];\n for (const field of [...grouped.keys()].sort()) {\n const members = grouped.get(field) as Binding[];\n if (SINGLETON_FIELDS.includes(field)) {\n const entry = members[0];\n if (entry) {\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n continue;\n }\n const renderedMembers = members.map((entry) =>\n entry.contribution.entry.cardinality === 'many'\n ? `...many(${entry.identifier}, ${contextOf(entry)})${entry.mcpWidget === undefined ? '' : `.map((tool) => withWidget(${widgetLiteral(entry.mcpWidget)}, tool))`}`\n : member(entry, contextOf(entry), target),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const rendered = members.some((entry) => entry.contribution.entry.cardinality === 'optional')\n ? `defined(${entries})`\n : entries;\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n return lines;\n}\n\n/** Root-owned registrations join routed registrations in the host's usual fields. */\nfunction withRootRegistrations(\n body: readonly string[],\n roots: readonly RootBinding[],\n target: 'server',\n indent: string,\n scope: ExtensionScope,\n): string[] {\n if (roots.length === 0) return [...body];\n const lines = [...body];\n const servicesIndex = lines.findIndex((line) => line.startsWith(`${indent}services: [`));\n const routedServices =\n servicesIndex < 0 ? '' : (lines.splice(servicesIndex, 1)[0]?.match(/services: \\[(.*)\\],$/u)?.[1] ?? '');\n const services = [...roots.map((root) => `...(${root.declaration}.services ?? [])`), routedServices]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}services: [${services}],`);\n\n if (target === 'server' && scope === 'session') {\n const activitiesIndex = lines.findIndex((line) => line.startsWith(`${indent}get activities()`));\n const routedActivities =\n activitiesIndex < 0 ? '' : (lines.splice(activitiesIndex, 1)[0]?.match(/return \\[(.*)\\]; \\},$/u)?.[1] ?? '');\n const activities = [...roots.map((root) => `...(${root.declaration}.activities ?? [])`), routedActivities]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}get activities(): DoomServerSessionPlugin['activities'] { return [${activities}]; },`);\n }\n return lines;\n}\n\nfunction importsFor(\n bindings: readonly Binding[],\n hatches: readonly { identifier: string; entry: ExtensionEntry }[],\n roots: readonly RootBinding[],\n entryDir: string,\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...bindings.map((b) => `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`),\n ...hatches.map((h) => `import ${h.identifier} from '${specifierFor(h.entry.file, entryDir)}';`),\n ];\n}\n\nfunction compact(lines: readonly string[]): string {\n return lines.filter((line, index, all) => !(line === '' && all[index - 1] === '')).join('\\n');\n}\n\n/**\n * Emits the resolver only when something calls it.\n *\n * Extension packages compile with noUnusedLocals, so a generated entry whose\n * every contribution is a factory would otherwise fail to typecheck on an\n * unused helper.\n */\nfunction resolverFor(body: readonly string[]): string[] {\n const lines: string[] = [];\n if (body.some((line) => line.includes('at('))) lines.push(resolver());\n if (body.some((line) => line.includes('many('))) lines.push(manyResolver());\n if (body.some((line) => line.includes('defined('))) lines.push(definedResolver());\n if (body.some((line) => line.includes('via('))) lines.push(IDENTITY_HELPER);\n return lines.length > 0 ? [...lines, ''] : [];\n}\n\n/** `noUnusedParameters` means a scope that never threads context takes none. */\nfunction parameterFor(lines: readonly string[]): string {\n return lines.some((line) => line.includes(', context)') || line.includes('(context)')) ? '(context)' : '()';\n}\n\n/**\n * The scope's factory: an expression body, or a block when roots come first.\n *\n * A root has to be constructed before the object that reads it, so a scope\n * that has one becomes statements followed by a return rather than a bare\n * object literal.\n */\nfunction scopeBody(\n prologue: readonly string[],\n hooks: string | undefined,\n body: readonly string[],\n indent: string,\n): string[] {\n const object = [...(hooks === undefined ? [] : [`${indent} ${hooks}`]), ...body];\n const asynchronous = [...prologue, ...body].some((line) => line.includes('await '));\n const prefix = asynchronous ? 'async ' : '';\n if (prologue.length === 0) return [`${prefix}${parameterFor(body)} => ({`, ...object, `${indent}}),`];\n return [\n `${prefix}${parameterFor([...prologue, ...body])} => {`,\n ...prologue.map((line) => `${indent} ${line}`),\n `${indent} return {`,\n ...object.map((line) => ` ${line}`),\n `${indent} };`,\n `${indent}},`,\n ];\n}\n\n/** Folds every enclosing root's lifecycle hooks into the one set the host reads. */\nfunction rootHooks(roots: readonly RootBinding[]): string | undefined {\n if (roots.length === 0) return undefined;\n return `...composeRootHooks(${roots.map((root) => root.declaration).join(', ')}),`;\n}\n\n/**\n * The headless entry, one declaration per scope.\n *\n * Contributions cascade downward here because the server does not do it\n * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the\n * scopes above it. Emitting the repetition is what lets an author declare a\n * channel once and have it mount at all three scopes.\n */\nexport function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n const allRoots = rootBindings(resolution.roots);\n\n const scopes: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = bindings.filter((b) => SCOPE_ORDER.indexOf(b.contribution.entry.scope) <= index);\n const here = hatches.filter((h) => SCOPE_ORDER.indexOf(h.entry.scope) <= index);\n // Each scope is an independent mount, so it constructs the roots that\n // enclose it from scratch rather than sharing the deeper scope's.\n const roots = allRoots.filter((root) => SCOPE_ORDER.indexOf(root.entry.scope) <= index);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(visible, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'server'),\n roots,\n 'server',\n ' ',\n scope,\n ),\n ...here.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n if (body.length === 0 && roots.length === 0) continue;\n if (roots.length > 0) usesRoots = true;\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...scopes,\n '});',\n '',\n 'export default facet;',\n '',\n ]);\n}\n\n/** The explicit remote-MCP entry. It intentionally imports only .mcp declarations. */\nexport function renderMcpEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const body = bodyFor(bindings, ' ', () => 'context', 'mcp');\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\n ...(bindings.some((binding) => binding.mcpWidget !== undefined)\n ? [\n 'const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({',\n ' ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },',\n '});',\n '',\n ]\n : []),\n 'export const mcp = defineMcpPlugin({',\n ` name: '${options.packageName}',`,\n ' session: (context) => ({',\n ...body,\n ' }) satisfies DoomMcpSessionPlugin,',\n '});',\n '',\n 'export default mcp;',\n '',\n ]);\n}\n\n/** What differs between the two frontend entries: the SDK they import and the name they export. */\ninterface FrontendEntryShape {\n readonly module: string;\n readonly define: string;\n readonly exportName: string;\n}\n\nconst FRONTEND_ENTRY: Readonly<Record<FrontendTarget, FrontendEntryShape>> = {\n web: { module: '@agimon-ai/po-core/web', define: 'defineWebPlugin', exportName: 'webPlugin' },\n native: { module: '@agimon-ai/po-core/native', define: 'defineNativePlugin', exportName: 'nativePlugin' },\n};\n\n/**\n * A frontend entry, one contributions object per scope.\n *\n * No cascade here, unlike the server: the registry already folds global into\n * workspace into session before install, so repeating a contribution would\n * install it twice.\n */\nfunction renderFrontendEntry(resolution: TargetResolution, options: RenderOptions, target: FrontendTarget): string {\n const shape = FRONTEND_ENTRY[target];\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n\n const scopes: string[] = [];\n for (const scope of SCOPE_ORDER) {\n const visible = bindings.filter((b) => b.contribution.entry.scope === scope);\n const here = hatches.filter((h) => h.entry.scope === scope);\n const body = [\n ...bodyFor(visible, ' ', () => 'undefined', target),\n // Frontend escape hatches are contribution data. Calling them would also\n // call React components, so merge the authored object directly.\n ...here.map((hatch) => ` ...${hatch.identifier},`),\n ];\n if (body.length === 0) continue;\n scopes.push(` ${scope}: {`, ...body, ' },');\n }\n\n const names = scopes.some((line) => line.includes('get '))\n ? `${shape.define}, type ${CONTRIBUTIONS_TYPE[target]}`\n : shape.define;\n return compact([\n HEADER,\n `import { ${names} } from '${shape.module}';`,\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n `export const ${shape.exportName} = ${shape.define}({`,\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n\n/** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'web');\n}\n\n/** The native app entry, built from `.native` files only. */\nexport function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'native');\n}\n"],"mappings":"iLAQA,MAAMA,EAAS,4DAGTC,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtFC,EAAmE,CACvE,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,OAAQ,CAAC,EACT,IAAK,CAAC,CACR,EAYMC,EAA2C,CAAC,UAAU,EAEtDC,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1EC,EAA4D,CAChE,OAAQ,0BACR,IAAK,yBAGL,OAAQ,yB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A,IAAM4D,EAAQ7C,EAAO,KAAM,GAASd,EAAK,SAAS,MAAM,CAAC,EACrD,GAAG0D,EAAM,OAAO,SAAS5G,EAAmBM,KAC5CsG,EAAM,OACV,OAAOrB,EAAQ,CACb5F,EACA,YAAYkH,EAAM,WAAWD,EAAM,OAAO,IAC1C,GACA,GAAG1B,EAAWZ,EAAUe,EAAS,CAAC,EAAGzE,EAAQ,QAAQ,EACrD,GACA,GAAG6E,EAAYzB,CAAM,EACrB,gBAAgB4C,EAAM,WAAW,KAAKA,EAAM,OAAO,IACnD,UAAUhG,EAAQ,SAAS,IAC3B,GAAGoD,EACH,MACA,EACF,CAAC,CACH,CAGA,SAAgB8C,EAAe,EAA8B,EAAgC,CAC3F,OAAOH,EAAoBvE,EAAYxB,EAAS,KAAK,CACvD,CAGA,SAAgBmG,EAAkB,EAA8B,EAAgC,CAC9F,OAAOJ,EAAoBvE,EAAYxB,EAAS,QAAQ,CAC1D"}
1
+ {"version":3,"file":"index.mjs","names":["HEADER","SINGLETON_FIELDS","FACTORY_FIELDS","ALWAYS_FACTORY_FIELDS","SCOPE_ORDER","CONTRIBUTIONS_TYPE","resolver","manyResolver","definedResolver","IDENTITY_HELPER","fillIdentity","target","toKebab","name","BACKEND_IDENTITY","toSnake","FRONTEND_IDENTITY","options","identityFor","contribution","surface","entry","isFrontendTarget","uniqueIdentifier","head","parts","word","index","base","candidate","suffix","taken","identifierFor","specifierFor","file","relative","posix","entryDir","widgetLiteral","key","bind","resolution","left","right","identifier","mcpWidget","DEPTH","rootBindings","entries","rootPrologue","lines","enclosing","root","roots","body","line","contextForScope","found","scope","hatchBindings","member","binding","contextExpression","resolved","isFactory","identity","renderIdentity","value","serverImport","scopes","defer","field","rendered","bodyFor","grouped","bindings","held","members","contextOf","indent","withRootRegistrations","servicesIndex","routedServices","services","activitiesIndex","routedActivities","activities","importsFor","r","b","hatches","h","compact","all","resolverFor","parameterFor","scopeBody","object","hooks","prefix","prologue","rootHooks","renderServerEntry","allRoots","usesRoots","visible","here","innermost","hatch","factory","renderMcpEntry","FRONTEND_ENTRY","renderFrontendEntry","shape","names","renderWebEntry","renderNativeEntry"],"sources":["../../../src/services/renderEntry/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionEntry, ExtensionScope } from '../../types/extensionGraph';\nimport { type Identity, renderIdentity, toKebab, toSnake } from '../identity';\nimport { isFrontendTarget } from '../resolveTarget';\nimport type { BuildTarget, FrontendTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/po-build. Do not edit by hand.';\n\n/** Fields that accept one declaration rather than an array of declarations. */\nconst SINGLETON_FIELDS: readonly string[] = ['fileLinks', 'repositorySettingsPanel', 'start'];\n\n/**\n * Fields whose members are factories rather than declarations.\n *\n * Keyed by target, not by field name alone, because `channels` means two\n * different things. A server facet's array holds `() => PoHubChannel`, so\n * the host can build one per mount. The cockpit's holds the contribution\n * itself. Treating them alike called a plain object as a function.\n */\nconst FACTORY_FIELDS: Readonly<Record<BuildTarget, readonly string[]>> = {\n server: ['channels'],\n web: [],\n native: [],\n mcp: [],\n};\n\n/**\n * Fields whose member is always a factory of the value, never the value.\n *\n * A Cordis plugin is itself a function, so nothing at runtime separates one\n * from a `(context) => plugin` factory. Rather than guess, the service surface\n * is uniformly a factory and is always called. That is also what lets a\n * package with shared per-mount state decompose: the service builds the graph\n * from the mount and publishes it, and every other contribution is a getter,\n * so it is built after the service fibers are up and can inject it.\n */\nconst ALWAYS_FACTORY_FIELDS: readonly string[] = ['services'];\n\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/**\n * Resolves a routed file's default export, which may be the declaration or a\n * factory of one. Both host helpers already accept either shape, so a\n * generated entry has to as well. Emitted rather than imported, so a generated\n * entry carries no runtime dependency beyond the helper it is calling.\n */\n/** The contribution set each host reads, used to annotate the emitted getters. */\nconst CONTRIBUTIONS_TYPE: Readonly<Record<BuildTarget, string>> = {\n server: 'PoServerSessionPlugin',\n web: 'WebPluginContributions',\n // The native app reuses the cockpit's plugin registry, so its contributions\n // are the same type, re-exported from the native SDK.\n native: 'WebPluginContributions',\n mcp: 'PoMcpSessionPlugin',\n};\n\n/**\n * Resolves a routed file's default export without imposing one host context on\n * every factory. The generated mount supplies the concrete context, and `at`\n * preserves that type while still accepting declaration objects.\n */\nfunction resolver(): string {\n return [\n 'type Factory<T, C> = (context: C) => T;',\n 'const at = <T, C>(value: T | Factory<T, C>, context: C): T =>',\n \" typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\",\n ].join('\\n');\n}\n\n/** Resolves a zero-many catalog contribution without flattening tuple declarations. */\nfunction manyResolver(): string {\n return [\n 'type ManyFactory<T, C> = (context: C) => T | readonly T[];',\n 'const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {',\n \" const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;\",\n ' return Array.isArray(resolved) ? resolved : [resolved as T];',\n '};',\n ].join('\\n');\n}\n\nfunction definedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const defined = <T>(values: readonly (T | undefined)[]): T[] =>',\n ' values.filter((value): value is T => value !== undefined);',\n ].join('\\n');\n}\n\n/**\n * Applies the identity the path derived, letting the authored value win.\n *\n * A call rather than an object literal on purpose. `{ name: 'x', ...value }`\n * is what this means, but TypeScript reports TS2783 whenever the spread's type\n * also declares the key, which is the common case here.\n *\n * The parameters are deliberately untyped so `T` is inferred from the\n * contribution array this sits in rather than from either argument: the\n * authored file supplies only the half the path cannot. The cost is that the\n * merged shape is not checked against `T`, only its position is.\n */\n// Preserve absence before applying a path-derived name. Otherwise optional routes\n// become incomplete placeholder tools or hooks that the `defined` filter cannot remove.\nconst IDENTITY_HELPER = [\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T =>',\n ' (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;',\n].join('\\n');\n\n/**\n * Every fill is a slot fill. There is no host-region special case.\n *\n * The cockpit's own regions are slots like any other: an activity section\n * already renders into `activity.<group>`, which is why naming the target\n * directly works for a host region and a plugin's slot alike. Keeping this\n * uniform is what lets a layout package declare new regions without the build\n * tooling learning about them.\n */\nfunction fillIdentity(name: string, target: string | undefined): Identity {\n if (target === undefined) return { id: toKebab(name) };\n return { slot: target, id: toKebab(name) };\n}\n\n/** What the path can tell each host, keyed by the folder the author typed. */\nconst BACKEND_IDENTITY: Readonly<Record<string, (name: string) => Identity>> = {\n tool: (name) => ({ name: toSnake(name) }),\n // Kebab, unlike a tool. A command name is what the user types after the\n // slash and it reaches registerCommand verbatim, so `subagents-doctor` must\n // stay `/subagents-doctor` rather than becoming `/subagents_doctor`.\n command: (name) => ({ name: toKebab(name) }),\n channel: (name) => ({ frameType: toSnake(name) }),\n hook: (name) => ({ event: toSnake(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n};\n\nconst FRONTEND_IDENTITY: Readonly<Record<string, (name: string, options: RenderOptions) => Identity>> = {\n tool: (name) => ({ tools: [toSnake(name)] }),\n channel: (name) => ({ channel: toSnake(name) }),\n slot: (name, options) => ({ slot: `${options.pluginId}.${toKebab(name)}` }),\n command: (name) => ({ id: toKebab(name) }),\n tab: (name) => ({ id: toKebab(name) }),\n template: (name) => ({ id: toKebab(name) }),\n dock: (name) => ({ id: toKebab(name) }),\n setting: (name) => ({ id: toKebab(name) }),\n action: (name) => ({ id: toKebab(name) }),\n mode: (name) => ({ name: toKebab(name) }),\n 'activity-group': (name) => ({ name: toKebab(name) }),\n 'selection-axis': (name) => ({ name: toKebab(name) }),\n // A leader binding's id is namespaced like a slot, because the key tree is\n // shared and two plugins must not collide on one path's identity.\n leader: (name, options) => ({ id: `${options.pluginId}.${toKebab(name)}` }),\n};\n\n/**\n * What the path knows about a contribution's identity.\n *\n * Keyed by surface, because the folder is what the author types. A surface\n * absent from the table, or an identity the path cannot supply such as a tab's\n * human label, is left entirely to the authored file.\n */\nfunction identityFor(\n contribution: ResolvedContribution,\n target: BuildTarget,\n options: RenderOptions,\n): Identity | undefined {\n const { entry } = contribution;\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n if (!isFrontendTarget(target)) return BACKEND_IDENTITY[surface]?.(entry.name);\n if (surface === 'fill') return fillIdentity(entry.name, entry.target);\n return FRONTEND_IDENTITY[surface]?.(entry.name, options);\n}\n\n/** A stable, unique, valid identifier built from path words. */\nfunction uniqueIdentifier(parts: readonly string[], taken: Set<string>): string {\n const words = parts\n .join('-')\n .split(/[^A-Za-z0-9]+/u)\n .filter((word) => word.length > 0);\n const head = words.map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1))).join('');\n const base = /^[A-Za-z_]/u.test(head) ? head : `x${head}`;\n let candidate = base;\n let suffix = 2;\n while (taken.has(candidate)) candidate = `${base}${suffix++}`;\n taken.add(candidate);\n return candidate;\n}\n\n/** A stable, unique, valid identifier: surface and name, disambiguated by scope when needed. */\nfunction identifierFor(contribution: ResolvedContribution, taken: Set<string>): string {\n return uniqueIdentifier([contribution.entry.surface ?? 'extra', contribution.entry.name], taken);\n}\n\n/** The extensionless relative specifier from a generated entry to a routed file. */\nfunction specifierFor(file: string, entryDir: string): string {\n const target = file.replace(/\\.[^.]+$/u, '');\n const relative = posix.relative(entryDir, target);\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\ninterface Binding {\n readonly identifier: string;\n readonly contribution: ResolvedContribution;\n readonly identity: Identity | undefined;\n readonly mcpWidget: string | undefined;\n}\n\n/** Encode data for generated JavaScript, including the HTML script boundary. */\nfunction widgetLiteral(key: string): string {\n return JSON.stringify(key).replaceAll('<', '\\\\u003c').replaceAll('\\u2028', '\\\\u2028').replaceAll('\\u2029', '\\\\u2029');\n}\n\nfunction bind(resolution: TargetResolution, options: RenderOptions): Binding[] {\n const taken = new Set<string>();\n return [...resolution.contributions]\n .sort((left, right) => left.entry.file.localeCompare(right.entry.file))\n .map((contribution) => {\n // The contribution takes its identifier first, so the plain name stays\n // with the tool rather than going to whichever file sorted earlier.\n const identifier = identifierFor(contribution, taken);\n const mcpWidget = resolution.target === 'mcp' ? options.mcpWidgets?.[contribution.entry.file] : undefined;\n if (mcpWidget !== undefined && !/^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*\\/[a-z0-9_]+$/u.test(mcpWidget))\n throw new Error(`Invalid MCP widget key '${mcpWidget}'`);\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n mcpWidget,\n };\n });\n}\n\n/** Scope nesting depth, so a contribution can find the root that encloses it. */\nconst DEPTH: Readonly<Record<ExtensionScope, number>> = { global: 0, workspace: 1, session: 2 };\n\ninterface RootBinding {\n /** The imported factory. */\n readonly identifier: string;\n /** The declaration it returned: `value` plus this scope's lifecycle hooks. */\n readonly declaration: string;\n /** The mount context contributions beneath this root receive. */\n readonly context: string;\n readonly entry: ExtensionEntry;\n}\n\nfunction rootBindings(entries: readonly ExtensionEntry[]): RootBinding[] {\n return entries.map((entry) => {\n const suffix = entry.scope[0]?.toUpperCase() + entry.scope.slice(1);\n return { identifier: `root${suffix}`, declaration: `scope${suffix}`, context: `context${suffix}`, entry };\n });\n}\n\n/**\n * Constructs each scope before anything it contains, outermost first.\n *\n * Every root is handed the context its enclosing root produced. Root factories\n * may be async, so the generated host factory awaits each one before exposing\n * its value to narrower contributions.\n */\nfunction rootPrologue(roots: readonly RootBinding[], base: string, body: readonly string[]): string[] {\n const lines: string[] = [];\n let enclosing = base;\n for (const [index, root] of roots.entries()) {\n lines.push(`const ${root.declaration} = await ${root.identifier}(${enclosing});`);\n const contextIsUsed = index < roots.length - 1 || body.some((line) => line.includes(root.context));\n if (contextIsUsed) lines.push(`const ${root.context} = { ...${enclosing}, root: ${root.declaration}.value };`);\n enclosing = root.context;\n }\n return lines;\n}\n\n/** The context a contribution sees: the nearest enclosing root's, or the mount's. */\nfunction contextForScope(roots: readonly RootBinding[], scope: ExtensionScope, base: string): string {\n let found = base;\n for (const root of roots) {\n if (DEPTH[root.entry.scope] <= DEPTH[scope]) found = root.context;\n }\n return found;\n}\n\nfunction hatchBindings(entries: readonly ExtensionEntry[]): { identifier: string; entry: ExtensionEntry }[] {\n return [...entries]\n .sort((left, right) => left.file.localeCompare(right.file))\n .map((entry, index) => ({ identifier: `extra${index === 0 ? '' : index + 1}`, entry }));\n}\n\n/**\n * One contribution as it appears inside its array, identity first so the file wins.\n *\n * The browser half is never resolved. The cockpit builds its definition as\n * data and starts it separately, so a frontend file has no mount context to\n * receive, and resolving anyway would call any export that happens to be a\n * function. A React component is a function, so that is not hypothetical.\n */\nfunction member(binding: Binding, contextExpression: string, target: BuildTarget): string {\n if (ALWAYS_FACTORY_FIELDS.includes(binding.contribution.field)) {\n return `${binding.identifier}(${contextExpression})`;\n }\n\n const resolved = isFrontendTarget(target) ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n const isFactory = FACTORY_FIELDS[target].includes(binding.contribution.field);\n // A live collection is the contribution container itself. Applying a path\n // identity would spread class instances into plain objects and can erase\n // prototype-backed snapshot/subscribe methods.\n if (binding.contribution.entry.cardinality === 'collection') return resolved;\n if (binding.identity === undefined) return isFactory ? binding.identifier : resolved;\n\n const identity = renderIdentity(binding.identity);\n // A channel array holds factories, so the identity is applied inside one.\n if (isFactory) return `() => via({ ${identity} }, ${binding.identifier}())`;\n const value = `via({ ${identity} }, ${resolved})`;\n return binding.mcpWidget === undefined ? value : `withWidget(${widgetLiteral(binding.mcpWidget)}, ${value})`;\n}\n\n/** The server entry imports only the types its scopes actually use. */\nfunction serverImport(scopes: readonly string[]): string {\n const types = scopes.some((line) => line.includes('get ')) ? ['type PoServerSessionPlugin'] : [];\n return `import { ${['defineServerPlugin', ...types].join(', ')} } from '@agimon-ai/po-core/serverFacet';`;\n}\n\n/**\n * Emits a contribution as a getter, so it is built after services mount.\n *\n * Both host helpers register `services` first and read every other field\n * afterwards. A plain property would be evaluated when the entry's factory\n * returns, which is before any service exists, so a routed file could never\n * inject one at construction and every package with shared per-mount state\n * would be stuck in one closure.\n *\n * `services` itself stays a plain property: it is what the helper reads first,\n * and a getter for it would buy nothing.\n */\nfunction defer(field: string, rendered: string, target: BuildTarget): string {\n if (field === 'services' || rendered.startsWith('...')) return rendered;\n const [name, ...value] = rendered.split(': ');\n // Annotated, because a getter gets no contextual type from the object\n // literal it sits in, so the identity helper's T would widen to unknown and\n // the contribution would stop type checking against the array it joins.\n const type = `${CONTRIBUTIONS_TYPE[target]}['${name}']`;\n return `get ${name}(): ${type} { return ${value.join(': ').replace(/,$/u, '')}; },`;\n}\n\n/**\n * The contributions object's body.\n *\n * The mount context is resolved per contribution rather than once, because a\n * root rebinds it for everything beneath it and two contributions at different\n * scopes can therefore see different contexts in the same object.\n */\nfunction bodyFor(\n bindings: readonly Binding[],\n indent: string,\n contextOf: (binding: Binding) => string,\n target: BuildTarget,\n): string[] {\n const grouped = new Map<string, Binding[]>();\n for (const binding of bindings) {\n const held = grouped.get(binding.contribution.field);\n if (held === undefined) grouped.set(binding.contribution.field, [binding]);\n else held.push(binding);\n }\n\n const lines: string[] = [];\n for (const field of [...grouped.keys()].sort()) {\n const members = grouped.get(field) as Binding[];\n if (SINGLETON_FIELDS.includes(field)) {\n const entry = members[0];\n if (entry) {\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n continue;\n }\n const renderedMembers = members.map((entry) =>\n entry.contribution.entry.cardinality === 'many'\n ? `...many(${entry.identifier}, ${contextOf(entry)})${entry.mcpWidget === undefined ? '' : `.map((tool) => withWidget(${widgetLiteral(entry.mcpWidget)}, tool))`}`\n : member(entry, contextOf(entry), target),\n );\n const entries = `[${renderedMembers.join(', ')}]`;\n const rendered = members.some((entry) => entry.contribution.entry.cardinality === 'optional')\n ? `defined(${entries})`\n : entries;\n lines.push(`${indent}${defer(field, `${field}: ${rendered},`, target)}`);\n }\n return lines;\n}\n\n/** Root-owned registrations join routed registrations in the host's usual fields. */\nfunction withRootRegistrations(\n body: readonly string[],\n roots: readonly RootBinding[],\n target: 'server',\n indent: string,\n scope: ExtensionScope,\n): string[] {\n if (roots.length === 0) return [...body];\n const lines = [...body];\n const servicesIndex = lines.findIndex((line) => line.startsWith(`${indent}services: [`));\n const routedServices =\n servicesIndex < 0 ? '' : (lines.splice(servicesIndex, 1)[0]?.match(/services: \\[(.*)\\],$/u)?.[1] ?? '');\n const services = [...roots.map((root) => `...(${root.declaration}.services ?? [])`), routedServices]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}services: [${services}],`);\n\n if (target === 'server' && scope === 'session') {\n const activitiesIndex = lines.findIndex((line) => line.startsWith(`${indent}get activities()`));\n const routedActivities =\n activitiesIndex < 0 ? '' : (lines.splice(activitiesIndex, 1)[0]?.match(/return \\[(.*)\\]; \\},$/u)?.[1] ?? '');\n const activities = [...roots.map((root) => `...(${root.declaration}.activities ?? [])`), routedActivities]\n .filter(Boolean)\n .join(', ');\n lines.push(`${indent}get activities(): PoServerSessionPlugin['activities'] { return [${activities}]; },`);\n }\n return lines;\n}\n\nfunction importsFor(\n bindings: readonly Binding[],\n hatches: readonly { identifier: string; entry: ExtensionEntry }[],\n roots: readonly RootBinding[],\n entryDir: string,\n): string[] {\n return [\n ...roots.map((r) => `import ${r.identifier} from '${specifierFor(r.entry.file, entryDir)}';`),\n ...bindings.map((b) => `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`),\n ...hatches.map((h) => `import ${h.identifier} from '${specifierFor(h.entry.file, entryDir)}';`),\n ];\n}\n\nfunction compact(lines: readonly string[]): string {\n return lines.filter((line, index, all) => !(line === '' && all[index - 1] === '')).join('\\n');\n}\n\n/**\n * Emits the resolver only when something calls it.\n *\n * Extension packages compile with noUnusedLocals, so a generated entry whose\n * every contribution is a factory would otherwise fail to typecheck on an\n * unused helper.\n */\nfunction resolverFor(body: readonly string[]): string[] {\n const lines: string[] = [];\n if (body.some((line) => line.includes('at('))) lines.push(resolver());\n if (body.some((line) => line.includes('many('))) lines.push(manyResolver());\n if (body.some((line) => line.includes('defined('))) lines.push(definedResolver());\n if (body.some((line) => line.includes('via('))) lines.push(IDENTITY_HELPER);\n return lines.length > 0 ? [...lines, ''] : [];\n}\n\n/** `noUnusedParameters` means a scope that never threads context takes none. */\nfunction parameterFor(lines: readonly string[]): string {\n return lines.some((line) => line.includes(', context)') || line.includes('(context)')) ? '(context)' : '()';\n}\n\n/**\n * The scope's factory: an expression body, or a block when roots come first.\n *\n * A root has to be constructed before the object that reads it, so a scope\n * that has one becomes statements followed by a return rather than a bare\n * object literal.\n */\nfunction scopeBody(\n prologue: readonly string[],\n hooks: string | undefined,\n body: readonly string[],\n indent: string,\n): string[] {\n const object = [...(hooks === undefined ? [] : [`${indent} ${hooks}`]), ...body];\n const asynchronous = [...prologue, ...body].some((line) => line.includes('await '));\n const prefix = asynchronous ? 'async ' : '';\n if (prologue.length === 0) return [`${prefix}${parameterFor(body)} => ({`, ...object, `${indent}}),`];\n return [\n `${prefix}${parameterFor([...prologue, ...body])} => {`,\n ...prologue.map((line) => `${indent} ${line}`),\n `${indent} return {`,\n ...object.map((line) => ` ${line}`),\n `${indent} };`,\n `${indent}},`,\n ];\n}\n\n/** Folds every enclosing root's lifecycle hooks into the one set the host reads. */\nfunction rootHooks(roots: readonly RootBinding[]): string | undefined {\n if (roots.length === 0) return undefined;\n return `...composeRootHooks(${roots.map((root) => root.declaration).join(', ')}),`;\n}\n\n/**\n * The headless entry, one declaration per scope.\n *\n * Contributions cascade downward here because the server does not do it\n * itself: a facet reads exactly one `plugin[host.scope]` and nothing from the\n * scopes above it. Emitting the repetition is what lets an author declare a\n * channel once and have it mount at all three scopes.\n */\nexport function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n const allRoots = rootBindings(resolution.roots);\n\n const scopes: string[] = [];\n let usesRoots = false;\n for (const [index, scope] of SCOPE_ORDER.entries()) {\n const visible = bindings.filter((b) => SCOPE_ORDER.indexOf(b.contribution.entry.scope) <= index);\n const here = hatches.filter((h) => SCOPE_ORDER.indexOf(h.entry.scope) <= index);\n // Each scope is an independent mount, so it constructs the roots that\n // enclose it from scratch rather than sharing the deeper scope's.\n const roots = allRoots.filter((root) => SCOPE_ORDER.indexOf(root.entry.scope) <= index);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(visible, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'server'),\n roots,\n 'server',\n ' ',\n scope,\n ),\n ...here.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n if (body.length === 0 && roots.length === 0) continue;\n if (roots.length > 0) usesRoots = true;\n const factory = scopeBody(rootPrologue(roots, 'context', body), rootHooks(roots), body, ' ');\n scopes.push(` ${scope}: ${factory[0]}`, ...factory.slice(1));\n }\n\n return compact([\n HEADER,\n serverImport(scopes),\n ...(allRoots.length ? [\"import { composeServerProviderOverrides } from '@agimon-ai/po-core/serverFacet';\"] : []),\n ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/po-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\n ...(allRoots.length\n ? [` providerOverrides: composeServerProviderOverrides(${allRoots.map((root) => root.identifier).join(', ')}),`]\n : []),\n ...scopes,\n '});',\n '',\n 'export default facet;',\n '',\n ]);\n}\n\n/** The explicit remote-MCP entry. It intentionally imports only .mcp declarations. */\nexport function renderMcpEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const body = bodyFor(bindings, ' ', () => 'context', 'mcp');\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\n ...(bindings.some((binding) => binding.mcpWidget !== undefined)\n ? [\n 'const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({',\n ' ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },',\n '});',\n '',\n ]\n : []),\n 'export const mcp = defineMcpPlugin({',\n ` name: '${options.packageName}',`,\n ' session: (context) => ({',\n ...body,\n ' }) satisfies PoMcpSessionPlugin,',\n '});',\n '',\n 'export default mcp;',\n '',\n ]);\n}\n\n/** What differs between the two frontend entries: the SDK they import and the name they export. */\ninterface FrontendEntryShape {\n readonly module: string;\n readonly define: string;\n readonly exportName: string;\n}\n\nconst FRONTEND_ENTRY: Readonly<Record<FrontendTarget, FrontendEntryShape>> = {\n web: { module: '@agimon-ai/po-core/web', define: 'defineWebPlugin', exportName: 'webPlugin' },\n native: { module: '@agimon-ai/po-core/native', define: 'defineNativePlugin', exportName: 'nativePlugin' },\n};\n\n/**\n * A frontend entry, one contributions object per scope.\n *\n * No cascade here, unlike the server: the registry already folds global into\n * workspace into session before install, so repeating a contribution would\n * install it twice.\n */\nfunction renderFrontendEntry(resolution: TargetResolution, options: RenderOptions, target: FrontendTarget): string {\n const shape = FRONTEND_ENTRY[target];\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n\n const scopes: string[] = [];\n for (const scope of SCOPE_ORDER) {\n const visible = bindings.filter((b) => b.contribution.entry.scope === scope);\n const here = hatches.filter((h) => h.entry.scope === scope);\n const body = [\n ...bodyFor(visible, ' ', () => 'undefined', target),\n // Frontend escape hatches are contribution data. Calling them would also\n // call React components, so merge the authored object directly.\n ...here.map((hatch) => ` ...${hatch.identifier},`),\n ];\n if (body.length === 0) continue;\n scopes.push(` ${scope}: {`, ...body, ' },');\n }\n\n const names = scopes.some((line) => line.includes('get '))\n ? `${shape.define}, type ${CONTRIBUTIONS_TYPE[target]}`\n : shape.define;\n return compact([\n HEADER,\n `import { ${names} } from '${shape.module}';`,\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n `export const ${shape.exportName} = ${shape.define}({`,\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n\n/** The cockpit entry, built from `.web` files and their unsuffixed fallbacks. */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'web');\n}\n\n/** The native app entry, built from `.native` files only. */\nexport function renderNativeEntry(resolution: TargetResolution, options: RenderOptions): string {\n return renderFrontendEntry(resolution, options, 'native');\n}\n"],"mappings":"iLAQA,MAAMA,EAAS,4DAGTC,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtFC,EAAmE,CACvE,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,OAAQ,CAAC,EACT,IAAK,CAAC,CACR,EAYMC,EAA2C,CAAC,UAAU,EAEtDC,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1EC,EAA4D,CAChE,OAAQ,wBACR,IAAK,yBAGL,OAAQ,yBACR,IAAK,oBACP,EAOA,SAASC,GAAmB,CAC1B,MAAO,CACL,0CACA,gEACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CAGA,SAASC,GAAuB,CAC9B,MAAO,CACL,6DACA,kGACA,kGACA,iEACA,IACF,CAAC,CAAC,KAAK;CAAI,CACb,CAEA,SAASC,GAA0B,CACjC,MAAO,CACL,yDACA,kEACA,8DACF,CAAC,CAAC,KAAK;CAAI,CACb,CAgBA,MAAMC,EAAkB,CACtB,2EACA,mFACF,CAAC,CAAC,KAAK;CAAI,EAWX,SAASC,EAAa,EAAc,EAAsC,CAExE,OADIC,IAAW,IAAA,GAAkB,CAAE,GAAIC,EAAQC,CAAI,CAAE,EAC9C,CAAE,KAAMF,EAAQ,GAAIC,EAAQC,CAAI,CAAE,CAC3C,CAGA,MAAMC,EAAyE,CAC7E,KAAO,IAAU,CAAE,KAAMC,EAAQF,CAAI,CAAE,GAIvC,QAAU,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1D"}
@@ -1,3 +1,3 @@
1
- const e=require("../identity/index.cjs");let t=require("node:path");function n(n,r,i){let a={},o=[],s=[],c=/* @__PURE__ */ new Set,l=n.entries.filter(e=>e.side===`frontend`&&e.platform===`mcp`&&e.surface===`tool`).sort((e,t)=>e.file.localeCompare(t.file));for(let[u,d]of l.entries()){let l=e.toSnake(d.name),f=`${r}/${l}`;if(c.has(f))throw Error(`Duplicate MCP widget '${f}'`);let p=n.entries.filter(t=>t.side===`backend`&&t.platform===`mcp`&&t.surface===`tool`&&e.toSnake(t.name)===l&&JSON.stringify(t.gates)===JSON.stringify(d.gates));if(p.length!==1)throw Error(`MCP widget '${d.file}' must match exactly one backend tool declaration`);c.add(f),a[p[0].file]=f;let m=t.posix.relative(i,d.file.replace(/\.[^.]+$/u,``));o.push(`import Widget${u} from ${JSON.stringify(m.startsWith(`.`)?m:`./${m}`)};`),s.push(` ${JSON.stringify(f)}: Widget${u},`)}return{declarations:a,names:[...c],source:l.length===0?void 0:[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import type { ComponentType } from 'react';`,`import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {`,...s,`};`,``].join(`
1
+ const e=require("../identity/index.cjs");let t=require("node:path");function n(n,r,i){let a={},o=[],s=[],c=/* @__PURE__ */ new Set,l=n.entries.filter(e=>e.side===`frontend`&&e.platform===`mcp`&&e.surface===`tool`).sort((e,t)=>e.file.localeCompare(t.file));for(let[u,d]of l.entries()){let l=e.toSnake(d.name),f=`${r}/${l}`;if(c.has(f))throw Error(`Duplicate MCP widget '${f}'`);let p=n.entries.filter(t=>t.side===`backend`&&t.platform===`mcp`&&t.surface===`tool`&&e.toSnake(t.name)===l&&JSON.stringify(t.gates)===JSON.stringify(d.gates));if(p.length!==1)throw Error(`MCP widget '${d.file}' must match exactly one backend tool declaration`);c.add(f),a[p[0].file]=f;let m=t.posix.relative(i,d.file.replace(/\.[^.]+$/u,``));o.push(`import Widget${u} from ${JSON.stringify(m.startsWith(`.`)?m:`./${m}`)};`),s.push(` ${JSON.stringify(f)}: Widget${u},`)}return{declarations:a,names:[...c],source:l.length===0?void 0:[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import type { ComponentType } from 'react';`,`import type { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {`,...s,`};`,``].join(`
2
2
  `)}}exports.renderMcpWidgets=n;
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["toSnake","posix","require_index","node_path","renderMcpWidgets","declarations","imports","members","names","widgets","graph","entry","left","right","index","name","key","packageName","tools","candidate","relative","entryDir"],"sources":["../../../src/services/renderMcpWidgets/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionGraph } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\n\n/** Browser entries are paired by their routed identity, never imported into the Node MCP facet. */\nexport function renderMcpWidgets(graph: ExtensionGraph, packageName: string, entryDir: string) {\n const declarations: Record<string, string> = {};\n const imports: string[] = [];\n const members: string[] = [];\n const names = new Set<string>();\n const widgets = graph.entries\n .filter((entry) => entry.side === 'frontend' && entry.platform === 'mcp' && entry.surface === 'tool')\n .sort((left, right) => left.file.localeCompare(right.file));\n for (const [index, entry] of widgets.entries()) {\n const name = toSnake(entry.name);\n const key = `${packageName}/${name}`;\n if (names.has(key)) throw new Error(`Duplicate MCP widget '${key}'`);\n const tools = graph.entries.filter(\n (candidate) =>\n candidate.side === 'backend' &&\n candidate.platform === 'mcp' &&\n candidate.surface === 'tool' &&\n toSnake(candidate.name) === name &&\n JSON.stringify(candidate.gates) === JSON.stringify(entry.gates),\n );\n if (tools.length !== 1)\n throw new Error(`MCP widget '${entry.file}' must match exactly one backend tool declaration`);\n names.add(key);\n declarations[tools[0]!.file] = key;\n const relative = posix.relative(entryDir, entry.file.replace(/\\.[^.]+$/u, ''));\n imports.push(\n `import Widget${index} from ${JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`)};`,\n );\n members.push(` ${JSON.stringify(key)}: Widget${index},`);\n }\n return {\n declarations,\n names: [...names],\n source:\n widgets.length === 0\n ? undefined\n : [\n '// Generated by @agimon-ai/po-build. Do not edit by hand.',\n \"import type { ComponentType } from 'react';\",\n \"import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {',\n ...members,\n '};',\n '',\n ].join('\\n'),\n };\n}\n"],"mappings":"oEAMA,SAAgBI,EAAiB,EAAuB,EAAqB,EAAkB,CAC7F,IAAMC,EAAuC,CAAC,EACxCC,EAAoB,CAAC,EACrBC,EAAoB,CAAC,EACrBC,kBAAQ,IAAI,IACZC,EAAUC,EAAM,QACnB,OAAQ,GAAUC,EAAM,OAAS,YAAcA,EAAM,WAAa,OAASA,EAAM,UAAY,MAAM,CAAC,CACpG,MAAM,EAAM,IAAUC,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC5D,IAAK,GAAM,CAACC,EAAOH,KAAUF,EAAQ,QAAQ,EAAG,CAC9C,IAAMM,EAAOf,EAAAA,QAAQW,EAAM,IAAI,EACzBK,EAAM,GAAGC,EAAY,GAAGF,IAC9B,GAAIP,EAAM,IAAIQ,CAAG,EAAG,MAAU,MAAM,yBAAyBA,EAAI,EAAE,EACnE,IAAME,EAAQR,EAAM,QAAQ,OACzB,GACCS,EAAU,OAAS,WACnBA,EAAU,WAAa,OACvBA,EAAU,UAAY,QACtBnB,EAAAA,QAAQmB,EAAU,IAAI,IAAMJ,GAC5B,KAAK,UAAUI,EAAU,KAAK,IAAM,KAAK,UAAUR,EAAM,KAAK,CAClE,EACA,GAAIO,EAAM,SAAW,EACnB,MAAU,MAAM,eAAeP,EAAM,KAAK,kDAAkD,EAC9FH,EAAM,IAAIQ,CAAG,EACb,EAAaE,EAAM,EAAE,CAAE,MAAQF,EAC/B,IAAMI,EAAWnB,EAAAA,MAAM,SAASoB,EAAUV,EAAM,KAAK,QAAQ,YAAa,EAAE,CAAC,EAC7EL,EAAQ,KACN,gBAAgBQ,EAAM,QAAQ,KAAK,UAAUM,EAAS,WAAW,GAAG,EAAIA,EAAW,KAAKA,GAAU,EAAE,EACtG,EACAb,EAAQ,KAAK,KAAK,KAAK,UAAUS,CAAG,EAAE,UAAUF,EAAM,EAAE,CAC1D,CACA,MAAO,CACL,eACA,MAAO,CAAC,GAAGN,CAAK,EAChB,OACEC,EAAQ,SAAW,EACf,IAAA,GACA,CACE,4DACA,8CACA,0EACA,GAAGH,EACH,GACA,wFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
1
+ {"version":3,"file":"index.cjs","names":["toSnake","posix","require_index","node_path","renderMcpWidgets","declarations","imports","members","names","widgets","graph","entry","left","right","index","name","key","packageName","tools","candidate","relative","entryDir"],"sources":["../../../src/services/renderMcpWidgets/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionGraph } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\n\n/** Browser entries are paired by their routed identity, never imported into the Node MCP facet. */\nexport function renderMcpWidgets(graph: ExtensionGraph, packageName: string, entryDir: string) {\n const declarations: Record<string, string> = {};\n const imports: string[] = [];\n const members: string[] = [];\n const names = new Set<string>();\n const widgets = graph.entries\n .filter((entry) => entry.side === 'frontend' && entry.platform === 'mcp' && entry.surface === 'tool')\n .sort((left, right) => left.file.localeCompare(right.file));\n for (const [index, entry] of widgets.entries()) {\n const name = toSnake(entry.name);\n const key = `${packageName}/${name}`;\n if (names.has(key)) throw new Error(`Duplicate MCP widget '${key}'`);\n const tools = graph.entries.filter(\n (candidate) =>\n candidate.side === 'backend' &&\n candidate.platform === 'mcp' &&\n candidate.surface === 'tool' &&\n toSnake(candidate.name) === name &&\n JSON.stringify(candidate.gates) === JSON.stringify(entry.gates),\n );\n if (tools.length !== 1)\n throw new Error(`MCP widget '${entry.file}' must match exactly one backend tool declaration`);\n names.add(key);\n declarations[tools[0]!.file] = key;\n const relative = posix.relative(entryDir, entry.file.replace(/\\.[^.]+$/u, ''));\n imports.push(\n `import Widget${index} from ${JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`)};`,\n );\n members.push(` ${JSON.stringify(key)}: Widget${index},`);\n }\n return {\n declarations,\n names: [...names],\n source:\n widgets.length === 0\n ? undefined\n : [\n '// Generated by @agimon-ai/po-build. Do not edit by hand.',\n \"import type { ComponentType } from 'react';\",\n \"import type { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {',\n ...members,\n '};',\n '',\n ].join('\\n'),\n };\n}\n"],"mappings":"oEAMA,SAAgBI,EAAiB,EAAuB,EAAqB,EAAkB,CAC7F,IAAMC,EAAuC,CAAC,EACxCC,EAAoB,CAAC,EACrBC,EAAoB,CAAC,EACrBC,kBAAQ,IAAI,IACZC,EAAUC,EAAM,QACnB,OAAQ,GAAUC,EAAM,OAAS,YAAcA,EAAM,WAAa,OAASA,EAAM,UAAY,MAAM,CAAC,CACpG,MAAM,EAAM,IAAUC,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC5D,IAAK,GAAM,CAACC,EAAOH,KAAUF,EAAQ,QAAQ,EAAG,CAC9C,IAAMM,EAAOf,EAAAA,QAAQW,EAAM,IAAI,EACzBK,EAAM,GAAGC,EAAY,GAAGF,IAC9B,GAAIP,EAAM,IAAIQ,CAAG,EAAG,MAAU,MAAM,yBAAyBA,EAAI,EAAE,EACnE,IAAME,EAAQR,EAAM,QAAQ,OACzB,GACCS,EAAU,OAAS,WACnBA,EAAU,WAAa,OACvBA,EAAU,UAAY,QACtBnB,EAAAA,QAAQmB,EAAU,IAAI,IAAMJ,GAC5B,KAAK,UAAUI,EAAU,KAAK,IAAM,KAAK,UAAUR,EAAM,KAAK,CAClE,EACA,GAAIO,EAAM,SAAW,EACnB,MAAU,MAAM,eAAeP,EAAM,KAAK,kDAAkD,EAC9FH,EAAM,IAAIQ,CAAG,EACb,EAAaE,EAAM,EAAE,CAAE,MAAQF,EAC/B,IAAMI,EAAWnB,EAAAA,MAAM,SAASoB,EAAUV,EAAM,KAAK,QAAQ,YAAa,EAAE,CAAC,EAC7EL,EAAQ,KACN,gBAAgBQ,EAAM,QAAQ,KAAK,UAAUM,EAAS,WAAW,GAAG,EAAIA,EAAW,KAAKA,GAAU,EAAE,EACtG,EACAb,EAAQ,KAAK,KAAK,KAAK,UAAUS,CAAG,EAAE,UAAUF,EAAM,EAAE,CAC1D,CACA,MAAO,CACL,eACA,MAAO,CAAC,GAAGN,CAAK,EAChB,OACEC,EAAQ,SAAW,EACf,IAAA,GACA,CACE,4DACA,8CACA,wEACA,GAAGH,EACH,GACA,sFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
@@ -1,3 +1,3 @@
1
- import{toSnake as e}from"../identity/index.mjs";import{posix as t}from"node:path";function n(n,r,i){let a={},o=[],s=[],c=/* @__PURE__ */ new Set,l=n.entries.filter(e=>e.side===`frontend`&&e.platform===`mcp`&&e.surface===`tool`).sort((e,t)=>e.file.localeCompare(t.file));for(let[u,d]of l.entries()){let l=e(d.name),f=`${r}/${l}`;if(c.has(f))throw Error(`Duplicate MCP widget '${f}'`);let p=n.entries.filter(t=>t.side===`backend`&&t.platform===`mcp`&&t.surface===`tool`&&e(t.name)===l&&JSON.stringify(t.gates)===JSON.stringify(d.gates));if(p.length!==1)throw Error(`MCP widget '${d.file}' must match exactly one backend tool declaration`);c.add(f),a[p[0].file]=f;let m=t.relative(i,d.file.replace(/\.[^.]+$/u,``));o.push(`import Widget${u} from ${JSON.stringify(m.startsWith(`.`)?m:`./${m}`)};`),s.push(` ${JSON.stringify(f)}: Widget${u},`)}return{declarations:a,names:[...c],source:l.length===0?void 0:[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import type { ComponentType } from 'react';`,`import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {`,...s,`};`,``].join(`
1
+ import{toSnake as e}from"../identity/index.mjs";import{posix as t}from"node:path";function n(n,r,i){let a={},o=[],s=[],c=/* @__PURE__ */ new Set,l=n.entries.filter(e=>e.side===`frontend`&&e.platform===`mcp`&&e.surface===`tool`).sort((e,t)=>e.file.localeCompare(t.file));for(let[u,d]of l.entries()){let l=e(d.name),f=`${r}/${l}`;if(c.has(f))throw Error(`Duplicate MCP widget '${f}'`);let p=n.entries.filter(t=>t.side===`backend`&&t.platform===`mcp`&&t.surface===`tool`&&e(t.name)===l&&JSON.stringify(t.gates)===JSON.stringify(d.gates));if(p.length!==1)throw Error(`MCP widget '${d.file}' must match exactly one backend tool declaration`);c.add(f),a[p[0].file]=f;let m=t.relative(i,d.file.replace(/\.[^.]+$/u,``));o.push(`import Widget${u} from ${JSON.stringify(m.startsWith(`.`)?m:`./${m}`)};`),s.push(` ${JSON.stringify(f)}: Widget${u},`)}return{declarations:a,names:[...c],source:l.length===0?void 0:[`// Generated by @agimon-ai/po-build. Do not edit by hand.`,`import type { ComponentType } from 'react';`,`import type { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';`,...o,``,`export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {`,...s,`};`,``].join(`
2
2
  `)}}export{n as renderMcpWidgets};
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["renderMcpWidgets","declarations","imports","members","names","widgets","graph","entry","left","right","index","name","toSnake","key","packageName","tools","candidate","relative","posix","entryDir"],"sources":["../../../src/services/renderMcpWidgets/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionGraph } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\n\n/** Browser entries are paired by their routed identity, never imported into the Node MCP facet. */\nexport function renderMcpWidgets(graph: ExtensionGraph, packageName: string, entryDir: string) {\n const declarations: Record<string, string> = {};\n const imports: string[] = [];\n const members: string[] = [];\n const names = new Set<string>();\n const widgets = graph.entries\n .filter((entry) => entry.side === 'frontend' && entry.platform === 'mcp' && entry.surface === 'tool')\n .sort((left, right) => left.file.localeCompare(right.file));\n for (const [index, entry] of widgets.entries()) {\n const name = toSnake(entry.name);\n const key = `${packageName}/${name}`;\n if (names.has(key)) throw new Error(`Duplicate MCP widget '${key}'`);\n const tools = graph.entries.filter(\n (candidate) =>\n candidate.side === 'backend' &&\n candidate.platform === 'mcp' &&\n candidate.surface === 'tool' &&\n toSnake(candidate.name) === name &&\n JSON.stringify(candidate.gates) === JSON.stringify(entry.gates),\n );\n if (tools.length !== 1)\n throw new Error(`MCP widget '${entry.file}' must match exactly one backend tool declaration`);\n names.add(key);\n declarations[tools[0]!.file] = key;\n const relative = posix.relative(entryDir, entry.file.replace(/\\.[^.]+$/u, ''));\n imports.push(\n `import Widget${index} from ${JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`)};`,\n );\n members.push(` ${JSON.stringify(key)}: Widget${index},`);\n }\n return {\n declarations,\n names: [...names],\n source:\n widgets.length === 0\n ? undefined\n : [\n '// Generated by @agimon-ai/po-build. Do not edit by hand.',\n \"import type { ComponentType } from 'react';\",\n \"import type { DoomMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<DoomMcpWidgetProps>>> = {',\n ...members,\n '};',\n '',\n ].join('\\n'),\n };\n}\n"],"mappings":"kFAMA,SAAgBA,EAAiB,EAAuB,EAAqB,EAAkB,CAC7F,IAAMC,EAAuC,CAAC,EACxCC,EAAoB,CAAC,EACrBC,EAAoB,CAAC,EACrBC,kBAAQ,IAAI,IACZC,EAAUC,EAAM,QACnB,OAAQ,GAAUC,EAAM,OAAS,YAAcA,EAAM,WAAa,OAASA,EAAM,UAAY,MAAM,CAAC,CACpG,MAAM,EAAM,IAAUC,EAAK,KAAK,cAAcC,EAAM,IAAI,CAAC,EAC5D,IAAK,GAAM,CAACC,EAAOH,KAAUF,EAAQ,QAAQ,EAAG,CAC9C,IAAMM,EAAOC,EAAQL,EAAM,IAAI,EACzBM,EAAM,GAAGC,EAAY,GAAGH,IAC9B,GAAIP,EAAM,IAAIS,CAAG,EAAG,MAAU,MAAM,yBAAyBA,EAAI,EAAE,EACnE,IAAME,EAAQT,EAAM,QAAQ,OACzB,GACCU,EAAU,OAAS,WACnBA,EAAU,WAAa,OACvBA,EAAU,UAAY,QACtBJ,EAAQI,EAAU,IAAI,IAAML,GAC5B,KAAK,UAAUK,EAAU,KAAK,IAAM,KAAK,UAAUT,EAAM,KAAK,CAClE,EACA,GAAIQ,EAAM,SAAW,EACnB,MAAU,MAAM,eAAeR,EAAM,KAAK,kDAAkD,EAC9FH,EAAM,IAAIS,CAAG,EACb,EAAaE,EAAM,EAAE,CAAE,MAAQF,EAC/B,IAAMI,EAAWC,EAAM,SAASC,EAAUZ,EAAM,KAAK,QAAQ,YAAa,EAAE,CAAC,EAC7EL,EAAQ,KACN,gBAAgBQ,EAAM,QAAQ,KAAK,UAAUO,EAAS,WAAW,GAAG,EAAIA,EAAW,KAAKA,GAAU,EAAE,EACtG,EACAd,EAAQ,KAAK,KAAK,KAAK,UAAUU,CAAG,EAAE,UAAUH,EAAM,EAAE,CAC1D,CACA,MAAO,CACL,eACA,MAAO,CAAC,GAAGN,CAAK,EAChB,OACEC,EAAQ,SAAW,EACf,IAAA,GACA,CACE,4DACA,8CACA,0EACA,GAAGH,EACH,GACA,wFACA,GAAGC,EACH,KACA,EACF,CAAC,CAAC,KAAK;CAAI,CACnB,CACF"}
1
+ {"version":3,"file":"index.mjs","names":["renderMcpWidgets","declarations","imports","members","names","widgets","graph","entry","left","right","index","name","toSnake","key","packageName","tools","candidate","relative","posix","entryDir"],"sources":["../../../src/services/renderMcpWidgets/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport type { ExtensionGraph } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\n\n/** Browser entries are paired by their routed identity, never imported into the Node MCP facet. */\nexport function renderMcpWidgets(graph: ExtensionGraph, packageName: string, entryDir: string) {\n const declarations: Record<string, string> = {};\n const imports: string[] = [];\n const members: string[] = [];\n const names = new Set<string>();\n const widgets = graph.entries\n .filter((entry) => entry.side === 'frontend' && entry.platform === 'mcp' && entry.surface === 'tool')\n .sort((left, right) => left.file.localeCompare(right.file));\n for (const [index, entry] of widgets.entries()) {\n const name = toSnake(entry.name);\n const key = `${packageName}/${name}`;\n if (names.has(key)) throw new Error(`Duplicate MCP widget '${key}'`);\n const tools = graph.entries.filter(\n (candidate) =>\n candidate.side === 'backend' &&\n candidate.platform === 'mcp' &&\n candidate.surface === 'tool' &&\n toSnake(candidate.name) === name &&\n JSON.stringify(candidate.gates) === JSON.stringify(entry.gates),\n );\n if (tools.length !== 1)\n throw new Error(`MCP widget '${entry.file}' must match exactly one backend tool declaration`);\n names.add(key);\n declarations[tools[0]!.file] = key;\n const relative = posix.relative(entryDir, entry.file.replace(/\\.[^.]+$/u, ''));\n imports.push(\n `import Widget${index} from ${JSON.stringify(relative.startsWith('.') ? relative : `./${relative}`)};`,\n );\n members.push(` ${JSON.stringify(key)}: Widget${index},`);\n }\n return {\n declarations,\n names: [...names],\n source:\n widgets.length === 0\n ? undefined\n : [\n '// Generated by @agimon-ai/po-build. Do not edit by hand.',\n \"import type { ComponentType } from 'react';\",\n \"import type { PoMcpWidgetProps } from '@agimon-ai/po-core/mcpWidget';\",\n ...imports,\n '',\n 'export const widgets: Readonly<Record<string, ComponentType<PoMcpWidgetProps>>> = {',\n ...members,\n '};',\n '',\n ].join('\\n'),\n };\n}\n"],"mappings":"kFAMA,SAAgBA,EAAiB,EAAuB,EAAqB,EAAkB,CAC7F,IA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AI,CACnB,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-build",
3
- "version": "0.0.0-alpha.3",
3
+ "version": "0.0.0-alpha.4",
4
4
  "description": "Folder-convention scanner and build presets for Po extensions.",
5
5
  "keywords": [
6
6
  "ai",
@@ -53,11 +53,11 @@
53
53
  "access": "public"
54
54
  },
55
55
  "devDependencies": {
56
- "@types/node": "25.9.9",
57
- "@vitest/coverage-v8": "5.0.3",
56
+ "@types/node": "26.6.5",
57
+ "@vitest/coverage-v8": "5.0.4",
58
58
  "tsdown": "0.23.1",
59
59
  "typescript": "7.0.2",
60
- "vitest": "5.0.3"
60
+ "vitest": "5.0.4"
61
61
  },
62
62
  "engines": {
63
63
  "node": ">=24"