@agimon-ai/doompi-build 0.0.1-alpha.13 → 0.0.1-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/services/generate/index.cjs +1 -1
  2. package/dist/services/generate/index.cjs.map +1 -1
  3. package/dist/services/generate/index.d.mts.map +1 -1
  4. package/dist/services/generate/index.mjs +1 -1
  5. package/dist/services/generate/index.mjs.map +1 -1
  6. package/dist/services/renderEntry/index.cjs +2 -2
  7. package/dist/services/renderEntry/index.cjs.map +1 -1
  8. package/dist/services/renderEntry/index.d.mts.map +1 -1
  9. package/dist/services/renderEntry/index.mjs +2 -2
  10. package/dist/services/renderEntry/index.mjs.map +1 -1
  11. package/dist/services/renderEntry/type.d.mts +2 -0
  12. package/dist/services/renderEntry/type.d.mts.map +1 -1
  13. package/dist/services/renderMcpWidgets/index.cjs +3 -0
  14. package/dist/services/renderMcpWidgets/index.cjs.map +1 -0
  15. package/dist/services/renderMcpWidgets/index.mjs +3 -0
  16. package/dist/services/renderMcpWidgets/index.mjs.map +1 -0
  17. package/dist/services/scan/index.cjs +1 -1
  18. package/dist/services/scan/index.cjs.map +1 -1
  19. package/dist/services/scan/index.mjs +1 -1
  20. package/dist/services/scan/index.mjs.map +1 -1
  21. package/dist/services/syncManifest/index.cjs +1 -1
  22. package/dist/services/syncManifest/index.cjs.map +1 -1
  23. package/dist/services/syncManifest/index.d.mts.map +1 -1
  24. package/dist/services/syncManifest/index.mjs +1 -1
  25. package/dist/services/syncManifest/index.mjs.map +1 -1
  26. package/dist/services/tsdownPreset/index.cjs +1 -1
  27. package/dist/services/tsdownPreset/index.cjs.map +1 -1
  28. package/dist/services/tsdownPreset/index.d.mts.map +1 -1
  29. package/dist/services/tsdownPreset/index.mjs +1 -1
  30. package/dist/services/tsdownPreset/index.mjs.map +1 -1
  31. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../constants/layout.cjs"),n=require("../scan/index.cjs"),r=require("../resolveTarget/index.cjs"),i=require("../renderClient/index.cjs"),a=require("../renderEntry/index.cjs"),o=require("../writeGenerated/index.cjs");let s=require("node:fs");s=e.__toESM(s,1);let c=require("node:path");c=e.__toESM(c,1);function l(e){return e.replace(/^@[^/]+\//u,``).replace(/^doompi-/u,``)}function u(e){let t=JSON.parse(s.default.readFileSync(c.default.join(e,`package.json`),`utf8`));if(typeof t.name!=`string`)throw Error(`${e}/package.json has no name`);return t.name}const d={cli:a.renderCliEntry,server:a.renderServerEntry,web:a.renderWebEntry,mcp:a.renderMcpEntry},f=t.GENERATED_ENTRY_FILENAMES,p={cli:`ts`,server:`ts`,web:`ts`,mcp:`ts`};function m(e){let a=e.packageName??u(e.packageDir),m=e.pluginId??l(a),h=n.scanExtensions(e),g=[...h.notices],_=/* @__PURE__ */ new Map,v=[];for(let e of h.entries)e.platform===void 0||t.BUILD_TARGET_PLATFORMS.includes(e.platform)||g.push({path:e.file,message:`'${e.platform}' is a forward-looking platform with no build target; this file is not emitted for cli, server, web or mcp`});let y=e.target===void 0?[`cli`,`server`,`web`]:[e.target];for(let e of y){let n=r.resolveTarget(h,e);g.push(...n.notices);let i=e===`cli`&&h.entries.some(e=>e.side===`frontend`&&e.surface===`template`&&e.platform===`web`);if(n.contributions.length===0&&n.escapeHatches.length===0&&n.roots.length===0&&!i)continue;v.push(e);let o=d[e],s=o(n,{packageName:a,pluginId:m,root:h.root,entryDir:t.GENERATED_DIR});_.set(`${t.GENERATED_DIR}/${f[e]}.${p[e]}`,s)}let b=e.target===void 0&&s.default.existsSync(c.default.join(e.packageDir,`src/types/apiRoutes.ts`)),x=v.includes(`web`),S=b&&x?i.renderApiClient(h,{packageName:a,pluginId:m,root:h.root,entryDir:t.GENERATED_DIR}):void 0;S!==void 0&&_.set(`${t.GENERATED_DIR}/${t.GENERATED_CLIENT_NAME}.ts`,S),b&&x&&S===void 0&&g.push({path:t.API_ROUTES_MODULE,message:`declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted`});let C=e.target===void 0?t.GENERATED_ENTRY_NAMES.filter(t=>t!==`mcp`||!s.default.existsSync(c.default.join(e.packageDir,`tsdown.mcp.config.ts`))).map(e=>`${t.GENERATED_DIR}/${e}.ts`):[`${t.GENERATED_DIR}/${f[e.target]}.${p[e.target]}`],{changed:w}=o.writeGenerated(e.packageDir,_,e.check,C);return{graph:h,packageName:a,pluginId:m,files:_,changed:w,notices:g,targets:v}}exports.defaultPluginId=l,exports.generateExtension=m;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../constants/layout.cjs"),n=require("../scan/index.cjs"),r=require("../resolveTarget/index.cjs"),i=require("../renderClient/index.cjs"),a=require("../renderEntry/index.cjs"),o=require("../renderMcpWidgets/index.cjs"),s=require("../writeGenerated/index.cjs");let c=require("node:fs");c=e.__toESM(c,1);let l=require("node:path");l=e.__toESM(l,1);function u(e){return e.replace(/^@[^/]+\//u,``).replace(/^doompi-/u,``)}function d(e){let t=JSON.parse(c.default.readFileSync(l.default.join(e,`package.json`),`utf8`));if(typeof t.name!=`string`)throw Error(`${e}/package.json has no name`);return t.name}const f={cli:a.renderCliEntry,server:a.renderServerEntry,web:a.renderWebEntry,mcp:a.renderMcpEntry},p=t.GENERATED_ENTRY_FILENAMES,m={cli:`ts`,server:`ts`,web:`ts`,mcp:`ts`};function h(e){let a=e.packageName??d(e.packageDir),h=e.pluginId??u(a),g=n.scanExtensions(e),_=[...g.notices],v=/* @__PURE__ */ new Map,y=[],b=e.target===`mcp`?o.renderMcpWidgets(g,a,t.GENERATED_DIR):void 0;b?.source!==void 0&&v.set(`${t.GENERATED_DIR}/mcp-ui.ts`,b.source);for(let e of g.entries)e.platform===void 0||t.BUILD_TARGET_PLATFORMS.includes(e.platform)||_.push({path:e.file,message:`'${e.platform}' is a forward-looking platform with no build target; this file is not emitted for cli, server, web or mcp`});let x=e.target===void 0?[`cli`,`server`,`web`]:[e.target];for(let e of x){let n=r.resolveTarget(g,e);_.push(...n.notices);let i=e===`cli`&&g.entries.some(e=>e.side===`frontend`&&e.surface===`template`&&e.platform===`web`);if(n.contributions.length===0&&n.escapeHatches.length===0&&n.roots.length===0&&!i)continue;y.push(e);let o=f[e],s=o(n,{packageName:a,pluginId:h,root:g.root,entryDir:t.GENERATED_DIR,mcpWidgets:b?.declarations});v.set(`${t.GENERATED_DIR}/${p[e]}.${m[e]}`,s)}let S=e.target===void 0&&c.default.existsSync(l.default.join(e.packageDir,`src/types/apiRoutes.ts`)),C=y.includes(`web`),w=S&&C?i.renderApiClient(g,{packageName:a,pluginId:h,root:g.root,entryDir:t.GENERATED_DIR}):void 0;w!==void 0&&v.set(`${t.GENERATED_DIR}/${t.GENERATED_CLIENT_NAME}.ts`,w),S&&C&&w===void 0&&_.push({path:t.API_ROUTES_MODULE,message:`declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted`});let T=e.target===void 0?t.GENERATED_ENTRY_NAMES.filter(t=>t!==`mcp`||!c.default.existsSync(l.default.join(e.packageDir,`tsdown.mcp.config.ts`))).map(e=>`${t.GENERATED_DIR}/${e}.ts`):[`${t.GENERATED_DIR}/${p[e.target]}.${m[e.target]}`,...e.target===`mcp`?[`${t.GENERATED_DIR}/mcp-ui.ts`]:[]],{changed:E}=s.writeGenerated(e.packageDir,v,e.check,T);return{graph:g,packageName:a,pluginId:h,files:v,changed:E,notices:_,targets:y}}exports.defaultPluginId=u,exports.generateExtension=h;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["fs","path","renderCliEntry","renderServerEntry","renderWebEntry","renderMcpEntry","GENERATED_ENTRY_FILENAMES","scanExtensions","BUILD_TARGET_PLATFORMS","resolveTarget","GENERATED_DIR","renderApiClient","GENERATED_CLIENT_NAME","API_ROUTES_MODULE","GENERATED_ENTRY_NAMES","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} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient } from '../renderClient';\nimport { renderCliEntry, renderMcpEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/doompi-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^doompi-/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 renderCliEntry>> = {\n cli: renderCliEntry,\n server: renderServerEntry,\n web: renderWebEntry,\n mcp: renderMcpEntry,\n};\n\n/** The generated entry keeps its historical filename so no consumer has to change. */\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\nconst ENTRY_EXTENSION: Readonly<Record<BuildTarget, string>> = { cli: 'ts', server: 'ts', web: 'ts', mcp: 'ts' };\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\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 print this 3x.\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 cli, server, web or mcp`,\n });\n }\n\n const requestedTargets = options.target === undefined ? (['cli', 'server', 'web'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n // modes.yaml admits packages through their Pi entry, even when their only feature is a browser layout.\n const templateAdmission =\n target === 'cli' &&\n graph.entries.some(\n (entry) => entry.side === 'frontend' && entry.surface === 'template' && entry.platform === 'web',\n );\n if (\n resolution.contributions.length === 0 &&\n resolution.escapeHatches.length === 0 &&\n resolution.roots.length === 0 &&\n !templateAdmission\n )\n continue;\n\n targets.push(target);\n const render = RENDERERS[target];\n const source = render(resolution, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR });\n files.set(`${GENERATED_DIR}/${ENTRY_FILENAME[target]}.${ENTRY_EXTENSION[target]}`, source);\n }\n\n // Not a fourth 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 if (hasRouteTable && hasBrowserHalf && client === 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 : [`${GENERATED_DIR}/${ENTRY_FILENAME[options.target]}.${ENTRY_EXTENSION[options.target]}`];\n const { changed } = writeGenerated(options.packageDir, files, options.check, managed);\n return { graph, packageName, pluginId, files, changed, notices, targets };\n}\n"],"mappings":"mXAqBA,SAAgB,EAAgB,EAA6B,CAC3D,OAAO,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,YAAa,EAAE,CACtE,CAEA,SAAS,EAAgB,EAA4B,CACnD,IAAM,EAAW,KAAK,MAAMA,EAAAA,QAAG,aAAaC,EAAAA,QAAK,KAAK,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAO,EAAS,MAAS,SAAU,MAAU,MAAM,GAAG,EAAW,0BAA0B,EAC/F,OAAO,EAAS,IAClB,CAEA,MAAM,EAAkE,CACtE,IAAKC,EAAAA,eACL,OAAQC,EAAAA,kBACR,IAAKC,EAAAA,eACL,IAAKC,EAAAA,cACP,EAGM,EAAwDC,EAAAA,0BACxD,EAAyD,CAAE,IAAK,KAAM,OAAQ,KAAM,IAAK,KAAM,IAAK,IAAK,EAU/G,SAAgB,EAAkB,EAA0C,CAC1E,IAAM,EAAc,EAAQ,aAAe,EAAgB,EAAQ,UAAU,EACvE,EAAW,EAAQ,UAAY,EAAgB,CAAW,EAE1D,EAAwBC,EAAAA,eAAe,CAAO,EAC9C,EAA6B,CAAC,GAAG,EAAM,OAAO,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AkB,IAAW,IAAA,IAChD,EAAQ,KAAK,CACX,KAAMC,EAAAA,kBACN,QAAS,2FACX,CAAC,EAGH,IAAM,EACJ,EAAQ,SAAW,IAAA,GACfC,EAAAA,sBAAsB,OACnB,GAAS,IAAS,OAAS,CAACd,EAAAA,QAAG,WAAWC,EAAAA,QAAK,KAAK,EAAQ,WAAY,sBAAsB,CAAC,CAClG,CAAC,CAAC,IAAK,GAAS,GAAGS,EAAAA,cAAc,GAAG,EAAK,IAAI,EAC7C,CAAC,GAAGA,EAAAA,cAAc,GAAG,EAAe,EAAQ,QAAQ,GAAG,EAAgB,EAAQ,SAAS,EACxF,CAAE,WAAYK,EAAAA,eAAe,EAAQ,WAAY,EAAO,EAAQ,MAAO,CAAO,EACpF,MAAO,CAAE,QAAO,cAAa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
1
+ {"version":3,"file":"index.cjs","names":["fs","path","renderCliEntry","renderServerEntry","renderWebEntry","renderMcpEntry","GENERATED_ENTRY_FILENAMES","scanExtensions","renderMcpWidgets","GENERATED_DIR","BUILD_TARGET_PLATFORMS","resolveTarget","renderApiClient","GENERATED_CLIENT_NAME","API_ROUTES_MODULE","GENERATED_ENTRY_NAMES","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} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient } from '../renderClient';\nimport { renderCliEntry, renderMcpEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { renderMcpWidgets } from '../renderMcpWidgets';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/doompi-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^doompi-/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 renderCliEntry>> = {\n cli: renderCliEntry,\n server: renderServerEntry,\n web: renderWebEntry,\n mcp: renderMcpEntry,\n};\n\n/** The generated entry keeps its historical filename so no consumer has to change. */\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\nconst ENTRY_EXTENSION: Readonly<Record<BuildTarget, string>> = { cli: 'ts', server: 'ts', web: 'ts', mcp: 'ts' };\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 print this 3x.\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 cli, server, web or mcp`,\n });\n }\n\n const requestedTargets = options.target === undefined ? (['cli', 'server', 'web'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n // modes.yaml admits packages through their Pi entry, even when their only feature is a browser layout.\n const templateAdmission =\n target === 'cli' &&\n graph.entries.some(\n (entry) => entry.side === 'frontend' && entry.surface === 'template' && entry.platform === 'web',\n );\n if (\n resolution.contributions.length === 0 &&\n resolution.escapeHatches.length === 0 &&\n resolution.roots.length === 0 &&\n !templateAdmission\n )\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]}.${ENTRY_EXTENSION[target]}`, source);\n }\n\n // Not a fourth 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 if (hasRouteTable && hasBrowserHalf && client === 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]}.${ENTRY_EXTENSION[options.target]}`,\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":"8ZAsBA,SAAgB,EAAgB,EAA6B,CAC3D,OAAO,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,YAAa,EAAE,CACtE,CAEA,SAAS,EAAgB,EAA4B,CACnD,IAAM,EAAW,KAAK,MAAMA,EAAAA,QAAG,aAAaC,EAAAA,QAAK,KAAK,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAO,EAAS,MAAS,SAAU,MAAU,MAAM,GAAG,EAAW,0BAA0B,EAC/F,OAAO,EAAS,IAClB,CAEA,MAAM,EAAkE,CACtE,IAAKC,EAAAA,eACL,OAAQC,EAAAA,kBACR,IAAKC,EAAAA,eACL,IAAKC,EAAAA,cACP,EAGM,EAAwDC,EAAAA,0BACxD,EAAyD,CAAE,IAAK,KAAM,OAAQ,KAAM,IAAK,KAAM,IAAK,IAAK,EAU/G,SAAgB,EAAkB,EAA0C,CAC1E,IAAM,EAAc,EAAQ,aAAe,EAAgB,EAAQ,UAAU,EACvE,EAAW,EAAQ,UAAY,EAAgB,CAAW,EAE1D,EAAwBC,EAAAA,eAAe,CAAO,EAC9C,EAA6B,CAAC,GAAG,EAAM,OAAO,EAC9C,kBAAQ,IAAI,IACZ,EAAyB,CAAC,EAC1B,EAAa,EAAQ,SAAW,MAAQC,EAAAA,iBAAiB,EAAO,EAAaC,EAAAA,aAAa,EAAI,IAAA,GAChG,GAAY,SA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AA,sBAAsB,KAAM,CAAM,EACtF,GAAiB,GAAkB,IAAW,IAAA,IAChD,EAAQ,KAAK,CACX,KAAMC,EAAAA,kBACN,QAAS,2FACX,CAAC,EAGH,IAAM,EACJ,EAAQ,SAAW,IAAA,GACfC,EAAAA,sBAAsB,OACnB,GAAS,IAAS,OAAS,CAACf,EAAAA,QAAG,WAAWC,EAAAA,QAAK,KAAK,EAAQ,WAAY,sBAAsB,CAAC,CAClG,CAAC,CAAC,IAAK,GAAS,GAAGQ,EAAAA,cAAc,GAAG,EAAK,IAAI,EAC7C,CACE,GAAGA,EAAAA,cAAc,GAAG,EAAe,EAAQ,QAAQ,GAAG,EAAgB,EAAQ,UAC9E,GAAI,EAAQ,SAAW,MAAQ,CAAC,GAAGA,EAAAA,cAAc,WAAW,EAAI,CAAC,CACnE,EACA,CAAE,WAAYO,EAAAA,eAAe,EAAQ,WAAY,EAAO,EAAQ,MAAO,CAAO,EACpF,MAAO,CAAE,QAAO,cAAa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/generate/index.ts"],"mappings":";;;wBAqBgB,gBAAgB;;;;;;;;;wBA6BhB,kBAAkB,SAAS,kBAAkB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/generate/index.ts"],"mappings":";;;wBAsBgB,gBAAgB;;;;;;;;;wBA6BhB,kBAAkB,SAAS,kBAAkB"}
@@ -1,2 +1,2 @@
1
- import{API_ROUTES_MODULE as e,BUILD_TARGET_PLATFORMS as t,GENERATED_CLIENT_NAME as n,GENERATED_DIR as r,GENERATED_ENTRY_FILENAMES as i,GENERATED_ENTRY_NAMES as a}from"../../constants/layout.mjs";import{scanExtensions as o}from"../scan/index.mjs";import{resolveTarget as s}from"../resolveTarget/index.mjs";import{renderApiClient as c}from"../renderClient/index.mjs";import{renderCliEntry as l,renderMcpEntry as u,renderServerEntry as d,renderWebEntry as f}from"../renderEntry/index.mjs";import{writeGenerated as p}from"../writeGenerated/index.mjs";import m from"node:fs";import h from"node:path";function g(e){return e.replace(/^@[^/]+\//u,``).replace(/^doompi-/u,``)}function _(e){let t=JSON.parse(m.readFileSync(h.join(e,`package.json`),`utf8`));if(typeof t.name!=`string`)throw Error(`${e}/package.json has no name`);return t.name}const v={cli:l,server:d,web:f,mcp:u},y=i,b={cli:`ts`,server:`ts`,web:`ts`,mcp:`ts`};function x(i){let l=i.packageName??_(i.packageDir),u=i.pluginId??g(l),d=o(i),f=[...d.notices],x=/* @__PURE__ */ new Map,S=[];for(let e of d.entries)e.platform===void 0||t.includes(e.platform)||f.push({path:e.file,message:`'${e.platform}' is a forward-looking platform with no build target; this file is not emitted for cli, server, web or mcp`});let C=i.target===void 0?[`cli`,`server`,`web`]:[i.target];for(let e of C){let t=s(d,e);f.push(...t.notices);let n=e===`cli`&&d.entries.some(e=>e.side===`frontend`&&e.surface===`template`&&e.platform===`web`);if(t.contributions.length===0&&t.escapeHatches.length===0&&t.roots.length===0&&!n)continue;S.push(e);let i=v[e],a=i(t,{packageName:l,pluginId:u,root:d.root,entryDir:r});x.set(`${r}/${y[e]}.${b[e]}`,a)}let w=i.target===void 0&&m.existsSync(h.join(i.packageDir,`src/types/apiRoutes.ts`)),T=S.includes(`web`),E=w&&T?c(d,{packageName:l,pluginId:u,root:d.root,entryDir:r}):void 0;E!==void 0&&x.set(`${r}/${n}.ts`,E),w&&T&&E===void 0&&f.push({path:e,message:`declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted`});let D=i.target===void 0?a.filter(e=>e!==`mcp`||!m.existsSync(h.join(i.packageDir,`tsdown.mcp.config.ts`))).map(e=>`${r}/${e}.ts`):[`${r}/${y[i.target]}.${b[i.target]}`],{changed:O}=p(i.packageDir,x,i.check,D);return{graph:d,packageName:l,pluginId:u,files:x,changed:O,notices:f,targets:S}}export{g as defaultPluginId,x as generateExtension};
1
+ import{API_ROUTES_MODULE as e,BUILD_TARGET_PLATFORMS as t,GENERATED_CLIENT_NAME as n,GENERATED_DIR as r,GENERATED_ENTRY_FILENAMES as i,GENERATED_ENTRY_NAMES as a}from"../../constants/layout.mjs";import{scanExtensions as o}from"../scan/index.mjs";import{resolveTarget as s}from"../resolveTarget/index.mjs";import{renderApiClient as c}from"../renderClient/index.mjs";import{renderCliEntry as l,renderMcpEntry as u,renderServerEntry as d,renderWebEntry as f}from"../renderEntry/index.mjs";import{renderMcpWidgets as p}from"../renderMcpWidgets/index.mjs";import{writeGenerated as m}from"../writeGenerated/index.mjs";import h from"node:fs";import g from"node:path";function _(e){return e.replace(/^@[^/]+\//u,``).replace(/^doompi-/u,``)}function v(e){let t=JSON.parse(h.readFileSync(g.join(e,`package.json`),`utf8`));if(typeof t.name!=`string`)throw Error(`${e}/package.json has no name`);return t.name}const y={cli:l,server:d,web:f,mcp:u},b=i,x={cli:`ts`,server:`ts`,web:`ts`,mcp:`ts`};function S(i){let l=i.packageName??v(i.packageDir),u=i.pluginId??_(l),d=o(i),f=[...d.notices],S=/* @__PURE__ */ new Map,C=[],w=i.target===`mcp`?p(d,l,r):void 0;w?.source!==void 0&&S.set(`${r}/mcp-ui.ts`,w.source);for(let e of d.entries)e.platform===void 0||t.includes(e.platform)||f.push({path:e.file,message:`'${e.platform}' is a forward-looking platform with no build target; this file is not emitted for cli, server, web or mcp`});let T=i.target===void 0?[`cli`,`server`,`web`]:[i.target];for(let e of T){let t=s(d,e);f.push(...t.notices);let n=e===`cli`&&d.entries.some(e=>e.side===`frontend`&&e.surface===`template`&&e.platform===`web`);if(t.contributions.length===0&&t.escapeHatches.length===0&&t.roots.length===0&&!n)continue;C.push(e);let i=y[e],a=i(t,{packageName:l,pluginId:u,root:d.root,entryDir:r,mcpWidgets:w?.declarations});S.set(`${r}/${b[e]}.${x[e]}`,a)}let E=i.target===void 0&&h.existsSync(g.join(i.packageDir,`src/types/apiRoutes.ts`)),D=C.includes(`web`),O=E&&D?c(d,{packageName:l,pluginId:u,root:d.root,entryDir:r}):void 0;O!==void 0&&S.set(`${r}/${n}.ts`,O),E&&D&&O===void 0&&f.push({path:e,message:`declares API routes, but no (backend)/api/<base-path>/ folder says where they are mounted`});let k=i.target===void 0?a.filter(e=>e!==`mcp`||!h.existsSync(g.join(i.packageDir,`tsdown.mcp.config.ts`))).map(e=>`${r}/${e}.ts`):[`${r}/${b[i.target]}.${x[i.target]}`,...i.target===`mcp`?[`${r}/mcp-ui.ts`]:[]],{changed:A}=m(i.packageDir,S,i.check,k);return{graph:d,packageName:l,pluginId:u,files:S,changed:A,notices:f,targets:C}}export{_ as defaultPluginId,S as generateExtension};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"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} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient } from '../renderClient';\nimport { renderCliEntry, renderMcpEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/doompi-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^doompi-/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 renderCliEntry>> = {\n cli: renderCliEntry,\n server: renderServerEntry,\n web: renderWebEntry,\n mcp: renderMcpEntry,\n};\n\n/** The generated entry keeps its historical filename so no consumer has to change. */\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\nconst ENTRY_EXTENSION: Readonly<Record<BuildTarget, string>> = { cli: 'ts', server: 'ts', web: 'ts', mcp: 'ts' };\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\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 print this 3x.\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 cli, server, web or mcp`,\n });\n }\n\n const requestedTargets = options.target === undefined ? (['cli', 'server', 'web'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n // modes.yaml admits packages through their Pi entry, even when their only feature is a browser layout.\n const templateAdmission =\n target === 'cli' &&\n graph.entries.some(\n (entry) => entry.side === 'frontend' && entry.surface === 'template' && entry.platform === 'web',\n );\n if (\n resolution.contributions.length === 0 &&\n resolution.escapeHatches.length === 0 &&\n resolution.roots.length === 0 &&\n !templateAdmission\n )\n continue;\n\n targets.push(target);\n const render = RENDERERS[target];\n const source = render(resolution, { packageName, pluginId, root: graph.root, entryDir: GENERATED_DIR });\n files.set(`${GENERATED_DIR}/${ENTRY_FILENAME[target]}.${ENTRY_EXTENSION[target]}`, source);\n }\n\n // Not a fourth 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 if (hasRouteTable && hasBrowserHalf && client === 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 : [`${GENERATED_DIR}/${ENTRY_FILENAME[options.target]}.${ENTRY_EXTENSION[options.target]}`];\n const { changed } = writeGenerated(options.packageDir, files, options.check, managed);\n return { graph, packageName, pluginId, files, changed, notices, targets };\n}\n"],"mappings":"mlBAqBA,SAAgB,EAAgB,EAA6B,CAC3D,OAAO,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,YAAa,EAAE,CACtE,CAEA,SAAS,EAAgB,EAA4B,CACnD,IAAM,EAAW,KAAK,MAAM,EAAG,aAAa,EAAK,KAAK,EAAY,cAAc,EAAG,MAAM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G,EAAgB,KAAW,CAAM,CAC3F,CAUA,IAAM,EAAgB,EAAQ,SAAW,IAAA,IAAa,EAAG,WAAW,EAAK,KAAK,EAAQ,WAAA,wBAA6B,CAAC,EAC9G,EAAiB,EAAQ,SAAS,KAAK,EACvC,EACJ,GAAiB,EACb,EAAgB,EAAO,CAAE,cAAa,WAAU,KAAM,EAAM,KAAM,SAAU,CAAc,CAAC,EAC3F,IAAA,GACF,IAAW,IAAA,IAAW,EAAM,IAAI,GAAG,EAAc,GAAG,EAAsB,KAAM,CAAM,EACtF,GAAiB,GAAkB,IAAW,IAAA,IAChD,EAAQ,KAAK,CACX,KAAM,EACN,QAAS,2FACX,CAAC,EAGH,IAAM,EACJ,EAAQ,SAAW,IAAA,GACf,EAAsB,OACnB,GAAS,IAAS,OAAS,CAAC,EAAG,WAAW,EAAK,KAAK,EAAQ,WAAY,sBAAsB,CAAC,CAClG,CAAC,CAAC,IAAK,GAAS,GAAG,EAAc,GAAG,EAAK,IAAI,EAC7C,CAAC,GAAG,EAAc,GAAG,EAAe,EAAQ,QAAQ,GAAG,EAAgB,EAAQ,SAAS,EACxF,CAAE,WAAY,EAAe,EAAQ,WAAY,EAAO,EAAQ,MAAO,CAAO,EACpF,MAAO,CAAE,QAAO,cAAa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
1
+ {"version":3,"file":"index.mjs","names":[],"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} from '../../constants/layout';\nimport type { ExtensionGraph, ExtensionNotice } from '../../types/extensionGraph';\nimport { renderApiClient } from '../renderClient';\nimport { renderCliEntry, renderMcpEntry, renderServerEntry, renderWebEntry } from '../renderEntry';\nimport { renderMcpWidgets } from '../renderMcpWidgets';\nimport { resolveTarget } from '../resolveTarget';\nimport type { BuildTarget } from '../resolveTarget/type';\nimport { scanExtensions } from '../scan';\nimport { writeGenerated } from '../writeGenerated';\nimport type { GenerateOptions, GenerateResult } from './type';\n\n/** `@agimon-ai/doompi-plan` becomes `plan`. */\nexport function defaultPluginId(packageName: string): string {\n return packageName.replace(/^@[^/]+\\//u, '').replace(/^doompi-/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 renderCliEntry>> = {\n cli: renderCliEntry,\n server: renderServerEntry,\n web: renderWebEntry,\n mcp: renderMcpEntry,\n};\n\n/** The generated entry keeps its historical filename so no consumer has to change. */\nconst ENTRY_FILENAME: Readonly<Record<BuildTarget, string>> = GENERATED_ENTRY_FILENAMES;\nconst ENTRY_EXTENSION: Readonly<Record<BuildTarget, string>> = { cli: 'ts', server: 'ts', web: 'ts', mcp: 'ts' };\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 print this 3x.\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 cli, server, web or mcp`,\n });\n }\n\n const requestedTargets = options.target === undefined ? (['cli', 'server', 'web'] as const) : [options.target];\n for (const target of requestedTargets) {\n const resolution = resolveTarget(graph, target);\n notices.push(...resolution.notices);\n // modes.yaml admits packages through their Pi entry, even when their only feature is a browser layout.\n const templateAdmission =\n target === 'cli' &&\n graph.entries.some(\n (entry) => entry.side === 'frontend' && entry.surface === 'template' && entry.platform === 'web',\n );\n if (\n resolution.contributions.length === 0 &&\n resolution.escapeHatches.length === 0 &&\n resolution.roots.length === 0 &&\n !templateAdmission\n )\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]}.${ENTRY_EXTENSION[target]}`, source);\n }\n\n // Not a fourth 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 if (hasRouteTable && hasBrowserHalf && client === 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]}.${ENTRY_EXTENSION[options.target]}`,\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":"opBAsBA,SAAgB,EAAgB,EAA6B,CAC3D,OAAO,EAAY,QAAQ,aAAc,EAAE,CAAC,CAAC,QAAQ,YAAa,EAAE,CACtE,CAEA,SAAS,EAAgB,EAA4B,CACnD,IAAM,EAAW,KAAK,MAAM,EAAG,aAAa,EAAK,KAAK,EAAY,cAAc,EAAG,MAAM,CAAC,EAC1F,GAAI,OAAO,EAAS,MAAS,SAAU,MAAU,MAAM,GAAG,EAAW,0BAA0B,EAC/F,OAAO,EAAS,IAClB,CAEA,MAAM,EAAkE,CACtE,IAAK,EACL,OAAQ,EACR,IAAK,EACL,IAAK,CACP,EAGM,EAAwD,EACxD,EAAyD,CAAE,IAAK,KAAM,OAAQ,KAAM,IAAK,KAAM,IAAK,IAAK,EAU/G,SAAgB,EAAkB,EAA0C,CAC1E,IAAM,EAAc,EAAQ,aAAe,EAAgB,EAAQ,UAAU,EACvE,EAAW,EAAQ,UAAY,EAAgB,CAAW,EAE1D,EAAwB,EAAe,CAAO,EAC9C,EAA6B,CAAC,GAAG,EAAM,OAAO,EAC9C,kBAAQ,IAAI,IACZ,EAAyB,CAAC,EAC1B,EAAa,EAAQ,SAAW,MAAQ,EAAiB,EAAO,EAAa,CAAa,EAAI,IAAA,GAChG,GAAY,S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S,2FACX,CAAC,EAGH,IAAM,EACJ,EAAQ,SAAW,IAAA,GACf,EAAsB,OACnB,GAAS,IAAS,OAAS,CAAC,EAAG,WAAW,EAAK,KAAK,EAAQ,WAAY,sBAAsB,CAAC,CAClG,CAAC,CAAC,IAAK,GAAS,GAAG,EAAc,GAAG,EAAK,IAAI,EAC7C,CACE,GAAG,EAAc,GAAG,EAAe,EAAQ,QAAQ,GAAG,EAAgB,EAAQ,UAC9E,GAAI,EAAQ,SAAW,MAAQ,CAAC,GAAG,EAAc,WAAW,EAAI,CAAC,CACnE,EACA,CAAE,WAAY,EAAe,EAAQ,WAAY,EAAO,EAAQ,MAAO,CAAO,EACpF,MAAO,CAAE,QAAO,cAAa,WAAU,QAAO,UAAS,UAAS,SAAQ,CAC1E"}
@@ -3,6 +3,6 @@ const e=require("../identity/index.cjs");let t=require("node:path");const n=`//
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
  `)}function f(){return[`/* v8 ignore next -- generated normalization branch */`,`const keyed = <T>(key: string, value: T | undefined): Record<string, T> =>`,` value === undefined ? {} : { [key]: value };`].join(`
5
5
  `)}const p=[`const via = <T>(identity: Record<string, unknown>, value: unknown): T =>`,` (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;`].join(`
6
- `);function m(t,n){return n===void 0?{id:e.toKebab(t)}:{slot:n,id:e.toKebab(t)}}const h={tool:t=>({name:e.toSnake(t)}),command:t=>({name:e.toKebab(t)}),channel:t=>({frameType:e.toSnake(t)}),hook:t=>({event:e.toSnake(t)}),mode:t=>({name:e.toKebab(t)})},g={tool:t=>({tools:[e.toSnake(t)]}),channel:t=>({channel:e.toSnake(t)}),slot:(t,n)=>({slot:`${n.pluginId}.${e.toKebab(t)}`}),command:t=>({id:e.toKebab(t)}),tab:t=>({id:e.toKebab(t)}),template:t=>({id:e.toKebab(t)}),dock:t=>({id:e.toKebab(t)}),setting:t=>({id:e.toKebab(t)}),action:t=>({id:e.toKebab(t)}),mode:t=>({name:e.toKebab(t)}),"activity-group":t=>({name:e.toKebab(t)}),"selection-axis":t=>({name:e.toKebab(t)}),leader:(t,n)=>({id:`${n.pluginId}.${e.toKebab(t)}`})};function _(e,t,n){let{entry:r}=e,i=r.surface;if(i!==void 0)return t===`web`?i===`fill`?m(r.name,r.target):g[i]?.(r.name,n):h[i]?.(r.name)}function v(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 y(e,t){return v([e.entry.surface??`extra`,e.entry.name],t)}function b(e,n){let r=e.replace(/\.[^.]+$/u,``),i=t.posix.relative(n,r);return i.startsWith(`.`)?i:`./${i}`}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=y(r,n),a=r.renderers;return{identifier:i,contribution:r,identity:_(r,e.target,t),renderers:a===void 0?void 0:{identifier:v([`render`,a.name],n),file:a.file}}})}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(t,n,r){if(o.includes(t.contribution.field))return`${t.identifier}(${n})`;let i=r===`web`?t.identifier:`at(${t.identifier}, ${n})`;if(r===`cli`&&t.contribution.entry.surface===`command`&&t.contribution.entry.platform===`cli`)return i;let s=t.renderers===void 0?i:`withPiRenderers(${i}, at(${t.renderers.identifier}, ${n}))`,c=a[r].includes(t.contribution.field);if(t.contribution.entry.cardinality===`collection`)return s;if(t.identity===void 0)return c?t.identifier:s;let l=e.renderIdentity(t.identity);return c?`() => via({ ${l} }, ${t.identifier}())`:`via({ ${l} }, ${s})`}function O(e,t,n,r){return e!==`tools`||t!==`cli`?`${e}: ${n},`:`...piToolContributions('${r.packageName}', ${n}),`}function k(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/doompi-core/serverFacet';`}function A(e,t){let n=[`definePiExtension`];e.some(e=>e.includes(`piToolContributions(`))&&n.push(`piToolContributions`),e.some(e=>e.includes(`withPiRenderers(`))&&n.push(`withPiRenderers`);let r=[...e.some(e=>e.includes(`at(`))||t?[`type PiPluginContext`]:[],...e.some(e=>e.includes(c.cli))?[`type ${c.cli}`]:[]];return`import { ${[...n,...r].join(`, `)} } from '@agimon-ai/doompi-core/piExtension';`}function j(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 M(t,n,a,o,s){let c=/* @__PURE__ */ new Map;for(let e of t){let t=c.get(e.contribution.field);t===void 0?c.set(e.contribution.field,[e]):t.push(e)}let l=[];for(let t of[...c.keys()].sort()){let u=c.get(t);if(r.includes(t)){l.push(`${n}${t}: {`);for(let t of u){let r=e.toSnake(t.contribution.entry.name),i=`at(${t.identifier}, ${a(t)})`,s=o===`cli`?`${i} as NonNullable<PiPluginContributions['events']>['${r}']`:i;l.push(t.contribution.entry.cardinality===`optional`?`${n} ...keyed('${r}', ${s}),`:`${n} ${r}: ${s},`)}l.push(`${n}},`);continue}if(o===`cli`&&u.length===1&&u[0]?.contribution.entry.cardinality===`collection`){let e=u[0],r=D(e,a(e),o);l.push(`${n}${j(t,O(t,o,r,s),o)}`);continue}if(i.includes(t)){let e=u[0];if(e){let r=D(e,a(e),o);l.push(`${n}${j(t,`${t}: ${r},`,o)}`)}continue}let d=`[${u.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${a(e)})`:D(e,a(e),o)).join(`, `)}]`,f=u.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${d})`:d;l.push(`${n}${j(t,O(t,o,f,s),o)}`)}return l}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 '${b(e.entry.file,r)}';`),...e.flatMap(e=>[`import ${e.identifier} from '${b(e.contribution.entry.file,r)}';`,...e.renderers===void 0?[]:[`import ${e.renderers.identifier} from '${b(e.renderers.file,r)}';`]]),...t.map(e=>`import ${e.identifier} from '${b(e.entry.file,r)}';`)]}function F(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
7
- `)}function I(e){return e.length===0?[]:[`type OptionsOf<T> = T extends (context: PiPluginContext<infer Options>) => unknown ? Options : never;`,`type InferredOptions = Exclude<${e.map(e=>`OptionsOf<typeof ${e}>`).join(` | `)}, undefined>;`,`type Intersect<Union> =`,` (Union extends unknown ? (value: Union) => void : never) extends (value: infer Value) => void ? Value : never;`,`type ExtensionOptions = [InferredOptions] extends [never] ? undefined : Intersect<InferredOptions>;`,``]}function L(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(`keyed(`))&&t.push(f()),e.some(e=>e.includes(`via(`))&&t.push(p),t.length>0?[...t,``]:[]}function R(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function z(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}${R(n)} => ({`,...i,`${r}}),`]:[`${a}${R([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function B(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function V(e,t){let r=x(e,t),i=E(e.escapeHatches),a=C(e.roots),o=a[a.length-1]?.context??`context`,s=[...N(M(r,` `,e=>T(a,e.contribution.entry.scope,`context`),`cli`,t),a,`cli`,` `,`session`),...i.map(e=>` ...await at(${e.identifier}, ${o}),`)],c=w(a,`context`,s),l=z(c,B(a),s,``),u=[...a.map(e=>e.identifier),...r.map(e=>e.identifier),...i.map(e=>e.identifier)],d=u.length>0;return F([n,A([...c,...s],d),...a.length>0?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...P(r,i,a,t.entryDir),``,...I(u),...L(s),`export const extension = definePiExtension${d?`<ExtensionOptions>`:``}('${t.packageName}', ${l[0]}`,...l.slice(1,-1),`${l[l.length-1]?.replace(/,$/u,``)});`,``,`export default extension;`,``])}function H(e,t){let r=x(e,t),i=E(e.escapeHatches),a=C(e.roots),o=[],c=!1;for(let[e,n]of s.entries()){let l=r.filter(t=>s.indexOf(t.contribution.entry.scope)<=e),u=i.filter(t=>s.indexOf(t.entry.scope)<=e),d=a.filter(t=>s.indexOf(t.entry.scope)<=e),f=d[d.length-1]?.context??`context`,p=[...N(M(l,` `,e=>T(d,e.contribution.entry.scope,`context`),`server`,t),d,`server`,` `,n),...u.map(e=>` ...await at(${e.identifier}, ${f}),`)];if(p.length===0&&d.length===0)continue;d.length>0&&(c=!0);let m=z(w(d,`context`,p),B(d),p,` `);o.push(` ${n}: ${m[0]}`,...m.slice(1))}return F([n,k(o),...c?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...P(r,i,a,t.entryDir),``,...L(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...o,`});`,``,`export default facet;`,``])}function U(e,t){let r=x(e,t),i=M(r,` `,()=>`context`,`mcp`,t);return F([n,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';`,``,...P(r,[],[],t.entryDir),``,...L(i),`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...i,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}function W(e,t){let r=x(e,t),i=E(e.escapeHatches),a=[];for(let e of s){let n=r.filter(t=>t.contribution.entry.scope===e),o=i.filter(t=>t.entry.scope===e),s=[...M(n,` `,()=>`undefined`,`web`,t),...o.map(e=>` ...${e.identifier},`)];s.length!==0&&a.push(` ${e}: {`,...s,` },`)}return F([n,a.some(e=>e.includes(`get `))?`import { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/doompi-core/web';`:`import { defineWebPlugin } from '@agimon-ai/doompi-core/web';`,``,...P(r,i,[],t.entryDir),``,...L(a),`export const webPlugin = defineWebPlugin({`,` id: '${t.pluginId}',`,...a,`});`,``])}exports.renderCliEntry=V,exports.renderMcpEntry=U,exports.renderServerEntry=H,exports.renderWebEntry=W;
6
+ `);function m(t,n){return n===void 0?{id:e.toKebab(t)}:{slot:n,id:e.toKebab(t)}}const h={tool:t=>({name:e.toSnake(t)}),command:t=>({name:e.toKebab(t)}),channel:t=>({frameType:e.toSnake(t)}),hook:t=>({event:e.toSnake(t)}),mode:t=>({name:e.toKebab(t)})},g={tool:t=>({tools:[e.toSnake(t)]}),channel:t=>({channel:e.toSnake(t)}),slot:(t,n)=>({slot:`${n.pluginId}.${e.toKebab(t)}`}),command:t=>({id:e.toKebab(t)}),tab:t=>({id:e.toKebab(t)}),template:t=>({id:e.toKebab(t)}),dock:t=>({id:e.toKebab(t)}),setting:t=>({id:e.toKebab(t)}),action:t=>({id:e.toKebab(t)}),mode:t=>({name:e.toKebab(t)}),"activity-group":t=>({name:e.toKebab(t)}),"selection-axis":t=>({name:e.toKebab(t)}),leader:(t,n)=>({id:`${n.pluginId}.${e.toKebab(t)}`})};function _(e,t,n){let{entry:r}=e,i=r.surface;if(i!==void 0)return t===`web`?i===`fill`?m(r.name,r.target):g[i]?.(r.name,n):h[i]?.(r.name)}function v(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 y(e,t){return v([e.entry.surface??`extra`,e.entry.name],t)}function b(e,n){let r=e.replace(/\.[^.]+$/u,``),i=t.posix.relative(n,r);return i.startsWith(`.`)?i:`./${i}`}function x(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function S(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=y(r,n),a=r.renderers,o=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(o!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(o))throw Error(`Invalid MCP widget key '${o}'`);return{identifier:i,contribution:r,identity:_(r,e.target,t),mcpWidget:o,renderers:a===void 0?void 0:{identifier:v([`render`,a.name],n),file:a.file}}})}const C={global:0,workspace:1,session:2};function w(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 T(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 E(e,t,n){let r=n;for(let n of e)C[n.entry.scope]<=C[t]&&(r=n.context);return r}function D(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function O(t,n,r){if(o.includes(t.contribution.field))return`${t.identifier}(${n})`;let i=r===`web`?t.identifier:`at(${t.identifier}, ${n})`;if(r===`cli`&&t.contribution.entry.surface===`command`&&t.contribution.entry.platform===`cli`)return i;let s=t.renderers===void 0?i:`withPiRenderers(${i}, at(${t.renderers.identifier}, ${n}))`,c=a[r].includes(t.contribution.field);if(t.contribution.entry.cardinality===`collection`)return s;if(t.identity===void 0)return c?t.identifier:s;let l=e.renderIdentity(t.identity);if(c)return`() => via({ ${l} }, ${t.identifier}())`;let u=`via({ ${l} }, ${s})`;return t.mcpWidget===void 0?u:`withWidget(${x(t.mcpWidget)}, ${u})`}function k(e,t,n,r){return e!==`tools`||t!==`cli`?`${e}: ${n},`:`...piToolContributions('${r.packageName}', ${n}),`}function A(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/doompi-core/serverFacet';`}function j(e,t){let n=[`definePiExtension`];e.some(e=>e.includes(`piToolContributions(`))&&n.push(`piToolContributions`),e.some(e=>e.includes(`withPiRenderers(`))&&n.push(`withPiRenderers`);let r=[...e.some(e=>e.includes(`at(`))||t?[`type PiPluginContext`]:[],...e.some(e=>e.includes(c.cli))?[`type ${c.cli}`]:[]];return`import { ${[...n,...r].join(`, `)} } from '@agimon-ai/doompi-core/piExtension';`}function M(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 N(t,n,a,o,s){let c=/* @__PURE__ */ new Map;for(let e of t){let t=c.get(e.contribution.field);t===void 0?c.set(e.contribution.field,[e]):t.push(e)}let l=[];for(let t of[...c.keys()].sort()){let u=c.get(t);if(r.includes(t)){l.push(`${n}${t}: {`);for(let t of u){let r=e.toSnake(t.contribution.entry.name),i=`at(${t.identifier}, ${a(t)})`,s=o===`cli`?`${i} as NonNullable<PiPluginContributions['events']>['${r}']`:i;l.push(t.contribution.entry.cardinality===`optional`?`${n} ...keyed('${r}', ${s}),`:`${n} ${r}: ${s},`)}l.push(`${n}},`);continue}if(o===`cli`&&u.length===1&&u[0]?.contribution.entry.cardinality===`collection`){let e=u[0],r=O(e,a(e),o);l.push(`${n}${M(t,k(t,o,r,s),o)}`);continue}if(i.includes(t)){let e=u[0];if(e){let r=O(e,a(e),o);l.push(`${n}${M(t,`${t}: ${r},`,o)}`)}continue}let d=`[${u.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${a(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${x(e.mcpWidget)}, tool))`}`:O(e,a(e),o)).join(`, `)}]`,f=u.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${d})`:d;l.push(`${n}${M(t,k(t,o,f,s),o)}`)}return l}function P(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 F(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${b(e.entry.file,r)}';`),...e.flatMap(e=>[`import ${e.identifier} from '${b(e.contribution.entry.file,r)}';`,...e.renderers===void 0?[]:[`import ${e.renderers.identifier} from '${b(e.renderers.file,r)}';`]]),...t.map(e=>`import ${e.identifier} from '${b(e.entry.file,r)}';`)]}function I(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
7
+ `)}function L(e){return e.length===0?[]:[`type OptionsOf<T> = T extends (context: PiPluginContext<infer Options>) => unknown ? Options : never;`,`type InferredOptions = Exclude<${e.map(e=>`OptionsOf<typeof ${e}>`).join(` | `)}, undefined>;`,`type Intersect<Union> =`,` (Union extends unknown ? (value: Union) => void : never) extends (value: infer Value) => void ? Value : never;`,`type ExtensionOptions = [InferredOptions] extends [never] ? undefined : Intersect<InferredOptions>;`,``]}function R(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(`keyed(`))&&t.push(f()),e.some(e=>e.includes(`via(`))&&t.push(p),t.length>0?[...t,``]:[]}function z(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function B(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}${z(n)} => ({`,...i,`${r}}),`]:[`${a}${z([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function V(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function H(e,t){let r=S(e,t),i=D(e.escapeHatches),a=w(e.roots),o=a[a.length-1]?.context??`context`,s=[...P(N(r,` `,e=>E(a,e.contribution.entry.scope,`context`),`cli`,t),a,`cli`,` `,`session`),...i.map(e=>` ...await at(${e.identifier}, ${o}),`)],c=T(a,`context`,s),l=B(c,V(a),s,``),u=[...a.map(e=>e.identifier),...r.map(e=>e.identifier),...i.map(e=>e.identifier)],d=u.length>0;return I([n,j([...c,...s],d),...a.length>0?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...F(r,i,a,t.entryDir),``,...L(u),...R(s),`export const extension = definePiExtension${d?`<ExtensionOptions>`:``}('${t.packageName}', ${l[0]}`,...l.slice(1,-1),`${l[l.length-1]?.replace(/,$/u,``)});`,``,`export default extension;`,``])}function U(e,t){let r=S(e,t),i=D(e.escapeHatches),a=w(e.roots),o=[],c=!1;for(let[e,n]of s.entries()){let l=r.filter(t=>s.indexOf(t.contribution.entry.scope)<=e),u=i.filter(t=>s.indexOf(t.entry.scope)<=e),d=a.filter(t=>s.indexOf(t.entry.scope)<=e),f=d[d.length-1]?.context??`context`,p=[...P(N(l,` `,e=>E(d,e.contribution.entry.scope,`context`),`server`,t),d,`server`,` `,n),...u.map(e=>` ...await at(${e.identifier}, ${f}),`)];if(p.length===0&&d.length===0)continue;d.length>0&&(c=!0);let m=B(T(d,`context`,p),V(d),p,` `);o.push(` ${n}: ${m[0]}`,...m.slice(1))}return I([n,A(o),...c?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...F(r,i,a,t.entryDir),``,...R(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...o,`});`,``,`export default facet;`,``])}function W(e,t){let r=S(e,t),i=N(r,` `,()=>`context`,`mcp`,t);return I([n,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';`,``,...F(r,[],[],t.entryDir),``,...R(i),...r.some(e=>e.mcpWidget!==void 0)?[`const withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({`,` ...value, _meta: { ...(value as { _meta?: object })._meta, ["doompi/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...i,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}function G(e,t){let r=S(e,t),i=D(e.escapeHatches),a=[];for(let e of s){let n=r.filter(t=>t.contribution.entry.scope===e),o=i.filter(t=>t.entry.scope===e),s=[...N(n,` `,()=>`undefined`,`web`,t),...o.map(e=>` ...${e.identifier},`)];s.length!==0&&a.push(` ${e}: {`,...s,` },`)}return I([n,a.some(e=>e.includes(`get `))?`import { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/doompi-core/web';`:`import { defineWebPlugin } from '@agimon-ai/doompi-core/web';`,``,...F(r,i,[],t.entryDir),``,...R(a),`export const webPlugin = defineWebPlugin({`,` id: '${t.pluginId}',`,...a,`});`,``])}exports.renderCliEntry=H,exports.renderMcpEntry=W,exports.renderServerEntry=U,exports.renderWebEntry=G;
8
8
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["toKebab","toSnake","posix","renderIdentity"],"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 type { BuildTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/doompi-build. Do not edit by hand.';\n\n/** The one field that is a record keyed by event name rather than an array. */\nconst RECORD_FIELDS: readonly string[] = ['events'];\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 cli: ['channels'],\n server: ['channels'],\n web: [],\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 cli: 'PiPluginContributions',\n server: 'DoomServerSessionPlugin',\n web: '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\nfunction keyedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const keyed = <T>(key: string, value: T | undefined): Record<string, T> =>',\n ' value === undefined ? {} : { [key]: value };',\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 // Only the server reads this; the CLI keys its events record by the same 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 (target !== 'web') 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 /** The paired presentation file, when one is folded into this contribution. */\n readonly renderers: { readonly identifier: string; readonly file: string } | undefined;\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 paired = contribution.renderers;\n return {\n identifier,\n contribution,\n identity: identityFor(contribution, resolution.target, options),\n renderers:\n paired === undefined\n ? undefined\n : { identifier: uniqueIdentifier(['render', paired.name], taken), file: paired.file },\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 base = target === 'web' ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n // Pi command tuples already carry their native name and handler. A path\n // identity spread would turn the tuple into an object and lose both.\n if (\n target === 'cli' &&\n binding.contribution.entry.surface === 'command' &&\n binding.contribution.entry.platform === 'cli'\n )\n return base;\n // A terminal tool renderer is a field of the tool declaration, not a\n // registration of its own, so the pair is merged at runtime: three tool\n // shapes reach this array and each holds renderers somewhere different.\n const resolved =\n binding.renderers === undefined\n ? base\n : `withPiRenderers(${base}, at(${binding.renderers.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 return `via({ ${identity} }, ${resolved})`;\n}\n\n/**\n * The CLI keeps replacements apart from additions, and only the value knows\n * which a tool is. A tool that claims a name Pi already ships is an override\n * claim the host arbitrates, not a second registration, but both are authored\n * in `tool/`, so the path cannot tell them apart. The generated entry defers\n * to a runtime split instead.\n */\nfunction wrapField(field: string, target: BuildTarget, rendered: string, options: RenderOptions): string {\n if (field !== 'tools' || target !== 'cli') return `${field}: ${rendered},`;\n return `...piToolContributions('${options.packageName}', ${rendered}),`;\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/doompi-core/serverFacet';`;\n}\n\n/** The CLI entry imports only what its body and inferred options use. */\nfunction cliImport(body: readonly string[], infersOptions: boolean): string {\n const named = ['definePiExtension'];\n if (body.some((line) => line.includes('piToolContributions('))) named.push('piToolContributions');\n if (body.some((line) => line.includes('withPiRenderers('))) named.push('withPiRenderers');\n const types = [\n ...(body.some((line) => line.includes('at(')) || infersOptions ? ['type PiPluginContext'] : []),\n ...(body.some((line) => line.includes(CONTRIBUTIONS_TYPE.cli)) ? [`type ${CONTRIBUTIONS_TYPE.cli}`] : []),\n ];\n return `import { ${[...named, ...types].join(', ')} } from '@agimon-ai/doompi-core/piExtension';`;\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 options: RenderOptions,\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 (RECORD_FIELDS.includes(field)) {\n lines.push(`${indent}${field}: {`);\n for (const entry of members) {\n const key = toSnake(entry.contribution.entry.name);\n const resolved = `at(${entry.identifier}, ${contextOf(entry)})`;\n const value =\n target === 'cli' ? `${resolved} as NonNullable<PiPluginContributions['events']>['${key}']` : resolved;\n lines.push(\n entry.contribution.entry.cardinality === 'optional'\n ? `${indent} ...keyed('${key}', ${value}),`\n : `${indent} ${key}: ${value},`,\n );\n }\n lines.push(`${indent}},`);\n continue;\n }\n if (target === 'cli' && members.length === 1 && members[0]?.contribution.entry.cardinality === 'collection') {\n const entry = members[0];\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, wrapField(field, target, rendered, options), target)}`);\n continue;\n }\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)})`\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, wrapField(field, target, rendered, options), 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: 'cli' | '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.flatMap((b) => [\n `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`,\n ...(b.renderers === undefined\n ? []\n : [`import ${b.renderers.identifier} from '${specifierFor(b.renderers.file, entryDir)}';`]),\n ]),\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/** Infers the public Pi options contract from authored context factories. */\nfunction cliOptionsType(identifiers: readonly string[]): string[] {\n if (identifiers.length === 0) return [];\n const members = identifiers.map((identifier) => `OptionsOf<typeof ${identifier}>`).join(' | ');\n return [\n 'type OptionsOf<T> = T extends (context: PiPluginContext<infer Options>) => unknown ? Options : never;',\n `type InferredOptions = Exclude<${members}, undefined>;`,\n 'type Intersect<Union> =',\n ' (Union extends unknown ? (value: Union) => void : never) extends (value: infer Value) => void ? Value : never;',\n 'type ExtensionOptions = [InferredOptions] extends [never] ? undefined : Intersect<InferredOptions>;',\n '',\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('keyed('))) lines.push(keyedResolver());\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/** The interactive terminal entry. One mount, so every backend contribution lands in it. */\nexport function renderCliEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n // One mount, so every root in the tree applies, whatever its scope.\n const roots = rootBindings(resolution.roots);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(bindings, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'cli', options),\n roots,\n 'cli',\n ' ',\n 'session',\n ),\n ...hatches.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n const prologue = rootPrologue(roots, 'context', body);\n const factory = scopeBody(prologue, rootHooks(roots), body, '');\n const optionIdentifiers = [\n ...roots.map((root) => root.identifier),\n ...bindings.map((binding) => binding.identifier),\n ...hatches.map((hatch) => hatch.identifier),\n ];\n const infersOptions = optionIdentifiers.length > 0;\n\n return compact([\n HEADER,\n cliImport([...prologue, ...body], infersOptions),\n ...(roots.length > 0 ? [\"import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, roots, options.entryDir),\n '',\n ...cliOptionsType(optionIdentifiers),\n ...resolverFor(body),\n `export const extension = definePiExtension${infersOptions ? '<ExtensionOptions>' : ''}('${options.packageName}', ${factory[0]}`,\n ...factory.slice(1, -1),\n `${factory[factory.length - 1]?.replace(/,$/u, '')});`,\n '',\n 'export default extension;',\n '',\n ]);\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(\n visible,\n ' ',\n (b) => contextForScope(roots, b.contribution.entry.scope, 'context'),\n 'server',\n options,\n ),\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 ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\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', options);\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';\",\n '',\n ...importsFor(bindings, [], [], options.entryDir),\n '',\n ...resolverFor(body),\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/**\n * The cockpit 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 */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\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', 'web', options),\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 return compact([\n HEADER,\n scopes.some((line) => line.includes('get '))\n ? \"import { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/doompi-core/web';\"\n : \"import { defineWebPlugin } from '@agimon-ai/doompi-core/web';\",\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const webPlugin = defineWebPlugin({',\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n"],"mappings":"oEAOA,MAAM,EAAS,gEAGT,EAAmC,CAAC,QAAQ,EAE5C,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtF,EAAmE,CACvE,IAAK,CAAC,UAAU,EAChB,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,IAAK,CAAC,CACR,EAYM,EAA2C,CAAC,UAAU,EAEtD,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1E,EAA4D,CAChE,IAAK,wBACL,OAAQ,0BACR,IAAK,yBACL,IAAK,sBACP,EAOA,SAAS,GAAmB,CAC1B,MAAO,CACL,0CACA,gEACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CAGA,SAAS,GAAuB,CAC9B,MAAO,CACL,6DACA,kGACA,kGACA,iEACA,IACF,CAAC,CAAC,KAAK;CAAI,CACb,CAEA,SAAS,GAA0B,CACjC,MAAO,CACL,yDACA,kEACA,8DACF,CAAC,CAAC,KAAK;CAAI,CACb,CAEA,SAAS,GAAwB,CAC/B,MAAO,CACL,yDACA,6EACA,gDACF,CAAC,CAAC,KAAK;CAAI,CACb,CAgBA,MAAM,EAAkB,CACtB,2EACA,mFACF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EAAS,WAAc,YAAa,MAAO,CAAO,EAG7D,GAAG,EAAK,IAAK,GAAU,UAAU,EAAM,WAAW,EAAE,CACtD,EACI,EAAK,SAAW,GACpB,EAAO,KAAK,KAAK,EAAM,KAAM,GAAG,EAAM,MAAM,CAC9C,CAEA,OAAO,EAAQ,CACb,EACA,EAAO,KAAM,GAAS,EAAK,SAAS,MAAM,CAAC,EACvC,6FACA,gEACJ,GACA,GAAG,EAAW,EAAU,EAAS,CAAC,EAAG,EAAQ,QAAQ,EACrD,GACA,GAAG,EAAY,CAAM,EACrB,6CACA,UAAU,EAAQ,SAAS,IAC3B,GAAG,EACH,MACA,EACF,CAAC,CACH"}
1
+ {"version":3,"file":"index.cjs","names":["toKebab","toSnake","posix","renderIdentity"],"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 type { BuildTarget, ResolvedContribution, TargetResolution } from '../resolveTarget/type';\nimport type { RenderOptions } from './type';\n\nconst HEADER = '// Generated by @agimon-ai/doompi-build. Do not edit by hand.';\n\n/** The one field that is a record keyed by event name rather than an array. */\nconst RECORD_FIELDS: readonly string[] = ['events'];\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 cli: ['channels'],\n server: ['channels'],\n web: [],\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 cli: 'PiPluginContributions',\n server: 'DoomServerSessionPlugin',\n web: '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\nfunction keyedResolver(): string {\n return [\n '/* v8 ignore next -- generated normalization branch */',\n 'const keyed = <T>(key: string, value: T | undefined): Record<string, T> =>',\n ' value === undefined ? {} : { [key]: value };',\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 // Only the server reads this; the CLI keys its events record by the same 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 (target !== 'web') 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 /** The paired presentation file, when one is folded into this contribution. */\n readonly renderers: { readonly identifier: string; readonly file: 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 paired = contribution.renderers;\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 renderers:\n paired === undefined\n ? undefined\n : { identifier: uniqueIdentifier(['render', paired.name], taken), file: paired.file },\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 base = target === 'web' ? binding.identifier : `at(${binding.identifier}, ${contextExpression})`;\n // Pi command tuples already carry their native name and handler. A path\n // identity spread would turn the tuple into an object and lose both.\n if (\n target === 'cli' &&\n binding.contribution.entry.surface === 'command' &&\n binding.contribution.entry.platform === 'cli'\n )\n return base;\n // A terminal tool renderer is a field of the tool declaration, not a\n // registration of its own, so the pair is merged at runtime: three tool\n // shapes reach this array and each holds renderers somewhere different.\n const resolved =\n binding.renderers === undefined\n ? base\n : `withPiRenderers(${base}, at(${binding.renderers.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/**\n * The CLI keeps replacements apart from additions, and only the value knows\n * which a tool is. A tool that claims a name Pi already ships is an override\n * claim the host arbitrates, not a second registration, but both are authored\n * in `tool/`, so the path cannot tell them apart. The generated entry defers\n * to a runtime split instead.\n */\nfunction wrapField(field: string, target: BuildTarget, rendered: string, options: RenderOptions): string {\n if (field !== 'tools' || target !== 'cli') return `${field}: ${rendered},`;\n return `...piToolContributions('${options.packageName}', ${rendered}),`;\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/doompi-core/serverFacet';`;\n}\n\n/** The CLI entry imports only what its body and inferred options use. */\nfunction cliImport(body: readonly string[], infersOptions: boolean): string {\n const named = ['definePiExtension'];\n if (body.some((line) => line.includes('piToolContributions('))) named.push('piToolContributions');\n if (body.some((line) => line.includes('withPiRenderers('))) named.push('withPiRenderers');\n const types = [\n ...(body.some((line) => line.includes('at(')) || infersOptions ? ['type PiPluginContext'] : []),\n ...(body.some((line) => line.includes(CONTRIBUTIONS_TYPE.cli)) ? [`type ${CONTRIBUTIONS_TYPE.cli}`] : []),\n ];\n return `import { ${[...named, ...types].join(', ')} } from '@agimon-ai/doompi-core/piExtension';`;\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 options: RenderOptions,\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 (RECORD_FIELDS.includes(field)) {\n lines.push(`${indent}${field}: {`);\n for (const entry of members) {\n const key = toSnake(entry.contribution.entry.name);\n const resolved = `at(${entry.identifier}, ${contextOf(entry)})`;\n const value =\n target === 'cli' ? `${resolved} as NonNullable<PiPluginContributions['events']>['${key}']` : resolved;\n lines.push(\n entry.contribution.entry.cardinality === 'optional'\n ? `${indent} ...keyed('${key}', ${value}),`\n : `${indent} ${key}: ${value},`,\n );\n }\n lines.push(`${indent}},`);\n continue;\n }\n if (target === 'cli' && members.length === 1 && members[0]?.contribution.entry.cardinality === 'collection') {\n const entry = members[0];\n const rendered = member(entry, contextOf(entry), target);\n lines.push(`${indent}${defer(field, wrapField(field, target, rendered, options), target)}`);\n continue;\n }\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, wrapField(field, target, rendered, options), 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: 'cli' | '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.flatMap((b) => [\n `import ${b.identifier} from '${specifierFor(b.contribution.entry.file, entryDir)}';`,\n ...(b.renderers === undefined\n ? []\n : [`import ${b.renderers.identifier} from '${specifierFor(b.renderers.file, entryDir)}';`]),\n ]),\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/** Infers the public Pi options contract from authored context factories. */\nfunction cliOptionsType(identifiers: readonly string[]): string[] {\n if (identifiers.length === 0) return [];\n const members = identifiers.map((identifier) => `OptionsOf<typeof ${identifier}>`).join(' | ');\n return [\n 'type OptionsOf<T> = T extends (context: PiPluginContext<infer Options>) => unknown ? Options : never;',\n `type InferredOptions = Exclude<${members}, undefined>;`,\n 'type Intersect<Union> =',\n ' (Union extends unknown ? (value: Union) => void : never) extends (value: infer Value) => void ? Value : never;',\n 'type ExtensionOptions = [InferredOptions] extends [never] ? undefined : Intersect<InferredOptions>;',\n '',\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('keyed('))) lines.push(keyedResolver());\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/** The interactive terminal entry. One mount, so every backend contribution lands in it. */\nexport function renderCliEntry(resolution: TargetResolution, options: RenderOptions): string {\n const bindings = bind(resolution, options);\n const hatches = hatchBindings(resolution.escapeHatches);\n // One mount, so every root in the tree applies, whatever its scope.\n const roots = rootBindings(resolution.roots);\n const innermost = roots[roots.length - 1]?.context ?? 'context';\n const body = [\n ...withRootRegistrations(\n bodyFor(bindings, ' ', (b) => contextForScope(roots, b.contribution.entry.scope, 'context'), 'cli', options),\n roots,\n 'cli',\n ' ',\n 'session',\n ),\n ...hatches.map((hatch) => ` ...await at(${hatch.identifier}, ${innermost}),`),\n ];\n const prologue = rootPrologue(roots, 'context', body);\n const factory = scopeBody(prologue, rootHooks(roots), body, '');\n const optionIdentifiers = [\n ...roots.map((root) => root.identifier),\n ...bindings.map((binding) => binding.identifier),\n ...hatches.map((hatch) => hatch.identifier),\n ];\n const infersOptions = optionIdentifiers.length > 0;\n\n return compact([\n HEADER,\n cliImport([...prologue, ...body], infersOptions),\n ...(roots.length > 0 ? [\"import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, roots, options.entryDir),\n '',\n ...cliOptionsType(optionIdentifiers),\n ...resolverFor(body),\n `export const extension = definePiExtension${infersOptions ? '<ExtensionOptions>' : ''}('${options.packageName}', ${factory[0]}`,\n ...factory.slice(1, -1),\n `${factory[factory.length - 1]?.replace(/,$/u, '')});`,\n '',\n 'export default extension;',\n '',\n ]);\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(\n visible,\n ' ',\n (b) => contextForScope(roots, b.contribution.entry.scope, 'context'),\n 'server',\n options,\n ),\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 ...(usesRoots ? [\"import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';\"] : []),\n '',\n ...importsFor(bindings, hatches, allRoots, options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const facet = defineServerPlugin({',\n ` name: '${options.packageName}',`,\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', options);\n return compact([\n HEADER,\n \"import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-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, [\"doompi/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/**\n * The cockpit 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 */\nexport function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string {\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', 'web', options),\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 return compact([\n HEADER,\n scopes.some((line) => line.includes('get '))\n ? \"import { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/doompi-core/web';\"\n : \"import { defineWebPlugin } from '@agimon-ai/doompi-core/web';\",\n '',\n ...importsFor(bindings, hatches, [], options.entryDir),\n '',\n ...resolverFor(scopes),\n 'export const webPlugin = defineWebPlugin({',\n ` id: '${options.pluginId}',`,\n ...scopes,\n '});',\n '',\n ]);\n}\n"],"mappings":"oEAOA,MAAM,EAAS,gEAGT,EAAmC,CAAC,QAAQ,EAE5C,EAAsC,CAAC,YAAa,0BAA2B,OAAO,EAUtF,EAAmE,CACvE,IAAK,CAAC,UAAU,EAChB,OAAQ,CAAC,UAAU,EACnB,IAAK,CAAC,EACN,IAAK,CAAC,CACR,EAYM,EAA2C,CAAC,UAAU,EAEtD,EAAyC,CAAC,SAAU,YAAa,SAAS,EAS1E,EAA4D,CAChE,IAAK,wBACL,OAAQ,0BACR,IAAK,yBACL,IAAK,sBACP,EAOA,SAAS,GAAmB,CAC1B,MAAO,CACL,0CACA,gEACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CAGA,SAAS,GAA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,6CACA,UAAU,EAAQ,SAAS,IAC3B,GAAG,EACH,MACA,EACF,CAAC,CACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/renderEntry/index.ts"],"mappings":";;;;wBAgkBgB,eAAe,YAAY,kBAAkB,SAAS;;;;;;;;;wBAmDtD,kBAAkB,YAAY,kBAAkB,SAAS;;;;;;;;wBAoFzD,eAAe,YAAY,kBAAkB,SAAS"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/renderEntry/index.ts"],"mappings":";;;;wBA2kBgB,eAAe,YAAY,kBAAkB,SAAS;;;;;;;;;wBAmDtD,kBAAkB,YAAY,kBAAkB,SAAS;;;;;;;;wBA4FzD,eAAe,YAAY,kBAAkB,SAAS"}
@@ -3,6 +3,6 @@ import{renderIdentity as e,toKebab as t,toSnake as n}from"../identity/index.mjs"
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
  `)}function m(){return[`/* v8 ignore next -- generated normalization branch */`,`const keyed = <T>(key: string, value: T | undefined): Record<string, T> =>`,` value === undefined ? {} : { [key]: value };`].join(`
5
5
  `)}const h=[`const via = <T>(identity: Record<string, unknown>, value: unknown): T =>`,` (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;`].join(`
6
- `);function g(e,n){return n===void 0?{id:t(e)}:{slot:n,id:t(e)}}const _={tool:e=>({name:n(e)}),command:e=>({name:t(e)}),channel:e=>({frameType:n(e)}),hook:e=>({event:n(e)}),mode:e=>({name:t(e)})},v={tool:e=>({tools:[n(e)]}),channel:e=>({channel:n(e)}),slot:(e,n)=>({slot:`${n.pluginId}.${t(e)}`}),command:e=>({id:t(e)}),tab:e=>({id:t(e)}),template:e=>({id:t(e)}),dock:e=>({id:t(e)}),setting:e=>({id:t(e)}),action:e=>({id:t(e)}),mode:e=>({name:t(e)}),"activity-group":e=>({name:t(e)}),"selection-axis":e=>({name:t(e)}),leader:(e,n)=>({id:`${n.pluginId}.${t(e)}`})};function y(e,t,n){let{entry:r}=e,i=r.surface;if(i!==void 0)return t===`web`?i===`fill`?g(r.name,r.target):v[i]?.(r.name,n):_[i]?.(r.name)}function b(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 x(e,t){return b([e.entry.surface??`extra`,e.entry.name],t)}function S(e,t){let n=e.replace(/\.[^.]+$/u,``),i=r.relative(t,n);return i.startsWith(`.`)?i:`./${i}`}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=x(r,n),a=r.renderers;return{identifier:i,contribution:r,identity:y(r,e.target,t),renderers:a===void 0?void 0:{identifier:b([`render`,a.name],n),file:a.file}}})}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(t,n,r){if(c.includes(t.contribution.field))return`${t.identifier}(${n})`;let i=r===`web`?t.identifier:`at(${t.identifier}, ${n})`;if(r===`cli`&&t.contribution.entry.surface===`command`&&t.contribution.entry.platform===`cli`)return i;let a=t.renderers===void 0?i:`withPiRenderers(${i}, at(${t.renderers.identifier}, ${n}))`,o=s[r].includes(t.contribution.field);if(t.contribution.entry.cardinality===`collection`)return a;if(t.identity===void 0)return o?t.identifier:a;let l=e(t.identity);return o?`() => via({ ${l} }, ${t.identifier}())`:`via({ ${l} }, ${a})`}function A(e,t,n,r){return e!==`tools`||t!==`cli`?`${e}: ${n},`:`...piToolContributions('${r.packageName}', ${n}),`}function j(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/doompi-core/serverFacet';`}function M(e,t){let n=[`definePiExtension`];e.some(e=>e.includes(`piToolContributions(`))&&n.push(`piToolContributions`),e.some(e=>e.includes(`withPiRenderers(`))&&n.push(`withPiRenderers`);let r=[...e.some(e=>e.includes(`at(`))||t?[`type PiPluginContext`]:[],...e.some(e=>e.includes(u.cli))?[`type ${u.cli}`]:[]];return`import { ${[...n,...r].join(`, `)} } from '@agimon-ai/doompi-core/piExtension';`}function N(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 P(e,t,r,i,s){let c=/* @__PURE__ */ new Map;for(let t of e){let e=c.get(t.contribution.field);e===void 0?c.set(t.contribution.field,[t]):e.push(t)}let l=[];for(let e of[...c.keys()].sort()){let u=c.get(e);if(a.includes(e)){l.push(`${t}${e}: {`);for(let e of u){let a=n(e.contribution.entry.name),o=`at(${e.identifier}, ${r(e)})`,s=i===`cli`?`${o} as NonNullable<PiPluginContributions['events']>['${a}']`:o;l.push(e.contribution.entry.cardinality===`optional`?`${t} ...keyed('${a}', ${s}),`:`${t} ${a}: ${s},`)}l.push(`${t}},`);continue}if(i===`cli`&&u.length===1&&u[0]?.contribution.entry.cardinality===`collection`){let n=u[0],a=k(n,r(n),i);l.push(`${t}${N(e,A(e,i,a,s),i)}`);continue}if(o.includes(e)){let n=u[0];if(n){let a=k(n,r(n),i);l.push(`${t}${N(e,`${e}: ${a},`,i)}`)}continue}let d=`[${u.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${r(e)})`:k(e,r(e),i)).join(`, `)}]`,f=u.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${d})`:d;l.push(`${t}${N(e,A(e,i,f,s),i)}`)}return l}function F(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 I(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${S(e.entry.file,r)}';`),...e.flatMap(e=>[`import ${e.identifier} from '${S(e.contribution.entry.file,r)}';`,...e.renderers===void 0?[]:[`import ${e.renderers.identifier} from '${S(e.renderers.file,r)}';`]]),...t.map(e=>`import ${e.identifier} from '${S(e.entry.file,r)}';`)]}function L(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
7
- `)}function R(e){return e.length===0?[]:[`type OptionsOf<T> = T extends (context: PiPluginContext<infer Options>) => unknown ? Options : never;`,`type InferredOptions = Exclude<${e.map(e=>`OptionsOf<typeof ${e}>`).join(` | `)}, undefined>;`,`type Intersect<Union> =`,` (Union extends unknown ? (value: Union) => void : never) extends (value: infer Value) => void ? Value : never;`,`type ExtensionOptions = [InferredOptions] extends [never] ? undefined : Intersect<InferredOptions>;`,``]}function z(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(`keyed(`))&&t.push(m()),e.some(e=>e.includes(`via(`))&&t.push(h),t.length>0?[...t,``]:[]}function B(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function V(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}${B(n)} => ({`,...i,`${r}}),`]:[`${a}${B([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function H(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function U(e,t){let n=C(e,t),r=O(e.escapeHatches),a=T(e.roots),o=a[a.length-1]?.context??`context`,s=[...F(P(n,` `,e=>D(a,e.contribution.entry.scope,`context`),`cli`,t),a,`cli`,` `,`session`),...r.map(e=>` ...await at(${e.identifier}, ${o}),`)],c=E(a,`context`,s),l=V(c,H(a),s,``),u=[...a.map(e=>e.identifier),...n.map(e=>e.identifier),...r.map(e=>e.identifier)],d=u.length>0;return L([i,M([...c,...s],d),...a.length>0?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...I(n,r,a,t.entryDir),``,...R(u),...z(s),`export const extension = definePiExtension${d?`<ExtensionOptions>`:``}('${t.packageName}', ${l[0]}`,...l.slice(1,-1),`${l[l.length-1]?.replace(/,$/u,``)});`,``,`export default extension;`,``])}function W(e,t){let n=C(e,t),r=O(e.escapeHatches),a=T(e.roots),o=[],s=!1;for(let[e,i]of l.entries()){let c=n.filter(t=>l.indexOf(t.contribution.entry.scope)<=e),u=r.filter(t=>l.indexOf(t.entry.scope)<=e),d=a.filter(t=>l.indexOf(t.entry.scope)<=e),f=d[d.length-1]?.context??`context`,p=[...F(P(c,` `,e=>D(d,e.contribution.entry.scope,`context`),`server`,t),d,`server`,` `,i),...u.map(e=>` ...await at(${e.identifier}, ${f}),`)];if(p.length===0&&d.length===0)continue;d.length>0&&(s=!0);let m=V(E(d,`context`,p),H(d),p,` `);o.push(` ${i}: ${m[0]}`,...m.slice(1))}return L([i,j(o),...s?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...I(n,r,a,t.entryDir),``,...z(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...o,`});`,``,`export default facet;`,``])}function G(e,t){let n=C(e,t),r=P(n,` `,()=>`context`,`mcp`,t);return L([i,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';`,``,...I(n,[],[],t.entryDir),``,...z(r),`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...r,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}function K(e,t){let n=C(e,t),r=O(e.escapeHatches),a=[];for(let e of l){let i=n.filter(t=>t.contribution.entry.scope===e),o=r.filter(t=>t.entry.scope===e),s=[...P(i,` `,()=>`undefined`,`web`,t),...o.map(e=>` ...${e.identifier},`)];s.length!==0&&a.push(` ${e}: {`,...s,` },`)}return L([i,a.some(e=>e.includes(`get `))?`import { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/doompi-core/web';`:`import { defineWebPlugin } from '@agimon-ai/doompi-core/web';`,``,...I(n,r,[],t.entryDir),``,...z(a),`export const webPlugin = defineWebPlugin({`,` id: '${t.pluginId}',`,...a,`});`,``])}export{U as renderCliEntry,G as renderMcpEntry,W as renderServerEntry,K as renderWebEntry};
6
+ `);function g(e,n){return n===void 0?{id:t(e)}:{slot:n,id:t(e)}}const _={tool:e=>({name:n(e)}),command:e=>({name:t(e)}),channel:e=>({frameType:n(e)}),hook:e=>({event:n(e)}),mode:e=>({name:t(e)})},v={tool:e=>({tools:[n(e)]}),channel:e=>({channel:n(e)}),slot:(e,n)=>({slot:`${n.pluginId}.${t(e)}`}),command:e=>({id:t(e)}),tab:e=>({id:t(e)}),template:e=>({id:t(e)}),dock:e=>({id:t(e)}),setting:e=>({id:t(e)}),action:e=>({id:t(e)}),mode:e=>({name:t(e)}),"activity-group":e=>({name:t(e)}),"selection-axis":e=>({name:t(e)}),leader:(e,n)=>({id:`${n.pluginId}.${t(e)}`})};function y(e,t,n){let{entry:r}=e,i=r.surface;if(i!==void 0)return t===`web`?i===`fill`?g(r.name,r.target):v[i]?.(r.name,n):_[i]?.(r.name)}function b(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 x(e,t){return b([e.entry.surface??`extra`,e.entry.name],t)}function S(e,t){let n=e.replace(/\.[^.]+$/u,``),i=r.relative(t,n);return i.startsWith(`.`)?i:`./${i}`}function C(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}function w(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=x(r,n),a=r.renderers,o=e.target===`mcp`?t.mcpWidgets?.[r.entry.file]:void 0;if(o!==void 0&&!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*\/[a-z0-9_]+$/u.test(o))throw Error(`Invalid MCP widget key '${o}'`);return{identifier:i,contribution:r,identity:y(r,e.target,t),mcpWidget:o,renderers:a===void 0?void 0:{identifier:b([`render`,a.name],n),file:a.file}}})}const T={global:0,workspace:1,session:2};function E(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 D(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 O(e,t,n){let r=n;for(let n of e)T[n.entry.scope]<=T[t]&&(r=n.context);return r}function k(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function A(t,n,r){if(c.includes(t.contribution.field))return`${t.identifier}(${n})`;let i=r===`web`?t.identifier:`at(${t.identifier}, ${n})`;if(r===`cli`&&t.contribution.entry.surface===`command`&&t.contribution.entry.platform===`cli`)return i;let a=t.renderers===void 0?i:`withPiRenderers(${i}, at(${t.renderers.identifier}, ${n}))`,o=s[r].includes(t.contribution.field);if(t.contribution.entry.cardinality===`collection`)return a;if(t.identity===void 0)return o?t.identifier:a;let l=e(t.identity);if(o)return`() => via({ ${l} }, ${t.identifier}())`;let u=`via({ ${l} }, ${a})`;return t.mcpWidget===void 0?u:`withWidget(${C(t.mcpWidget)}, ${u})`}function j(e,t,n,r){return e!==`tools`||t!==`cli`?`${e}: ${n},`:`...piToolContributions('${r.packageName}', ${n}),`}function M(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/doompi-core/serverFacet';`}function N(e,t){let n=[`definePiExtension`];e.some(e=>e.includes(`piToolContributions(`))&&n.push(`piToolContributions`),e.some(e=>e.includes(`withPiRenderers(`))&&n.push(`withPiRenderers`);let r=[...e.some(e=>e.includes(`at(`))||t?[`type PiPluginContext`]:[],...e.some(e=>e.includes(u.cli))?[`type ${u.cli}`]:[]];return`import { ${[...n,...r].join(`, `)} } from '@agimon-ai/doompi-core/piExtension';`}function P(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 F(e,t,r,i,s){let c=/* @__PURE__ */ new Map;for(let t of e){let e=c.get(t.contribution.field);e===void 0?c.set(t.contribution.field,[t]):e.push(t)}let l=[];for(let e of[...c.keys()].sort()){let u=c.get(e);if(a.includes(e)){l.push(`${t}${e}: {`);for(let e of u){let a=n(e.contribution.entry.name),o=`at(${e.identifier}, ${r(e)})`,s=i===`cli`?`${o} as NonNullable<PiPluginContributions['events']>['${a}']`:o;l.push(e.contribution.entry.cardinality===`optional`?`${t} ...keyed('${a}', ${s}),`:`${t} ${a}: ${s},`)}l.push(`${t}},`);continue}if(i===`cli`&&u.length===1&&u[0]?.contribution.entry.cardinality===`collection`){let n=u[0],a=A(n,r(n),i);l.push(`${t}${P(e,j(e,i,a,s),i)}`);continue}if(o.includes(e)){let n=u[0];if(n){let a=A(n,r(n),i);l.push(`${t}${P(e,`${e}: ${a},`,i)}`)}continue}let d=`[${u.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${r(e)})${e.mcpWidget===void 0?``:`.map((tool) => withWidget(${C(e.mcpWidget)}, tool))`}`:A(e,r(e),i)).join(`, `)}]`,f=u.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${d})`:d;l.push(`${t}${P(e,j(e,i,f,s),i)}`)}return l}function I(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 L(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${S(e.entry.file,r)}';`),...e.flatMap(e=>[`import ${e.identifier} from '${S(e.contribution.entry.file,r)}';`,...e.renderers===void 0?[]:[`import ${e.renderers.identifier} from '${S(e.renderers.file,r)}';`]]),...t.map(e=>`import ${e.identifier} from '${S(e.entry.file,r)}';`)]}function R(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
7
+ `)}function z(e){return e.length===0?[]:[`type OptionsOf<T> = T extends (context: PiPluginContext<infer Options>) => unknown ? Options : never;`,`type InferredOptions = Exclude<${e.map(e=>`OptionsOf<typeof ${e}>`).join(` | `)}, undefined>;`,`type Intersect<Union> =`,` (Union extends unknown ? (value: Union) => void : never) extends (value: infer Value) => void ? Value : never;`,`type ExtensionOptions = [InferredOptions] extends [never] ? undefined : Intersect<InferredOptions>;`,``]}function B(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(`keyed(`))&&t.push(m()),e.some(e=>e.includes(`via(`))&&t.push(h),t.length>0?[...t,``]:[]}function V(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function H(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}${V(n)} => ({`,...i,`${r}}),`]:[`${a}${V([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function U(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function W(e,t){let n=w(e,t),r=k(e.escapeHatches),a=E(e.roots),o=a[a.length-1]?.context??`context`,s=[...I(F(n,` `,e=>O(a,e.contribution.entry.scope,`context`),`cli`,t),a,`cli`,` `,`session`),...r.map(e=>` ...await at(${e.identifier}, ${o}),`)],c=D(a,`context`,s),l=H(c,U(a),s,``),u=[...a.map(e=>e.identifier),...n.map(e=>e.identifier),...r.map(e=>e.identifier)],d=u.length>0;return R([i,N([...c,...s],d),...a.length>0?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...L(n,r,a,t.entryDir),``,...z(u),...B(s),`export const extension = definePiExtension${d?`<ExtensionOptions>`:``}('${t.packageName}', ${l[0]}`,...l.slice(1,-1),`${l[l.length-1]?.replace(/,$/u,``)});`,``,`export default extension;`,``])}function G(e,t){let n=w(e,t),r=k(e.escapeHatches),a=E(e.roots),o=[],s=!1;for(let[e,i]of l.entries()){let c=n.filter(t=>l.indexOf(t.contribution.entry.scope)<=e),u=r.filter(t=>l.indexOf(t.entry.scope)<=e),d=a.filter(t=>l.indexOf(t.entry.scope)<=e),f=d[d.length-1]?.context??`context`,p=[...I(F(c,` `,e=>O(d,e.contribution.entry.scope,`context`),`server`,t),d,`server`,` `,i),...u.map(e=>` ...await at(${e.identifier}, ${f}),`)];if(p.length===0&&d.length===0)continue;d.length>0&&(s=!0);let m=H(D(d,`context`,p),U(d),p,` `);o.push(` ${i}: ${m[0]}`,...m.slice(1))}return R([i,M(o),...s?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...L(n,r,a,t.entryDir),``,...B(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...o,`});`,``,`export default facet;`,``])}function K(e,t){let n=w(e,t),r=F(n,` `,()=>`context`,`mcp`,t);return R([i,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';`,``,...L(n,[],[],t.entryDir),``,...B(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, ["doompi/widget"]: key },`,`});`,``]:[],`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...r,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}function q(e,t){let n=w(e,t),r=k(e.escapeHatches),a=[];for(let e of l){let i=n.filter(t=>t.contribution.entry.scope===e),o=r.filter(t=>t.entry.scope===e),s=[...F(i,` `,()=>`undefined`,`web`,t),...o.map(e=>` ...${e.identifier},`)];s.length!==0&&a.push(` ${e}: {`,...s,` },`)}return R([i,a.some(e=>e.includes(`get `))?`import { defineWebPlugin, type WebPluginContributions } from '@agimon-ai/doompi-core/web';`:`import { defineWebPlugin } from '@agimon-ai/doompi-core/web';`,``,...L(n,r,[],t.entryDir),``,...B(a),`export const webPlugin = defineWebPlugin({`,` id: '${t.pluginId}',`,...a,`});`,``])}export{W as renderCliEntry,K as renderMcpEntry,G as renderServerEntry,q as renderWebEntry};
8
8
  //# sourceMappingURL=index.mjs.map