@agimon-ai/doompi-build 0.0.1-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +82 -0
- package/dist/_virtual/_rolldown/runtime.cjs +1 -0
- package/dist/browserFile.cjs +1 -0
- package/dist/browserFile.d.mts +2 -0
- package/dist/browserFile.mjs +1 -0
- package/dist/constants/contributions.cjs +2 -0
- package/dist/constants/contributions.cjs.map +1 -0
- package/dist/constants/contributions.mjs +2 -0
- package/dist/constants/contributions.mjs.map +1 -0
- package/dist/constants/layout.cjs +2 -0
- package/dist/constants/layout.cjs.map +1 -0
- package/dist/constants/layout.d.mts +59 -0
- package/dist/constants/layout.d.mts.map +1 -0
- package/dist/constants/layout.mjs +2 -0
- package/dist/constants/layout.mjs.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.mts +16 -0
- package/dist/index.mjs +1 -0
- package/dist/services/browserFile/index.cjs +2 -0
- package/dist/services/browserFile/index.cjs.map +1 -0
- package/dist/services/browserFile/index.d.mts +28 -0
- package/dist/services/browserFile/index.d.mts.map +1 -0
- package/dist/services/browserFile/index.mjs +2 -0
- package/dist/services/browserFile/index.mjs.map +1 -0
- package/dist/services/filename/index.cjs +2 -0
- package/dist/services/filename/index.cjs.map +1 -0
- package/dist/services/filename/index.d.mts +29 -0
- package/dist/services/filename/index.d.mts.map +1 -0
- package/dist/services/filename/index.mjs +2 -0
- package/dist/services/filename/index.mjs.map +1 -0
- package/dist/services/generate/index.cjs +2 -0
- package/dist/services/generate/index.cjs.map +1 -0
- package/dist/services/generate/index.d.mts +15 -0
- package/dist/services/generate/index.d.mts.map +1 -0
- package/dist/services/generate/index.mjs +2 -0
- package/dist/services/generate/index.mjs.map +1 -0
- package/dist/services/generate/type.d.mts +28 -0
- package/dist/services/generate/type.d.mts.map +1 -0
- package/dist/services/identity/index.cjs +2 -0
- package/dist/services/identity/index.cjs.map +1 -0
- package/dist/services/identity/index.mjs +2 -0
- package/dist/services/identity/index.mjs.map +1 -0
- package/dist/services/renderClient/index.cjs +3 -0
- package/dist/services/renderClient/index.cjs.map +1 -0
- package/dist/services/renderClient/index.mjs +3 -0
- package/dist/services/renderClient/index.mjs.map +1 -0
- package/dist/services/renderEntry/index.cjs +7 -0
- package/dist/services/renderEntry/index.cjs.map +1 -0
- package/dist/services/renderEntry/index.d.mts +24 -0
- package/dist/services/renderEntry/index.d.mts.map +1 -0
- package/dist/services/renderEntry/index.mjs +7 -0
- package/dist/services/renderEntry/index.mjs.map +1 -0
- package/dist/services/renderEntry/type.d.mts +14 -0
- package/dist/services/renderEntry/type.d.mts.map +1 -0
- package/dist/services/resolveTarget/index.cjs +2 -0
- package/dist/services/resolveTarget/index.cjs.map +1 -0
- package/dist/services/resolveTarget/index.d.mts +16 -0
- package/dist/services/resolveTarget/index.d.mts.map +1 -0
- package/dist/services/resolveTarget/index.mjs +2 -0
- package/dist/services/resolveTarget/index.mjs.map +1 -0
- package/dist/services/resolveTarget/type.d.mts +34 -0
- package/dist/services/resolveTarget/type.d.mts.map +1 -0
- package/dist/services/scan/index.cjs +2 -0
- package/dist/services/scan/index.cjs.map +1 -0
- package/dist/services/scan/index.d.mts +19 -0
- package/dist/services/scan/index.d.mts.map +1 -0
- package/dist/services/scan/index.mjs +2 -0
- package/dist/services/scan/index.mjs.map +1 -0
- package/dist/services/scan/type.d.mts +25 -0
- package/dist/services/scan/type.d.mts.map +1 -0
- package/dist/services/segments/index.cjs +2 -0
- package/dist/services/segments/index.cjs.map +1 -0
- package/dist/services/segments/index.d.mts +26 -0
- package/dist/services/segments/index.d.mts.map +1 -0
- package/dist/services/segments/index.mjs +2 -0
- package/dist/services/segments/index.mjs.map +1 -0
- package/dist/services/syncManifest/index.cjs +2 -0
- package/dist/services/syncManifest/index.cjs.map +1 -0
- package/dist/services/syncManifest/index.d.mts +21 -0
- package/dist/services/syncManifest/index.d.mts.map +1 -0
- package/dist/services/syncManifest/index.mjs +2 -0
- package/dist/services/syncManifest/index.mjs.map +1 -0
- package/dist/services/syncManifest/type.d.mts +15 -0
- package/dist/services/syncManifest/type.d.mts.map +1 -0
- package/dist/services/tsdownPreset/index.cjs +2 -0
- package/dist/services/tsdownPreset/index.cjs.map +1 -0
- package/dist/services/tsdownPreset/index.d.mts +82 -0
- package/dist/services/tsdownPreset/index.d.mts.map +1 -0
- package/dist/services/tsdownPreset/index.mjs +2 -0
- package/dist/services/tsdownPreset/index.mjs.map +1 -0
- package/dist/services/writeGenerated/index.cjs +2 -0
- package/dist/services/writeGenerated/index.cjs.map +1 -0
- package/dist/services/writeGenerated/index.d.mts +23 -0
- package/dist/services/writeGenerated/index.d.mts.map +1 -0
- package/dist/services/writeGenerated/index.mjs +2 -0
- package/dist/services/writeGenerated/index.mjs.map +1 -0
- package/dist/tsdown.cjs +1 -0
- package/dist/tsdown.d.mts +2 -0
- package/dist/tsdown.mjs +1 -0
- package/dist/types/extensionGraph.d.mts +75 -0
- package/dist/types/extensionGraph.d.mts.map +1 -0
- package/package.json +72 -0
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
require("../../constants/layout.cjs");const e=require("../identity/index.cjs");let t=require("node:path");const n=[`global`,`workspace`,`session`];function r(t,n){if(!n)return`api`;let r=e.toKebab(t).split(`-`).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``);return/^[A-Za-z_]/u.test(r)?r:`api${r}`}function i(e){let t=e.route[0];if(t!==void 0&&`literal`in t)return t.literal}function a(e){let t=/* @__PURE__ */ new Map;for(let n of e.entries){if(n.side!==`backend`||n.surface!==`api`||n.role!==`contribution`)continue;let e=i(n);if(e===void 0)continue;let r=t.get(e)??/* @__PURE__ */ new Set;r.add(n.scope),t.set(e,r)}let a=[...t.keys()].sort();return a.map(e=>{let i=t.get(e),o=n.findIndex(e=>i.has(e));return{basePath:e,scopes:n.slice(o),identifier:r(e,a.length>1)}})}function o(e){let n=t.posix.relative(e,`src/types/apiRoutes`);return n.startsWith(`.`)?n:`./${n}`}function s(e){let t=e.scopes.map(e=>`'${e}'`).join(`, `),n=e.identifier===`api`?``:` for the ${e.basePath} mount`;return[`/** Scopes the tree mounts '${e.basePath}' at${n}. */`,`export const ${e.identifier}Scopes = [${t}] as const;`,``,`export const ${e.identifier} = createApiClient(routes, {`,` scopes: ${e.identifier}Scopes,`,` basePath: '${e.basePath}',`,` transport: (input, init) => sealedTransport.fetch(input, init),`,` sessionAddress: sessionApiAddress,`,`});`,``]}function c(e,t){let n=a(e);if(n.length!==0)return`${[`// Generated by @agimon-ai/doompi-build. Do not edit by hand.`,`import { createApiClient, sessionApiAddress } from '@agimon-ai/doompi-core/web';`,`import { sealedTransport } from '@agimon-ai/doompi-web-security/browser';`,``,`import routes from '${o(t.entryDir??`generated`)}';`,``,...n.flatMap(e=>s(e))].join(`
|
|
2
|
+
`).replace(/\n+$/u,``)}\n`}exports.renderApiClient=c;
|
|
3
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["toKebab","posix"],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/doompi-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `DoomApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\nfunction renderMount(mount: ClientMount): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ' transport: (input, init) => sealedTransport.fetch(input, init),',\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/doompi-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/doompi-web-security/browser';\",\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n"],"mappings":"0GAsBA,MAGM,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAAS,EAAc,EAAkB,EAA2B,CAClE,GAAI,CAAC,EAAU,MAAO,MACtB,IAAM,EAAQA,EAAAA,QAAQ,CAAQ,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,OAAQ,GAAS,EAAK,OAAS,CAAC,CAAC,CACjC,KAAK,EAAM,IAAW,IAAU,EAAI,EAAO,EAAK,EAAE,EAAE,YAAY,EAAI,EAAK,M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O,aACpD,GACA,gBAAgB,EAAM,WAAW,8BACjC,aAAa,EAAM,WAAW,SAC9B,gBAAgB,EAAM,SAAS,IAC/B,oEACA,uCACA,MACA,EACF,CACF,CAQA,SAAgB,EAAgB,EAAuB,EAA4C,CACjG,IAAM,EAAS,EAAS,CAAK,EACzB,KAAO,SAAW,EAWtB,MAAO,GAAG,CARR,gEACA,mFACA,4EACA,GACA,uBAAuB,EAAgB,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAG,EAAO,QAAS,GAAU,EAAY,CAAK,CAAC,CAEnC,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import"../../constants/layout.mjs";import{toKebab as e}from"../identity/index.mjs";import{posix as t}from"node:path";const n=[`global`,`workspace`,`session`];function r(t,n){if(!n)return`api`;let r=e(t).split(`-`).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``);return/^[A-Za-z_]/u.test(r)?r:`api${r}`}function i(e){let t=e.route[0];if(t!==void 0&&`literal`in t)return t.literal}function a(e){let t=/* @__PURE__ */ new Map;for(let n of e.entries){if(n.side!==`backend`||n.surface!==`api`||n.role!==`contribution`)continue;let e=i(n);if(e===void 0)continue;let r=t.get(e)??/* @__PURE__ */ new Set;r.add(n.scope),t.set(e,r)}let a=[...t.keys()].sort();return a.map(e=>{let i=t.get(e),o=n.findIndex(e=>i.has(e));return{basePath:e,scopes:n.slice(o),identifier:r(e,a.length>1)}})}function o(e){let n=t.relative(e,`src/types/apiRoutes`);return n.startsWith(`.`)?n:`./${n}`}function s(e){let t=e.scopes.map(e=>`'${e}'`).join(`, `),n=e.identifier===`api`?``:` for the ${e.basePath} mount`;return[`/** Scopes the tree mounts '${e.basePath}' at${n}. */`,`export const ${e.identifier}Scopes = [${t}] as const;`,``,`export const ${e.identifier} = createApiClient(routes, {`,` scopes: ${e.identifier}Scopes,`,` basePath: '${e.basePath}',`,` transport: (input, init) => sealedTransport.fetch(input, init),`,` sessionAddress: sessionApiAddress,`,`});`,``]}function c(e,t){let n=a(e);if(n.length!==0)return`${[`// Generated by @agimon-ai/doompi-build. Do not edit by hand.`,`import { createApiClient, sessionApiAddress } from '@agimon-ai/doompi-core/web';`,`import { sealedTransport } from '@agimon-ai/doompi-web-security/browser';`,``,`import routes from '${o(t.entryDir??`generated`)}';`,``,...n.flatMap(e=>s(e))].join(`
|
|
2
|
+
`).replace(/\n+$/u,``)}\n`}export{c as renderApiClient};
|
|
3
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/renderClient/index.ts"],"sourcesContent":["import { posix } from 'node:path';\n\nimport { GENERATED_DIR } from '../../constants/layout';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionScope } from '../../types/extensionGraph';\nimport { toKebab } from '../identity';\nimport type { RenderOptions } from '../renderEntry/type';\n\n/**\n * Renders the typed client a cockpit plugin calls its own API through.\n *\n * The two facts this injects are the two a package kept restating and getting\n * wrong: which scopes its API mounts at, and under which base path. Both are\n * read off the folder tree, so `api/file-edits/route.server.ts` at the session\n * scope is the whole declaration. A package that writes them out again is a\n * package that can disagree with itself, and several did.\n *\n * The route list is not read here. It is authored as plain data in\n * `src/types/apiRoutes.ts`, because this build evaluates no TypeScript and must\n * not learn how: it has no dependencies at all, and every specifier below is\n * emitted as text.\n */\n\nconst HEADER = '// Generated by @agimon-ai/doompi-build. Do not edit by hand.';\n\n/** Server scopes cascade outward-in, the way the generated server entry mounts them. */\nconst SCOPE_ORDER: readonly ExtensionScope[] = ['global', 'workspace', 'session'];\n\n/** One mount the tree declares: a base path, and the scopes it is reachable at. */\ninterface ClientMount {\n readonly basePath: string;\n readonly scopes: readonly ExtensionScope[];\n /** A valid identifier for the exported factory, when a package has several mounts. */\n readonly identifier: string;\n}\n\nfunction identifierFor(basePath: string, multiple: boolean): string {\n if (!multiple) return 'api';\n const camel = toKebab(basePath)\n .split('-')\n .filter((word) => word.length > 0)\n .map((word, index) => (index === 0 ? word : word[0]?.toUpperCase() + word.slice(1)))\n .join('');\n return /^[A-Za-z_]/u.test(camel) ? camel : `api${camel}`;\n}\n\n/**\n * The base path an api entry mounts at: the first literal segment below `api/`.\n *\n * An entry with no segment is the flat `api/route.server.ts` shape that predates\n * this convention. Its base path lives in a hand-written `DoomApi` the build\n * cannot read, so it contributes no client and keeps its hand-built URLs until\n * the folder is renamed.\n */\nfunction baseSegmentOf(entry: ExtensionEntry): string | undefined {\n const first = entry.route[0];\n if (first === undefined || !('literal' in first)) return undefined;\n return first.literal;\n}\n\nfunction mountsOf(graph: ExtensionGraph): ClientMount[] {\n const scopesByBase = new Map<string, Set<ExtensionScope>>();\n for (const entry of graph.entries) {\n if (entry.side !== 'backend' || entry.surface !== 'api' || entry.role !== 'contribution') continue;\n const basePath = baseSegmentOf(entry);\n if (basePath === undefined) continue;\n const held = scopesByBase.get(basePath) ?? new Set<ExtensionScope>();\n held.add(entry.scope);\n scopesByBase.set(basePath, held);\n }\n\n const bases = [...scopesByBase.keys()].sort();\n return bases.map((basePath) => {\n const declared = scopesByBase.get(basePath) as Set<ExtensionScope>;\n // A facet mounts a contribution at its own scope and every scope below it,\n // so a global API answers workspace and session requests too.\n const shallowest = SCOPE_ORDER.findIndex((scope) => declared.has(scope));\n return {\n basePath,\n scopes: SCOPE_ORDER.slice(shallowest),\n identifier: identifierFor(basePath, bases.length > 1),\n };\n });\n}\n\n/** The extensionless relative specifier from the generated directory to the route table. */\nfunction routesSpecifier(entryDir: string): string {\n const relative = posix.relative(entryDir, 'src/types/apiRoutes');\n return relative.startsWith('.') ? relative : `./${relative}`;\n}\n\nfunction renderMount(mount: ClientMount): string[] {\n const scopes = mount.scopes.map((scope) => `'${scope}'`).join(', ');\n const suffix = mount.identifier === 'api' ? '' : ` for the ${mount.basePath} mount`;\n return [\n `/** Scopes the tree mounts '${mount.basePath}' at${suffix}. */`,\n `export const ${mount.identifier}Scopes = [${scopes}] as const;`,\n '',\n `export const ${mount.identifier} = createApiClient(routes, {`,\n ` scopes: ${mount.identifier}Scopes,`,\n ` basePath: '${mount.basePath}',`,\n ' transport: (input, init) => sealedTransport.fetch(input, init),',\n ' sessionAddress: sessionApiAddress,',\n '});',\n '',\n ];\n}\n\n/**\n * The client source, or undefined when the tree declares no `api/<base-path>/`.\n *\n * `options.entryDir` is where the file will be written, so the relative import\n * of the route table is computed against it rather than assumed.\n */\nexport function renderApiClient(graph: ExtensionGraph, options: RenderOptions): string | undefined {\n const mounts = mountsOf(graph);\n if (mounts.length === 0) return undefined;\n\n const lines = [\n HEADER,\n \"import { createApiClient, sessionApiAddress } from '@agimon-ai/doompi-core/web';\",\n \"import { sealedTransport } from '@agimon-ai/doompi-web-security/browser';\",\n '',\n `import routes from '${routesSpecifier(options.entryDir ?? GENERATED_DIR)}';`,\n '',\n ...mounts.flatMap((mount) => renderMount(mount)),\n ];\n return `${lines.join('\\n').replace(/\\n+$/u, '')}\\n`;\n}\n"],"mappings":"qHAsBA,MAGM,EAAyC,CAAC,SAAU,YAAa,SAAS,EAUhF,SAAS,EAAc,EAAkB,EAA2B,CAClE,GAAI,CAAC,EAAU,MAAO,MACtB,IAAM,EAAQ,EAAQ,CAAQ,CAAC,CAC5B,MAAM,GAAG,CAAC,CACV,OAAQ,GAAS,EAAK,OAAS,CAAC,CAAC,CACjC,KAAK,EAAM,IAAW,IAAU,EAAI,EAAO,EAAK,EAAE,EAAE,YAAY,EAAI,EAAK,MAAM,CAAC,CAAE,CAAC,CACnF,KAAK,EAAE,EACV,MAAO,cAAc,KAAK,CAAK,EAAI,EAAQ,MAAM,GACnD,CAUA,SAAS,EAAc,EAA2C,CAChE,IAAM,EAAQ,EAAM,MAAM,GACtB,OAAU,IAAA,IAAe,YAAa,EAC1C,OAAO,EAAM,OACf,CAEA,SAAS,EAAS,EAAsC,CACtD,IAAM,kB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AuB,EAAgB,EAAQ,UAAA,WAAyB,EAAE,IAC1E,GACA,GAAG,EAAO,QAAS,GAAU,EAAY,CAAK,CAAC,CAEnC,CAAC,CAAC,KAAK;CAAI,CAAC,CAAC,QAAQ,QAAS,EAAE,EAAE,GAClD"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
const e=require("../identity/index.cjs");let t=require("node:path");const n=`// Generated by @agimon-ai/doompi-build. Do not edit by hand.`,r=[`events`],i=[`fileLinks`,`repositorySettingsPanel`,`start`],a={cli:[`channels`],server:[`channels`],web:[],mcp:[]},o=[`services`],s=[`global`,`workspace`,`session`],c={cli:`PiPluginContributions`,server:`DoomServerSessionPlugin`,web:`WebPluginContributions`,mcp:`DoomMcpSessionPlugin`};function l(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
|
|
2
|
+
`)}function u(){return[`type ManyFactory<T, C> = (context: C) => T | readonly T[];`,`const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {`,` const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;`,` return Array.isArray(resolved) ? resolved : [resolved as T];`,`};`].join(`
|
|
3
|
+
`)}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
|
+
`)}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
|
+
`)}function p(t,n){return n===void 0?{id:e.toKebab(t)}:{slot:n,id:e.toKebab(t)}}const m={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)})},h={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 g(e,t,n){let{entry:r}=e,i=r.surface;if(i!==void 0)return t===`web`?i===`fill`?p(r.name,r.target):h[i]?.(r.name,n):m[i]?.(r.name)}function _(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function v(e,t){return _([e.entry.surface??`extra`,e.entry.name],t)}function y(e,n){let r=e.replace(/\.[^.]+$/u,``),i=t.posix.relative(n,r);return i.startsWith(`.`)?i:`./${i}`}function b(e,t){let n=/* @__PURE__ */ new Set;return[...e.contributions].sort((e,t)=>e.entry.file.localeCompare(t.entry.file)).map(r=>{let i=v(r,n),a=r.renderers;return{identifier:i,contribution:r,identity:g(r,e.target,t),renderers:a===void 0?void 0:{identifier:_([`render`,a.name],n),file:a.file}}})}const x={global:0,workspace:1,session:2};function S(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 C(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 w(e,t,n){let r=n;for(let n of e)x[n.entry.scope]<=x[t]&&(r=n.context);return r}function T(e){return[...e].sort((e,t)=>e.file.localeCompare(t.file)).map((e,t)=>({identifier:`extra${t===0?``:t+1}`,entry:e}))}function E(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 D(e,t,n,r){return e!==`tools`||t!==`cli`?`${e}: ${n},`:`...piToolContributions('${r.packageName}', ${n}),`}function O(e){return`import { ${[`defineServerPlugin`,...e.some(e=>e.includes(`get `))?[`type DoomServerSessionPlugin`]:[]].join(`, `)} } from '@agimon-ai/doompi-core/serverFacet';`}function k(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 A(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 j(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=E(e,a(e),o);l.push(`${n}${A(t,D(t,o,r,s),o)}`);continue}if(i.includes(t)){let e=u[0];if(e){let r=E(e,a(e),o);l.push(`${n}${A(t,`${t}: ${r},`,o)}`)}continue}let d=`[${u.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${a(e)})`:E(e,a(e),o)).join(`, `)}]`,f=u.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${d})`:d;l.push(`${n}${A(t,D(t,o,f,s),o)}`)}return l}function M(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 N(e,t,n,r){return[...n.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`),...e.flatMap(e=>[`import ${e.identifier} from '${y(e.contribution.entry.file,r)}';`,...e.renderers===void 0?[]:[`import ${e.renderers.identifier} from '${y(e.renderers.file,r)}';`]]),...t.map(e=>`import ${e.identifier} from '${y(e.entry.file,r)}';`)]}function P(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
|
|
6
|
+
`)}function F(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 I(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(`const via = <T>(identity: Record<string, unknown>, value: unknown): T => ({ ...identity, ...(value as object) }) as T;`),t.length>0?[...t,``]:[]}function L(e){return e.some(e=>e.includes(`, context)`)||e.includes(`(context)`))?`(context)`:`()`}function R(e,t,n,r){let i=[...t===void 0?[]:[`${r} ${t}`],...n],a=[...e,...n].some(e=>e.includes(`await `))?`async `:``;return e.length===0?[`${a}${L(n)} => ({`,...i,`${r}}),`]:[`${a}${L([...e,...n])} => {`,...e.map(e=>`${r} ${e}`),`${r} return {`,...i.map(e=>` ${e}`),`${r} };`,`${r}},`]}function z(e){if(e.length!==0)return`...composeRootHooks(${e.map(e=>e.declaration).join(`, `)}),`}function B(e,t){let r=b(e,t),i=T(e.escapeHatches),a=S(e.roots),o=a[a.length-1]?.context??`context`,s=[...M(j(r,` `,e=>w(a,e.contribution.entry.scope,`context`),`cli`,t),a,`cli`,` `,`session`),...i.map(e=>` ...await at(${e.identifier}, ${o}),`)],c=C(a,`context`,s),l=R(c,z(a),s,``),u=[...a.map(e=>e.identifier),...r.map(e=>e.identifier),...i.map(e=>e.identifier)],d=u.length>0;return P([n,k([...c,...s],d),...a.length>0?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...N(r,i,a,t.entryDir),``,...F(u),...I(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 V(e,t){let r=b(e,t),i=T(e.escapeHatches),a=S(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=[...M(j(l,` `,e=>w(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=R(C(d,`context`,p),z(d),p,` `);o.push(` ${n}: ${m[0]}`,...m.slice(1))}return P([n,O(o),...c?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...N(r,i,a,t.entryDir),``,...I(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...o,`});`,``,`export default facet;`,``])}function H(e,t){let r=b(e,t),i=j(r,` `,()=>`context`,`mcp`,t);return P([n,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';`,``,...N(r,[],[],t.entryDir),``,...I(i),`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...i,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}function U(e,t){let r=b(e,t),i=T(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=[...j(n,` `,()=>`undefined`,`web`,t),...o.map(e=>` ...${e.identifier},`)];s.length!==0&&a.push(` ${e}: {`,...s,` },`)}return P([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';`,``,...N(r,i,[],t.entryDir),``,...I(a),`export const webPlugin = defineWebPlugin({`,` id: '${t.pluginId}',`,...a,`});`,``])}exports.renderCliEntry=B,exports.renderMcpEntry=H,exports.renderServerEntry=V,exports.renderWebEntry=U;
|
|
7
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +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// One line on purpose: at 118 characters it fits the repository's 120 print\n// width, so oxfmt would join a wrapped form and leave every build dirty.\nconst IDENTITY_HELPER =\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T => ({ ...identity, ...(value as object) }) as T;';\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,OA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AO,EAAQ,EAAU,WAAc,UAAW,MAAO,CAAO,EACtE,OAAO,EAAQ,CACb,EACA,gGACA,GACA,GAAG,EAAW,EAAU,CAAC,EAAG,CAAC,EAAG,EAAQ,QAAQ,EAChD,GACA,GAAG,EAAY,CAAI,EACnB,uCACA,YAAY,EAAQ,YAAY,IAChC,6BACA,GAAG,EACH,uCACA,MACA,GACA,sBACA,EACF,CAAC,CACH,CASA,SAAgB,EAAe,EAA8B,EAAgC,CAC3F,IAAM,EAAW,EAAK,EAAY,CAAO,EACnC,EAAU,EAAc,EAAW,aAAa,EAEhD,EAAmB,CAAC,EAC1B,IAAK,IAAM,KAAS,EAAa,CAC/B,IAAM,EAAU,EAAS,OAAQ,GAAM,EAAE,aAAa,MAAM,QAAU,CAAK,EACrE,EAAO,EAAQ,OAAQ,GAAM,EAAE,MAAM,QAAU,CAAK,EACpD,EAAO,CACX,GAAG,EAAQ,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"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { TargetResolution } from "../resolveTarget/type.mjs";
|
|
2
|
+
import { RenderOptions } from "./type.mjs";
|
|
3
|
+
//#region src/services/renderEntry/index.d.ts
|
|
4
|
+
/** The interactive terminal entry. One mount, so every backend contribution lands in it. */
|
|
5
|
+
export declare function renderCliEntry(resolution: TargetResolution, options: RenderOptions): string;
|
|
6
|
+
/**
|
|
7
|
+
* The headless entry, one declaration per scope.
|
|
8
|
+
*
|
|
9
|
+
* Contributions cascade downward here because the server does not do it
|
|
10
|
+
* itself: a facet reads exactly one `plugin[host.scope]` and nothing from the
|
|
11
|
+
* scopes above it. Emitting the repetition is what lets an author declare a
|
|
12
|
+
* channel once and have it mount at all three scopes.
|
|
13
|
+
*/
|
|
14
|
+
export declare function renderServerEntry(resolution: TargetResolution, options: RenderOptions): string;
|
|
15
|
+
/**
|
|
16
|
+
* The cockpit entry, one contributions object per scope.
|
|
17
|
+
*
|
|
18
|
+
* No cascade here, unlike the server: the registry already folds global into
|
|
19
|
+
* workspace into session before install, so repeating a contribution would
|
|
20
|
+
* install it twice.
|
|
21
|
+
*/
|
|
22
|
+
export declare function renderWebEntry(resolution: TargetResolution, options: RenderOptions): string;
|
|
23
|
+
//#endregion
|
|
24
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/renderEntry/index.ts"],"mappings":";;;;wBA8jBgB,eAAe,YAAY,kBAAkB,SAAS;;;;;;;;;wBAmDtD,kBAAkB,YAAY,kBAAkB,SAAS;;;;;;;;wBAoFzD,eAAe,YAAY,kBAAkB,SAAS"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{renderIdentity as e,toKebab as t,toSnake as n}from"../identity/index.mjs";import{posix as r}from"node:path";const i=`// Generated by @agimon-ai/doompi-build. Do not edit by hand.`,a=[`events`],o=[`fileLinks`,`repositorySettingsPanel`,`start`],s={cli:[`channels`],server:[`channels`],web:[],mcp:[]},c=[`services`],l=[`global`,`workspace`,`session`],u={cli:`PiPluginContributions`,server:`DoomServerSessionPlugin`,web:`WebPluginContributions`,mcp:`DoomMcpSessionPlugin`};function d(){return[`type Factory<T, C> = (context: C) => T;`,`const at = <T, C>(value: T | Factory<T, C>, context: C): T =>`,` typeof value === 'function' ? (value as Factory<T, C>)(context) : value;`].join(`
|
|
2
|
+
`)}function f(){return[`type ManyFactory<T, C> = (context: C) => T | readonly T[];`,`const many = <T, C>(value: T | readonly T[] | ManyFactory<T, C>, context: C): readonly T[] => {`,` const resolved = typeof value === 'function' ? (value as ManyFactory<T, C>)(context) : value;`,` return Array.isArray(resolved) ? resolved : [resolved as T];`,`};`].join(`
|
|
3
|
+
`)}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
|
+
`)}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
|
+
`)}function h(e,n){return n===void 0?{id:t(e)}:{slot:n,id:t(e)}}const g={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)})},_={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 v(e,t,n){let{entry:r}=e,i=r.surface;if(i!==void 0)return t===`web`?i===`fill`?h(r.name,r.target):_[i]?.(r.name,n):g[i]?.(r.name)}function y(e,t){let n=e.join(`-`).split(/[^A-Za-z0-9]+/u).filter(e=>e.length>0).map((e,t)=>t===0?e:e[0]?.toUpperCase()+e.slice(1)).join(``),r=/^[A-Za-z_]/u.test(n)?n:`x${n}`,i=r,a=2;for(;t.has(i);)i=`${r}${a++}`;return t.add(i),i}function b(e,t){return y([e.entry.surface??`extra`,e.entry.name],t)}function x(e,t){let n=e.replace(/\.[^.]+$/u,``),i=r.relative(t,n);return i.startsWith(`.`)?i:`./${i}`}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=b(r,n),a=r.renderers;return{identifier:i,contribution:r,identity:v(r,e.target,t),renderers:a===void 0?void 0:{identifier:y([`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(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 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(u.cli))?[`type ${u.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}(): ${`${u[n]}['${r}']`} { return ${i.join(`: `).replace(/,$/u,``)}; },`}function N(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=O(n,r(n),i);l.push(`${t}${M(e,k(e,i,a,s),i)}`);continue}if(o.includes(e)){let n=u[0];if(n){let a=O(n,r(n),i);l.push(`${t}${M(e,`${e}: ${a},`,i)}`)}continue}let d=`[${u.map(e=>e.contribution.entry.cardinality===`many`?`...many(${e.identifier}, ${r(e)})`:O(e,r(e),i)).join(`, `)}]`,f=u.some(e=>e.contribution.entry.cardinality===`optional`)?`defined(${d})`:d;l.push(`${t}${M(e,k(e,i,f,s),i)}`)}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 '${x(e.entry.file,r)}';`),...e.flatMap(e=>[`import ${e.identifier} from '${x(e.contribution.entry.file,r)}';`,...e.renderers===void 0?[]:[`import ${e.renderers.identifier} from '${x(e.renderers.file,r)}';`]]),...t.map(e=>`import ${e.identifier} from '${x(e.entry.file,r)}';`)]}function I(e){return e.filter((e,t,n)=>e!==``||n[t-1]!==``).join(`
|
|
6
|
+
`)}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(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(`const via = <T>(identity: Record<string, unknown>, value: unknown): T => ({ ...identity, ...(value as object) }) as T;`),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 n=S(e,t),r=D(e.escapeHatches),a=w(e.roots),o=a[a.length-1]?.context??`context`,s=[...P(N(n,` `,e=>E(a,e.contribution.entry.scope,`context`),`cli`,t),a,`cli`,` `,`session`),...r.map(e=>` ...await at(${e.identifier}, ${o}),`)],c=T(a,`context`,s),l=B(c,V(a),s,``),u=[...a.map(e=>e.identifier),...n.map(e=>e.identifier),...r.map(e=>e.identifier)],d=u.length>0;return I([i,j([...c,...s],d),...a.length>0?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...F(n,r,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 n=S(e,t),r=D(e.escapeHatches),a=w(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=[...P(N(c,` `,e=>E(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=B(T(d,`context`,p),V(d),p,` `);o.push(` ${i}: ${m[0]}`,...m.slice(1))}return I([i,A(o),...s?[`import { composeRootHooks } from '@agimon-ai/doompi-core/extensionFile';`]:[],``,...F(n,r,a,t.entryDir),``,...R(o),`export const facet = defineServerPlugin({`,` name: '${t.packageName}',`,...o,`});`,``,`export default facet;`,``])}function W(e,t){let n=S(e,t),r=N(n,` `,()=>`context`,`mcp`,t);return I([i,`import { defineMcpPlugin, type DoomMcpSessionPlugin } from '@agimon-ai/doompi-core/mcpFacet';`,``,...F(n,[],[],t.entryDir),``,...R(r),`export const mcp = defineMcpPlugin({`,` name: '${t.packageName}',`,` session: (context) => ({`,...r,` }) satisfies DoomMcpSessionPlugin,`,`});`,``,`export default mcp;`,``])}function G(e,t){let n=S(e,t),r=D(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=[...N(i,` `,()=>`undefined`,`web`,t),...o.map(e=>` ...${e.identifier},`)];s.length!==0&&a.push(` ${e}: {`,...s,` },`)}return I([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';`,``,...F(n,r,[],t.entryDir),``,...R(a),`export const webPlugin = defineWebPlugin({`,` id: '${t.pluginId}',`,...a,`});`,``])}export{H as renderCliEntry,W as renderMcpEntry,U as renderServerEntry,G as renderWebEntry};
|
|
7
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"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// One line on purpose: at 118 characters it fits the repository's 120 print\n// width, so oxfmt would join a wrapped form and leave every build dirty.\nconst IDENTITY_HELPER =\n 'const via = <T>(identity: Record<string, unknown>, value: unknown): T => ({ ...identity, ...(value as object) }) as T;';\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":"mHAOA,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,CA4BA,SAAS,EAAa,EAAc,EAAsC,CAExE,OADI,IAAW,IAAA,GAAkB,CAAE,GAAI,EAAQ,CAAI,CAAE,EAC9C,CAAE,KAAM,EAAQ,GAAI,EAAQ,CAAI,CAAE,CAC3C,CAGA,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S,IAC3B,GAAG,EACH,MACA,EACF,CAAC,CACH"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/services/renderEntry/type.d.ts
|
|
2
|
+
/** What the renderers need beyond the resolved contributions themselves. */
|
|
3
|
+
export interface RenderOptions {
|
|
4
|
+
/** The package's npm name, used as the extension and facet name. */
|
|
5
|
+
readonly packageName: string;
|
|
6
|
+
/** The cockpit plugin id. */
|
|
7
|
+
readonly pluginId: string;
|
|
8
|
+
/** Routing root, package-relative. */
|
|
9
|
+
readonly root: string;
|
|
10
|
+
/** Where the generated entry is written, package-relative, so its imports can be made relative to it. */
|
|
11
|
+
readonly entryDir: string;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//# sourceMappingURL=type.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.mts","names":[],"sources":["../../../src/services/renderEntry/type.ts"],"mappings":";;iBACiB;;WAEN;;WAEA;;WAEA;;WAEA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../constants/contributions.cjs"),t=require("../identity/index.cjs"),n={global:0,workspace:1,session:2};function r(e,t){return t===`web`?e.side===`frontend`:t===`mcp`?e.side===`backend`:e.side===`backend`||t===`cli`&&e.platform===`cli`}const i={cli:{backend:e.CLI_FIELDS,frontend:e.CLI_FRONTEND_FIELDS},server:{backend:e.SERVER_FIELDS,frontend:{}},web:{backend:{},frontend:e.WEB_FIELDS},mcp:{backend:e.MCP_FIELDS,frontend:{}}};function a(e){let t=e.gates.map(e=>`${e.kind}:${e.id}`).join(`/`),n=e.route.map(e=>`literal`in e?e.literal:`[${e.param.name}]`).join(`/`);return[e.side,e.scope,t,e.surface??``,n,e.name,e.target??``].join(`|`)}function o(e,t,n){return n===void 0?t:e[n]??t}function s(t,n){let r=t.surface;if(r===void 0)return;let a=i[n][t.side][r];if(a!==void 0&&a!==``&&(n!==`web`||r!==`lifecycle`||t.name===`start`))return n===`web`&&r===`setting`?o(e.SETTING_FIELDS,a,t.target):n===`web`&&r===`action`?o(e.ACTION_FIELDS,a,t.target):a}function c(e,n){let r=/* @__PURE__ */ new Map,i=[];for(let n of e)n.field===`tool-renderers`?r.set(t.toSnake(n.entry.name),n.entry):i.push(n);if(r.size===0)return i;let a=i.map(e=>{if(e.field!==`tools`)return e;let n=t.toSnake(e.entry.name),i=r.get(n);return i===void 0?e:(r.delete(n),{...e,renderers:i})});for(let e of r.values())n.push({path:e.file,message:`renders a tool no backend file contributes; nothing will draw it`});return a}function l(e,t){let i=[],o=[],l=[],u=/* @__PURE__ */ new Map;for(let n of e.entries){if(!r(n,t)||(t===`mcp`?n.platform!==`mcp`:n.platform!==void 0&&n.platform!==t))continue;if(n.role===`escape-hatch`){o.push(n);continue}if(n.role===`root`){if(n.side===`frontend`){i.push({path:n.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}l.push(n);continue}let e=a(n),s=u.get(e);if(s===void 0){u.set(e,n);continue}if(s.platform===n.platform){i.push({path:n.file,message:`duplicates ${s.file} for ${t}; the first one wins`});continue}n.platform!==void 0&&u.set(e,n)}let d=[];for(let e of u.values()){let n=s(e,t);n!==void 0&&d.push({entry:e,field:n})}return{target:t,contributions:c(d,i),escapeHatches:o,roots:l.sort((e,t)=>n[e.scope]-n[t.scope]),notices:i}}exports.resolveTarget=l;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["CLI_FIELDS","CLI_FRONTEND_FIELDS","SERVER_FIELDS","WEB_FIELDS","MCP_FIELDS","SETTING_FIELDS","ACTION_FIELDS","toSnake"],"sources":["../../../src/services/resolveTarget/index.ts"],"sourcesContent":["import {\n ACTION_FIELDS,\n CLI_FIELDS,\n CLI_FRONTEND_FIELDS,\n MCP_FIELDS,\n MERGED_INTO_TOOL,\n NOT_A_CONTRIBUTION,\n SERVER_FIELDS,\n SETTING_FIELDS,\n WEB_FIELDS,\n} from '../../constants/contributions';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionNotice, ExtensionSide } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\nimport type { BuildTarget, ResolvedContribution, TargetResolution } from './type';\n\n/** Nesting order, so roots compose outermost first. */\nconst SCOPE_DEPTH: Readonly<Record<string, number>> = { global: 0, workspace: 1, session: 2 };\n\n/**\n * Which sides a host reads, and which of their files.\n *\n * The side axis is logic against presentation, not Node against browser, so\n * the terminal reads both: every backend file, plus the frontend files that\n * name it. A frontend file that does not name the terminal is cockpit code,\n * which a terminal cannot render, so the CLI takes only explicit `.cli` ones.\n * The headless server has no presentation at all.\n */\nfunction drawsFrom(entry: ExtensionEntry, target: BuildTarget): boolean {\n if (target === 'web') return entry.side === 'frontend';\n if (target === 'mcp') return entry.side === 'backend';\n if (entry.side === 'backend') return true;\n return target === 'cli' && entry.platform === 'cli';\n}\n\nconst FIELDS_OF: Readonly<Record<BuildTarget, Readonly<Record<ExtensionSide, Readonly<Record<string, string>>>>>> = {\n cli: { backend: CLI_FIELDS, frontend: CLI_FRONTEND_FIELDS },\n server: { backend: SERVER_FIELDS, frontend: {} },\n web: { backend: {}, frontend: WEB_FIELDS },\n mcp: { backend: MCP_FIELDS, frontend: {} },\n};\n\n/** Everything but the platform: two files sharing this are the same contribution. */\nfunction logicalKey(entry: ExtensionEntry): string {\n const gates = entry.gates.map((gate) => `${gate.kind}:${gate.id}`).join('/');\n const route = entry.route\n .map((segment) => ('literal' in segment ? segment.literal : `[${segment.param.name}]`))\n .join('/');\n // The side is part of it, because the terminal reads both. Without it a\n // tool's logic and its TUI would look like one contribution overriding the\n // other, and only one of the pair would survive.\n return [entry.side, entry.scope, gates, entry.surface ?? '', route, entry.name, entry.target ?? ''].join('|');\n}\n\n/** Resolves the field for a surface whose filename target picks between two shapes. */\nfunction variantField(\n table: Readonly<Record<string, string>>,\n fallback: string,\n entryTarget: string | undefined,\n): string {\n if (entryTarget === undefined) return fallback;\n return table[entryTarget] ?? fallback;\n}\n\nfunction fieldFor(entry: ExtensionEntry, target: BuildTarget): string | undefined {\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n const declared = FIELDS_OF[target][entry.side][surface];\n if (declared === undefined || declared === NOT_A_CONTRIBUTION) return undefined;\n\n if (target === 'web' && surface === 'lifecycle' && entry.name !== 'start') return undefined;\n if (target === 'web' && surface === 'setting') return variantField(SETTING_FIELDS, declared, entry.target);\n if (target === 'web' && surface === 'action') return variantField(ACTION_FIELDS, declared, entry.target);\n return declared;\n}\n\n/**\n * Folds terminal tool renderers into the tool declarations they draw.\n *\n * Paired by the snake-cased filename, which is the tool's name on both sides.\n * A renderer naming no tool this package contributes is reported rather than\n * dropped: it is almost always a rename that only half landed, and a silently\n * missing renderer is the kind of thing nobody notices until a demo.\n */\nfunction mergeRenderers(\n contributions: readonly ResolvedContribution[],\n notices: ExtensionNotice[],\n): ResolvedContribution[] {\n const renderers = new Map<string, ExtensionEntry>();\n const rest: ResolvedContribution[] = [];\n for (const contribution of contributions) {\n if (contribution.field !== MERGED_INTO_TOOL) rest.push(contribution);\n else renderers.set(toSnake(contribution.entry.name), contribution.entry);\n }\n if (renderers.size === 0) return rest;\n\n const merged = rest.map((contribution) => {\n if (contribution.field !== 'tools') return contribution;\n const name = toSnake(contribution.entry.name);\n const found = renderers.get(name);\n if (found === undefined) return contribution;\n renderers.delete(name);\n return { ...contribution, renderers: found };\n });\n\n for (const orphan of renderers.values()) {\n notices.push({ path: orphan.file, message: `renders a tool no backend file contributes; nothing will draw it` });\n }\n return merged;\n}\n\n/**\n * Picks the winning file per logical contribution for one host.\n *\n * Metro and Expo semantics: a file naming this platform replaces a sibling\n * that names none, and a file naming none serves every platform on its side\n * that has no more specific sibling. The scan reports the unnamed one, so this\n * is a fallback rather than a supported way to author. Two files naming the\n * same platform for the same contribution is an authoring mistake, so the\n * first wins and the second becomes a notice rather than silently disappearing.\n */\nexport function resolveTarget(graph: ExtensionGraph, target: BuildTarget): TargetResolution {\n const notices: ExtensionNotice[] = [];\n const escapeHatches: ExtensionEntry[] = [];\n const roots: ExtensionEntry[] = [];\n const winners = new Map<string, ExtensionEntry>();\n\n for (const entry of graph.entries) {\n if (!drawsFrom(entry, target)) continue;\n if (target === 'mcp' ? entry.platform !== 'mcp' : entry.platform !== undefined && entry.platform !== target)\n continue;\n if (entry.role === 'escape-hatch') {\n escapeHatches.push(entry);\n continue;\n }\n\n if (entry.role === 'root') {\n // Backend only. A root is constructed from a mount context, and the\n // cockpit has none: it builds its plugin definition as data and starts\n // it separately, so there is nothing for a frontend root to receive.\n if (entry.side === 'frontend') {\n notices.push({ path: entry.file, message: 'a scope root is a backend file; the cockpit has no mount context' });\n continue;\n }\n roots.push(entry);\n continue;\n }\n\n const key = logicalKey(entry);\n const held = winners.get(key);\n if (held === undefined) {\n winners.set(key, entry);\n continue;\n }\n if (held.platform === entry.platform) {\n notices.push({ path: entry.file, message: `duplicates ${held.file} for ${target}; the first one wins` });\n continue;\n }\n // A platform file always beats the unsuffixed sibling it overrides.\n if (entry.platform !== undefined) winners.set(key, entry);\n }\n\n const contributions: ResolvedContribution[] = [];\n for (const entry of winners.values()) {\n const field = fieldFor(entry, target);\n if (field === undefined) continue;\n contributions.push({ entry, field });\n }\n\n return {\n target,\n contributions: mergeRenderers(contributions, notices),\n escapeHatches,\n roots: roots.sort((left, right) => SCOPE_DEPTH[left.scope] - SCOPE_DEPTH[right.scope]),\n notices,\n };\n}\n"],"mappings":"wFAgBM,EAAgD,CAAE,OAAQ,EAAG,UAAW,EAAG,QAAS,CAAE,EAW5F,SAAS,EAAU,EAAuB,EAA8B,CAItE,OAHI,IAAW,MAAc,EAAM,OAAS,WACxC,IAAW,MAAc,EAAM,OAAS,UACxC,EAAM,OAAS,WACZ,IAAW,OAAS,EAAM,WAAa,KAChD,CAEA,MAAM,EAA8G,CAClH,IAAK,CAAE,QAASA,EAAAA,WAAY,SAAUC,EAAAA,mBAAoB,EAC1D,OAAQ,CAAE,QAASC,EAAAA,c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1D,CAEA,IAAM,EAAwC,CAAC,EAC/C,IAAK,IAAM,KAAS,EAAQ,OAAO,EAAG,CACpC,IAAM,EAAQ,EAAS,EAAO,CAAM,EAChC,IAAU,IAAA,IACd,EAAc,KAAK,CAAE,QAAO,OAAM,CAAC,CACrC,CAEA,MAAO,CACL,SACA,cAAe,EAAe,EAAe,CAAO,EACpD,gBACA,MAAO,EAAM,MAAM,EAAM,IAAU,EAAY,EAAK,OAAS,EAAY,EAAM,MAAM,EACrF,SACF,CACF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ExtensionGraph } from "../../types/extensionGraph.mjs";
|
|
2
|
+
import { BuildTarget, TargetResolution } from "./type.mjs";
|
|
3
|
+
//#region src/services/resolveTarget/index.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Picks the winning file per logical contribution for one host.
|
|
6
|
+
*
|
|
7
|
+
* Metro and Expo semantics: a file naming this platform replaces a sibling
|
|
8
|
+
* that names none, and a file naming none serves every platform on its side
|
|
9
|
+
* that has no more specific sibling. The scan reports the unnamed one, so this
|
|
10
|
+
* is a fallback rather than a supported way to author. Two files naming the
|
|
11
|
+
* same platform for the same contribution is an authoring mistake, so the
|
|
12
|
+
* first wins and the second becomes a notice rather than silently disappearing.
|
|
13
|
+
*/
|
|
14
|
+
export declare function resolveTarget(graph: ExtensionGraph, target: BuildTarget): TargetResolution;
|
|
15
|
+
//#endregion
|
|
16
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/resolveTarget/index.ts"],"mappings":";;;;;;;;;;;;;wBAyHgB,cAAc,OAAO,gBAAgB,QAAQ,cAAc"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ACTION_FIELDS as e,CLI_FIELDS as t,CLI_FRONTEND_FIELDS as n,MCP_FIELDS as r,SERVER_FIELDS as i,SETTING_FIELDS as a,WEB_FIELDS as o}from"../../constants/contributions.mjs";import{toSnake as s}from"../identity/index.mjs";const c={global:0,workspace:1,session:2};function l(e,t){return t===`web`?e.side===`frontend`:t===`mcp`?e.side===`backend`:e.side===`backend`||t===`cli`&&e.platform===`cli`}const u={cli:{backend:t,frontend:n},server:{backend:i,frontend:{}},web:{backend:{},frontend:o},mcp:{backend:r,frontend:{}}};function d(e){let t=e.gates.map(e=>`${e.kind}:${e.id}`).join(`/`),n=e.route.map(e=>`literal`in e?e.literal:`[${e.param.name}]`).join(`/`);return[e.side,e.scope,t,e.surface??``,n,e.name,e.target??``].join(`|`)}function f(e,t,n){return n===void 0?t:e[n]??t}function p(t,n){let r=t.surface;if(r===void 0)return;let i=u[n][t.side][r];if(i!==void 0&&i!==``&&(n!==`web`||r!==`lifecycle`||t.name===`start`))return n===`web`&&r===`setting`?f(a,i,t.target):n===`web`&&r===`action`?f(e,i,t.target):i}function m(e,t){let n=/* @__PURE__ */ new Map,r=[];for(let t of e)t.field===`tool-renderers`?n.set(s(t.entry.name),t.entry):r.push(t);if(n.size===0)return r;let i=r.map(e=>{if(e.field!==`tools`)return e;let t=s(e.entry.name),r=n.get(t);return r===void 0?e:(n.delete(t),{...e,renderers:r})});for(let e of n.values())t.push({path:e.file,message:`renders a tool no backend file contributes; nothing will draw it`});return i}function h(e,t){let n=[],r=[],i=[],a=/* @__PURE__ */ new Map;for(let o of e.entries){if(!l(o,t)||(t===`mcp`?o.platform!==`mcp`:o.platform!==void 0&&o.platform!==t))continue;if(o.role===`escape-hatch`){r.push(o);continue}if(o.role===`root`){if(o.side===`frontend`){n.push({path:o.file,message:`a scope root is a backend file; the cockpit has no mount context`});continue}i.push(o);continue}let e=d(o),s=a.get(e);if(s===void 0){a.set(e,o);continue}if(s.platform===o.platform){n.push({path:o.file,message:`duplicates ${s.file} for ${t}; the first one wins`});continue}o.platform!==void 0&&a.set(e,o)}let o=[];for(let e of a.values()){let n=p(e,t);n!==void 0&&o.push({entry:e,field:n})}return{target:t,contributions:m(o,n),escapeHatches:r,roots:i.sort((e,t)=>c[e.scope]-c[t.scope]),notices:n}}export{h as resolveTarget};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/resolveTarget/index.ts"],"sourcesContent":["import {\n ACTION_FIELDS,\n CLI_FIELDS,\n CLI_FRONTEND_FIELDS,\n MCP_FIELDS,\n MERGED_INTO_TOOL,\n NOT_A_CONTRIBUTION,\n SERVER_FIELDS,\n SETTING_FIELDS,\n WEB_FIELDS,\n} from '../../constants/contributions';\nimport type { ExtensionEntry, ExtensionGraph, ExtensionNotice, ExtensionSide } from '../../types/extensionGraph';\nimport { toSnake } from '../identity';\nimport type { BuildTarget, ResolvedContribution, TargetResolution } from './type';\n\n/** Nesting order, so roots compose outermost first. */\nconst SCOPE_DEPTH: Readonly<Record<string, number>> = { global: 0, workspace: 1, session: 2 };\n\n/**\n * Which sides a host reads, and which of their files.\n *\n * The side axis is logic against presentation, not Node against browser, so\n * the terminal reads both: every backend file, plus the frontend files that\n * name it. A frontend file that does not name the terminal is cockpit code,\n * which a terminal cannot render, so the CLI takes only explicit `.cli` ones.\n * The headless server has no presentation at all.\n */\nfunction drawsFrom(entry: ExtensionEntry, target: BuildTarget): boolean {\n if (target === 'web') return entry.side === 'frontend';\n if (target === 'mcp') return entry.side === 'backend';\n if (entry.side === 'backend') return true;\n return target === 'cli' && entry.platform === 'cli';\n}\n\nconst FIELDS_OF: Readonly<Record<BuildTarget, Readonly<Record<ExtensionSide, Readonly<Record<string, string>>>>>> = {\n cli: { backend: CLI_FIELDS, frontend: CLI_FRONTEND_FIELDS },\n server: { backend: SERVER_FIELDS, frontend: {} },\n web: { backend: {}, frontend: WEB_FIELDS },\n mcp: { backend: MCP_FIELDS, frontend: {} },\n};\n\n/** Everything but the platform: two files sharing this are the same contribution. */\nfunction logicalKey(entry: ExtensionEntry): string {\n const gates = entry.gates.map((gate) => `${gate.kind}:${gate.id}`).join('/');\n const route = entry.route\n .map((segment) => ('literal' in segment ? segment.literal : `[${segment.param.name}]`))\n .join('/');\n // The side is part of it, because the terminal reads both. Without it a\n // tool's logic and its TUI would look like one contribution overriding the\n // other, and only one of the pair would survive.\n return [entry.side, entry.scope, gates, entry.surface ?? '', route, entry.name, entry.target ?? ''].join('|');\n}\n\n/** Resolves the field for a surface whose filename target picks between two shapes. */\nfunction variantField(\n table: Readonly<Record<string, string>>,\n fallback: string,\n entryTarget: string | undefined,\n): string {\n if (entryTarget === undefined) return fallback;\n return table[entryTarget] ?? fallback;\n}\n\nfunction fieldFor(entry: ExtensionEntry, target: BuildTarget): string | undefined {\n const surface = entry.surface;\n if (surface === undefined) return undefined;\n\n const declared = FIELDS_OF[target][entry.side][surface];\n if (declared === undefined || declared === NOT_A_CONTRIBUTION) return undefined;\n\n if (target === 'web' && surface === 'lifecycle' && entry.name !== 'start') return undefined;\n if (target === 'web' && surface === 'setting') return variantField(SETTING_FIELDS, declared, entry.target);\n if (target === 'web' && surface === 'action') return variantField(ACTION_FIELDS, declared, entry.target);\n return declared;\n}\n\n/**\n * Folds terminal tool renderers into the tool declarations they draw.\n *\n * Paired by the snake-cased filename, which is the tool's name on both sides.\n * A renderer naming no tool this package contributes is reported rather than\n * dropped: it is almost always a rename that only half landed, and a silently\n * missing renderer is the kind of thing nobody notices until a demo.\n */\nfunction mergeRenderers(\n contributions: readonly ResolvedContribution[],\n notices: ExtensionNotice[],\n): ResolvedContribution[] {\n const renderers = new Map<string, ExtensionEntry>();\n const rest: ResolvedContribution[] = [];\n for (const contribution of contributions) {\n if (contribution.field !== MERGED_INTO_TOOL) rest.push(contribution);\n else renderers.set(toSnake(contribution.entry.name), contribution.entry);\n }\n if (renderers.size === 0) return rest;\n\n const merged = rest.map((contribution) => {\n if (contribution.field !== 'tools') return contribution;\n const name = toSnake(contribution.entry.name);\n const found = renderers.get(name);\n if (found === undefined) return contribution;\n renderers.delete(name);\n return { ...contribution, renderers: found };\n });\n\n for (const orphan of renderers.values()) {\n notices.push({ path: orphan.file, message: `renders a tool no backend file contributes; nothing will draw it` });\n }\n return merged;\n}\n\n/**\n * Picks the winning file per logical contribution for one host.\n *\n * Metro and Expo semantics: a file naming this platform replaces a sibling\n * that names none, and a file naming none serves every platform on its side\n * that has no more specific sibling. The scan reports the unnamed one, so this\n * is a fallback rather than a supported way to author. Two files naming the\n * same platform for the same contribution is an authoring mistake, so the\n * first wins and the second becomes a notice rather than silently disappearing.\n */\nexport function resolveTarget(graph: ExtensionGraph, target: BuildTarget): TargetResolution {\n const notices: ExtensionNotice[] = [];\n const escapeHatches: ExtensionEntry[] = [];\n const roots: ExtensionEntry[] = [];\n const winners = new Map<string, ExtensionEntry>();\n\n for (const entry of graph.entries) {\n if (!drawsFrom(entry, target)) continue;\n if (target === 'mcp' ? entry.platform !== 'mcp' : entry.platform !== undefined && entry.platform !== target)\n continue;\n if (entry.role === 'escape-hatch') {\n escapeHatches.push(entry);\n continue;\n }\n\n if (entry.role === 'root') {\n // Backend only. A root is constructed from a mount context, and the\n // cockpit has none: it builds its plugin definition as data and starts\n // it separately, so there is nothing for a frontend root to receive.\n if (entry.side === 'frontend') {\n notices.push({ path: entry.file, message: 'a scope root is a backend file; the cockpit has no mount context' });\n continue;\n }\n roots.push(entry);\n continue;\n }\n\n const key = logicalKey(entry);\n const held = winners.get(key);\n if (held === undefined) {\n winners.set(key, entry);\n continue;\n }\n if (held.platform === entry.platform) {\n notices.push({ path: entry.file, message: `duplicates ${held.file} for ${target}; the first one wins` });\n continue;\n }\n // A platform file always beats the unsuffixed sibling it overrides.\n if (entry.platform !== undefined) winners.set(key, entry);\n }\n\n const contributions: ResolvedContribution[] = [];\n for (const entry of winners.values()) {\n const field = fieldFor(entry, target);\n if (field === undefined) continue;\n contributions.push({ entry, field });\n }\n\n return {\n target,\n contributions: mergeRenderers(contributions, notices),\n escapeHatches,\n roots: roots.sort((left, right) => SCOPE_DEPTH[left.scope] - SCOPE_DEPTH[right.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AAQ,IAAI,CAAG,EAC5B,GAAI,IAAS,IAAA,GAAW,CACtB,EAAQ,IAAI,EAAK,CAAK,EACtB,QACF,CACA,GAAI,EAAK,WAAa,EAAM,SAAU,CACpC,EAAQ,KAAK,CAAE,KAAM,EAAM,KAAM,QAAS,cAAc,EAAK,KAAK,OAAO,EAAO,qBAAsB,CAAC,EACvG,QACF,CAEI,EAAM,WAAa,IAAA,IAAW,EAAQ,IAAI,EAAK,CAAK,CAC1D,CAEA,IAAM,EAAwC,CAAC,EAC/C,IAAK,IAAM,KAAS,EAAQ,OAAO,EAAG,CACpC,IAAM,EAAQ,EAAS,EAAO,CAAM,EAChC,IAAU,IAAA,IACd,EAAc,KAAK,CAAE,QAAO,OAAM,CAAC,CACrC,CAEA,MAAO,CACL,SACA,cAAe,EAAe,EAAe,CAAO,EACpD,gBACA,MAAO,EAAM,MAAM,EAAM,IAAU,EAAY,EAAK,OAAS,EAAY,EAAM,MAAM,EACrF,SACF,CACF"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ExtensionEntry, ExtensionNotice } from "../../types/extensionGraph.mjs";
|
|
2
|
+
//#region src/services/resolveTarget/type.d.ts
|
|
3
|
+
/** The hosts an entry can be generated for. */
|
|
4
|
+
export type BuildTarget = 'cli' | 'server' | 'web' | 'mcp';
|
|
5
|
+
/** One file and the host contribution array it belongs in. */
|
|
6
|
+
export interface ResolvedContribution {
|
|
7
|
+
/** The winning file for this logical contribution on this host. */
|
|
8
|
+
readonly entry: ExtensionEntry;
|
|
9
|
+
/** The host contribution array this belongs in. */
|
|
10
|
+
readonly field: string;
|
|
11
|
+
/**
|
|
12
|
+
* A presentation file folded into this contribution rather than emitted
|
|
13
|
+
* beside it. Only the terminal has one: its tool renderers are fields of the
|
|
14
|
+
* tool declaration, so the pair becomes a single registration.
|
|
15
|
+
*/
|
|
16
|
+
readonly renderers?: ExtensionEntry;
|
|
17
|
+
}
|
|
18
|
+
/** Everything one host needs generated, plus anything skipped on the way. */
|
|
19
|
+
export interface TargetResolution {
|
|
20
|
+
readonly target: BuildTarget;
|
|
21
|
+
readonly contributions: readonly ResolvedContribution[];
|
|
22
|
+
/** Escape-hatch files whose raw contributions are merged in wholesale. */
|
|
23
|
+
readonly escapeHatches: readonly ExtensionEntry[];
|
|
24
|
+
/**
|
|
25
|
+
* Scope constructors, outermost first.
|
|
26
|
+
*
|
|
27
|
+
* Each one runs before the contributions beneath it and its value joins
|
|
28
|
+
* their mount context, so the order is the nesting order and nothing else.
|
|
29
|
+
*/
|
|
30
|
+
readonly roots: readonly ExtensionEntry[];
|
|
31
|
+
readonly notices: readonly ExtensionNotice[];
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//# sourceMappingURL=type.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type.d.mts","names":[],"sources":["../../../src/services/resolveTarget/type.ts"],"mappings":";;;YAGY;;iBAGK;;WAEN,OAAO;;WAEP;;;;;;WAMA,YAAY;;;iBAIN;WACN,QAAQ;WACR,wBAAwB;;WAExB,wBAAwB;;;;;;;WAOxB,gBAAgB;WAChB,kBAAkB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../constants/layout.cjs"),n=require("../filename/index.cjs"),r=require("../segments/index.cjs");let i=require("node:fs");i=e.__toESM(i,1);let a=require("node:path");a=e.__toESM(a,1);const o={scope:`global`,side:void 0,gates:[],surface:void 0,route:[],pendingGate:void 0};function s(e){return e===`backend`?t.BACKEND_SURFACES:t.FRONTEND_SURFACES}function c(e,n){return(e===`backend`?n.platforms?.backend:n.platforms?.frontend)??(e===`backend`?t.BACKEND_PLATFORMS:t.FRONTEND_PLATFORMS)}function l(e,t){let n=s(t);if(n.includes(e))return;let r=e.endsWith(`s`)?e.slice(0,-1):`${e}s`;return n.includes(r)?r:void 0}function u(e){return/export\s+default\s+defineRoutedContribution\s*\([\s\S]*,\s*\{\s*cardinality\s*:\s*['"](optional|many|collection)['"]/u.exec(e)?.[1]}function d(e,n){return(n===void 0?[t.DEFAULT_ROUTING_ROOT,t.ROUTING_ROOT_ALIAS]:[n]).find(t=>i.default.existsSync(a.default.join(e,t)))}function f(e){let f=d(e.packageDir,e.root);if(f===void 0)return{root:e.root??`src/extensions`,entries:[],notices:[]};let p=e.sides?.backend??`backend`,m=e.sides?.frontend??`frontend`,h=e.generatedEntries??t.GENERATED_ENTRY_NAMES,g=[],_=[],v=(e,t)=>void _.push({path:e,message:t}),y=(t,n,r)=>{n.platform===void 0&&v(t,`names no platform; add one of ${c(r,e).join(`, `)} before .${n.extension} (without one the host is inferred from the side rather than declared)`)},b=(t,n)=>{let r=a.default.join(e.packageDir,t),o=i.default.readdirSync(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name));for(let e of o){let r=`${t}/${e.name}`;e.isDirectory()?x(r,e.name,n):e.isFile()&&S(r,e.name,n)}},x=(e,n,i)=>{let a=r.classifySegment(n);if(a.kind===`private`)return;if(a.kind===`group`)return i.side===void 0&&a.name===p?b(e,{...i,side:`backend`}):i.side===void 0&&a.name===m?b(e,{...i,side:`frontend`}):b(e,i);if(a.kind===`dynamic`)return i.surface!==void 0&&t.ROUTED_SURFACES.includes(i.surface)?b(e,{...i,route:[...i.route,{param:a.param}]}):v(e,`a dynamic segment is only meaningful inside a routed surface such as api/`);if(i.pendingGate!==void 0){let t={kind:i.pendingGate,id:a.name};return b(e,{...i,gates:[...i.gates,t],pendingGate:void 0})}if(i.surface!==void 0)return t.ROUTED_SURFACES.includes(i.surface)?b(e,{...i,route:[...i.route,{literal:a.name}]}):v(e,`${i.surface}/ takes files directly; put helpers in a _private folder`);if(i.side===void 0)return a.name===`workspaces`&&i.scope===`global`?b(e,{...i,scope:`workspace`}):a.name===`sessions`&&i.scope===`workspace`?b(e,{...i,scope:`session`}):v(e,`expected a scope segment or a side group, such as (${p})`);if(t.GATE_SEGMENTS.includes(a.name))return b(e,{...i,pendingGate:a.name});if(s(i.side).includes(a.name))return b(e,{...i,surface:a.name});let o=l(a.name,i.side);return v(e,o===void 0?`'${a.name}' is not a ${i.side} surface`:`'${a.name}' is not a surface, did you mean '${o}'`)},S=(r,o,s)=>{if(s.side===void 0){let e=o.slice(0,o.lastIndexOf(`.`));return s.scope===`global`&&h.includes(e)||s.scope===`global`||n.parseFilename(o,[])===void 0?void 0:v(r,`a contribution needs a side group and a surface folder`)}let l=c(s.side,e),d=n.parseFilename(o,[...l,`mcp`]);if(d===void 0)return;if(d.platform===`mcp`&&(s.side!==`backend`||s.scope!==`session`||s.surface!==`tool`&&s.surface!==`skill`&&s.surface!==`resource`))return v(r,`MCP declarations belong in a session backend tool/, skill/, or resource/ surface`);let f=u(i.default.readFileSync(a.default.join(e.packageDir,r),`utf8`));if(s.surface===void 0){let e=s.gates[s.gates.length-1];if(e!==void 0&&d.name===e.kind){y(r,d,s.side),g.push({file:r,scope:s.scope,side:s.side,gates:s.gates.slice(0,-1),surface:e.kind,route:[],name:e.id,target:d.target,platform:d.platform,...f?{cardinality:f}:{},role:`contribution`});return}if(d.name===`root`&&e===void 0){y(r,d,s.side),g.push({file:r,scope:s.scope,side:s.side,gates:[],surface:void 0,route:[],name:d.name,target:d.target,platform:d.platform,role:`root`});return}return v(r,e===void 0?`only ${t.ROOT_FILE_NAME}.* is read at a side root; move each contribution into its named surface folder`:`inside ${e.kind}/${e.id}/ a contribution needs a surface folder, or name the file ${e.kind}.* to declare the gate`)}t.ROUTED_SURFACES.includes(s.surface)&&d.name!==`route`||(y(r,d,s.side),g.push({file:r,scope:s.scope,side:s.side,gates:s.gates,surface:s.surface,route:s.route,name:d.name,target:d.target,platform:d.platform,...f?{cardinality:f}:{},role:`contribution`}))};return b(f,o),{root:f,entries:g,notices:_}}exports.resolveRoutingRoot=d,exports.scanExtensions=f;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|