capable-kit 0.0.1-alpha.8 → 0.1.0-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.
Files changed (87) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +6 -0
  3. package/dist/ai-sdk.d.mts +3 -3
  4. package/dist/ai-sdk.mjs +9 -7
  5. package/dist/ai-sdk.mjs.map +1 -1
  6. package/dist/app.d.mts +2 -2
  7. package/dist/app.mjs +2 -2
  8. package/dist/bin.mjs +4 -4
  9. package/dist/cli.d.mts +9 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/core.d.mts +3 -3
  12. package/dist/core.mjs +1 -1
  13. package/dist/eve.d.mts +82 -5
  14. package/dist/eve.mjs +364 -23
  15. package/dist/eve.mjs.map +1 -1
  16. package/dist/http.d.mts +1 -1
  17. package/dist/http.mjs +1 -1
  18. package/dist/{index-F4ba_olD.d.mts → index-1A44jLuE.d.mts} +54 -16
  19. package/dist/{index-Dl4NK9G0.d.mts → index-CHuCLJIs.d.mts} +3 -3
  20. package/dist/{index-hdH_K5Zc.d.mts → index-D-NV4PiU.d.mts} +4 -4
  21. package/dist/{index-_qKFfWV4.d.mts → index-WiBWfyTn.d.mts} +63 -26
  22. package/dist/index.d.mts +4 -4
  23. package/dist/index.mjs +3 -3
  24. package/dist/mcp.d.mts +7 -2
  25. package/dist/mcp.mjs +1 -1
  26. package/dist/{mount-CEFAplR5.mjs → mount-BmLHp349.mjs} +16 -8
  27. package/dist/mount-BmLHp349.mjs.map +1 -0
  28. package/dist/react-query.d.mts +2 -2
  29. package/dist/react-query.mjs +1 -1
  30. package/dist/react-query.mjs.map +1 -1
  31. package/dist/runtime-support.d.mts +1 -1
  32. package/dist/runtime-support.mjs +3 -3
  33. package/dist/server.d.mts +1 -1
  34. package/dist/server.mjs +1 -1
  35. package/dist/{src-D_0PIhqq.mjs → src-3LE9S4QE.mjs} +67 -38
  36. package/dist/src-3LE9S4QE.mjs.map +1 -0
  37. package/dist/{src-D-cm2gQ6.mjs → src-B2WeUwUT.mjs} +64 -32
  38. package/dist/src-B2WeUwUT.mjs.map +1 -0
  39. package/dist/{src-BWxDO2Ua.mjs → src-C5jGDnuu.mjs} +3 -3
  40. package/dist/{src-BWxDO2Ua.mjs.map → src-C5jGDnuu.mjs.map} +1 -1
  41. package/dist/src-DePlcG_t.mjs +787 -0
  42. package/dist/src-DePlcG_t.mjs.map +1 -0
  43. package/dist/{src-rkr5j_NH.mjs → src-_6OmFRYa.mjs} +28 -10
  44. package/dist/src-_6OmFRYa.mjs.map +1 -0
  45. package/dist/{subscription-B-auXJbm.d.mts → subscription-DPdwovhw.d.mts} +2 -2
  46. package/dist/swr.d.mts +2 -2
  47. package/dist/swr.mjs +1 -1
  48. package/dist/swr.mjs.map +1 -1
  49. package/docs/CONTEXT.md +39 -20
  50. package/docs/README.md +3 -0
  51. package/docs/internal/README.md +3 -0
  52. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  53. package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
  54. package/docs/internal/architecture.md +31 -17
  55. package/docs/internal/capability-first-model.md +126 -17
  56. package/docs/internal/eve-recovery-validation.md +86 -0
  57. package/docs/internal/feedback/v-ray/README.md +258 -0
  58. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  59. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  60. package/docs/internal/implementation-friction.md +386 -1
  61. package/docs/internal/releases.md +79 -0
  62. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  63. package/docs/site/concepts/apps.mdx +7 -1
  64. package/docs/site/concepts/architecture.mdx +9 -1
  65. package/docs/site/concepts/capabilities.mdx +41 -4
  66. package/docs/site/concepts/errors.mdx +11 -1
  67. package/docs/site/concepts/presentations.mdx +20 -0
  68. package/docs/site/patterns/composition.mdx +152 -8
  69. package/docs/site/patterns/remote-apps.mdx +6 -2
  70. package/docs/site/patterns/subscriptions.mdx +79 -32
  71. package/docs/site/quickstart.mdx +1 -1
  72. package/docs/site/reference/packages-and-entry-points.mdx +50 -3
  73. package/docs/site/surfaces/cli.mdx +44 -0
  74. package/docs/site/surfaces/eve.mdx +65 -18
  75. package/docs/site/surfaces/typescript.mdx +3 -3
  76. package/package-docs.mjs +3 -0
  77. package/package.json +10 -11
  78. package/src/bin.ts +0 -0
  79. package/src/index.test.ts +2 -1
  80. package/src/index.ts +6 -1
  81. package/src/package.test.ts +9 -0
  82. package/dist/mount-CEFAplR5.mjs.map +0 -1
  83. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  84. package/dist/src-D_0PIhqq.mjs.map +0 -1
  85. package/dist/src-betOfnDL.mjs +0 -481
  86. package/dist/src-betOfnDL.mjs.map +0 -1
  87. package/dist/src-rkr5j_NH.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DePlcG_t.mjs","names":["samePath"],"sources":["../../app/src/manifest.ts","../../app/src/runtime.ts","../../app/src/customization.ts","../../app/src/composition.ts"],"sourcesContent":["import {\n isCapability,\n isCapabilityGroup,\n schemaToJsonSchema,\n type AnySchema,\n type CapabilityExecution,\n type AppDefinition,\n type LocatedCapability,\n} from \"@capable/core\";\n\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\nexport type ManifestError = {\n readonly message?: string;\n readonly data?: JsonSchema;\n readonly status?: number;\n readonly meta?: Readonly<Record<string, unknown>>;\n};\n\nexport type ManifestCapability = {\n readonly type: \"capability\";\n readonly customization?: {\n /** Use the Capability's placed path for surface navigation. */\n readonly navigation?: \"destination\";\n readonly title?: string;\n readonly description?: string;\n readonly meta?: Readonly<Record<string, unknown>>;\n };\n readonly id: string;\n readonly path: readonly string[];\n readonly title?: string;\n readonly description?: string;\n readonly deprecated: boolean;\n readonly effect?: \"read\" | \"write\" | \"destructive\";\n readonly execution: CapabilityExecution;\n readonly input?: JsonSchema;\n readonly output?: JsonSchema;\n readonly errors: Readonly<Record<string, ManifestError>>;\n readonly meta: Readonly<Record<string, unknown>>;\n};\n\nexport type ManifestGroup = {\n readonly type: \"group\";\n readonly key: string;\n readonly title?: string;\n readonly description?: string;\n readonly meta: Readonly<Record<string, unknown>>;\n readonly children: readonly ManifestNode[];\n};\n\nexport type ManifestNode = ManifestGroup | ManifestCapability;\n\nexport type ApplicationManifest = {\n readonly protocol: \"capable.capabilities.v4\";\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: readonly ManifestNode[];\n};\n\nexport function createAppManifest(\n definition: AppDefinition<any>,\n): ApplicationManifest {\n const byCapability = new Map(\n definition.locatedCapabilities.map((entry) => [entry.capability, entry]),\n );\n return Object.freeze({\n protocol: \"capable.capabilities.v4\",\n name: definition.name,\n version: definition.version,\n ...(definition.description ? { description: definition.description } : {}),\n capabilities: manifestNodes(definition.capabilities, byCapability),\n });\n}\n\nexport function validateManifest(\n manifest: ApplicationManifest,\n label: string,\n): void {\n if (manifest.protocol !== \"capable.capabilities.v4\") {\n throw new Error(`${label} uses unsupported protocol \"${manifest.protocol}\"`);\n }\n const capabilities = flattenManifestCapabilities(manifest.capabilities);\n const ids = new Map<string, ManifestCapability>();\n const paths = new Set<string>();\n for (const capability of capabilities) {\n if (![\"unary\", \"live\", \"events\"].includes(capability.execution)) {\n throw new Error(`${label} contains unsupported execution kind for Capability \"${capability.id}\"`);\n }\n if (capability.execution !== \"unary\" && capability.effect !== \"read\") {\n throw new Error(`${label} subscribable Capability \"${capability.id}\" must have effect \"read\"`);\n }\n const path = capability.path.join(\".\");\n const previous = ids.get(capability.id);\n if (previous && !sameCapabilityContract(previous, capability)) {\n throw new Error(\n `${label} contains conflicting definitions for Capability id \"${capability.id}\"`,\n );\n }\n if (paths.has(path)) {\n throw new Error(`${label} contains duplicate Capability path \"${path}\"`);\n }\n ids.set(capability.id, capability);\n paths.add(path);\n }\n validateManifestPaths(manifest.capabilities, [], label);\n}\n\nexport type ApplicationManifestSource<TOwner extends object = object> = {\n readonly manifest: ApplicationManifest;\n /** Identity used only to avoid repeating one source in the composed label. */\n readonly application: object;\n /** Terminal execution owner for every Capability ID in this source view. */\n readonly owners: ReadonlyMap<string, TOwner>;\n};\n\nexport function composeApplicationManifests(\n sources: readonly ApplicationManifestSource[],\n): ApplicationManifest {\n const conflicts = collectManifestConflicts(sources);\n if (conflicts.length) {\n throw new Error(\n `Cannot compose Apps:\\n${conflicts.map((item) => `- ${item}`).join(\"\\n\")}`,\n );\n }\n const manifests = sources.map(({ manifest }) => manifest);\n const applications = sources.filter((source, index) =>\n sources.findIndex(({ application }) => application === source.application) === index\n ).map(({ manifest }) => manifest);\n return Object.freeze({\n protocol: \"capable.capabilities.v4\",\n name: applications.map(({ name }) => name).join(\" + \"),\n version: applications.map(({ version }) => version).join(\" + \"),\n capabilities: mergeManifestNodes(\n manifests.flatMap(({ capabilities }) => capabilities),\n ),\n });\n}\n\nexport function selectManifest(\n source: ApplicationManifest,\n selection: {\n readonly include?: unknown;\n readonly exclude?: unknown;\n },\n): ApplicationManifest {\n validateSelectionTree(selection.include, source.capabilities, \"include\", []);\n validateSelectionTree(selection.exclude, source.capabilities, \"exclude\", []);\n return Object.freeze({\n ...source,\n capabilities: filterManifestNodes(source.capabilities, selection),\n });\n}\n\nfunction validateSelectionTree(\n tree: unknown,\n nodes: readonly ManifestNode[],\n label: \"include\" | \"exclude\",\n parent: readonly string[],\n): void {\n if (tree === undefined || tree === true) return;\n if (!tree || typeof tree !== \"object\" || Array.isArray(tree)) {\n throw new Error(\n `Application selection ${label} at \"${parent.join(\".\") || \"<root>\"}\" must be an object or true`,\n );\n }\n for (const [key, child] of Object.entries(tree)) {\n const path = [...parent, key];\n const node = nodes.find((candidate) =>\n candidate.type === \"group\"\n ? candidate.key === key\n : candidate.path.at(-1) === key\n );\n if (!node) {\n throw new Error(\n `Application selection ${label} references unknown path \"${path.join(\".\")}\"`,\n );\n }\n if (child === true) continue;\n if (node.type === \"capability\") {\n throw new Error(\n `Application selection ${label} at \"${path.join(\".\")}\" must be true`,\n );\n }\n validateSelectionTree(child, node.children, label, path);\n }\n}\n\nexport function flattenManifestCapabilities(\n nodes: readonly ManifestNode[],\n): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\"\n ? [node]\n : flattenManifestCapabilities(node.children)\n );\n}\n\nexport function findManifestCapability(\n nodes: readonly ManifestNode[],\n path: readonly string[],\n): ManifestCapability | undefined {\n const node = findManifestNode(nodes, path);\n return node?.type === \"capability\" ? node : undefined;\n}\n\nexport function findManifestNode(\n nodes: readonly ManifestNode[],\n path: readonly string[],\n): ManifestNode | undefined {\n let current = nodes;\n for (let index = 0; index < path.length; index++) {\n const key = path[index]!;\n const node = current.find((candidate) =>\n candidate.type === \"group\"\n ? candidate.key === key\n : candidate.path.at(-1) === key\n );\n if (!node) return undefined;\n if (node.type === \"capability\") {\n return index === path.length - 1 ? node : undefined;\n }\n if (index === path.length - 1) return node;\n current = node.children;\n }\n return undefined;\n}\n\nfunction manifestNodes(\n tree: Readonly<Record<string, unknown>>,\n located: ReadonlyMap<unknown, LocatedCapability>,\n): readonly ManifestNode[] {\n const nodes: ManifestNode[] = [];\n for (const [key, value] of Object.entries(tree)) {\n if (isCapability(value)) {\n const entry = located.get(value);\n if (entry) nodes.push(manifestCapability(entry));\n continue;\n }\n const decorated = isCapabilityGroup(value);\n const childTree = decorated\n ? value.capabilities\n : value as Readonly<Record<string, unknown>>;\n const children = manifestNodes(childTree, located);\n nodes.push(Object.freeze({\n type: \"group\",\n key,\n ...(decorated && value.title ? { title: value.title } : {}),\n ...(decorated && value.description\n ? { description: value.description }\n : {}),\n meta: decorated ? value.meta : {},\n children,\n } satisfies ManifestGroup));\n }\n return nodes;\n}\n\nfunction manifestCapability(entry: LocatedCapability): ManifestCapability {\n const capability = entry.capability;\n return Object.freeze({\n type: \"capability\",\n id: capability.id,\n path: entry.path,\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n deprecated: capability.deprecated,\n ...(capability.effect ? { effect: capability.effect } : {}),\n execution: capability.execution,\n ...(capability.input\n ? { input: manifestJsonSchema(capability.input, \"input\") }\n : {}),\n ...(capability.output\n ? { output: manifestJsonSchema(capability.output, \"output\") }\n : {}),\n errors: Object.fromEntries(\n Object.entries(entry.errors).map(([code, definition]) => [\n code,\n {\n ...(definition.message ? { message: definition.message } : {}),\n ...(typeof definition.status === \"number\"\n ? { status: definition.status }\n : {}),\n ...(definition.data\n ? { data: manifestJsonSchema(definition.data, \"output\") }\n : {}),\n ...(definition.meta ? { meta: definition.meta } : {}),\n } satisfies ManifestError,\n ]),\n ),\n meta: capability.meta,\n });\n}\n\nfunction manifestJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n): JsonSchema {\n return schemaToJsonSchema(schema, direction, {\n allowUnrepresentable: true,\n });\n}\n\nfunction validateManifestPaths(\n nodes: readonly ManifestNode[],\n parent: readonly string[],\n label: string,\n): void {\n for (const node of nodes) {\n if (node.type === \"group\") {\n validateManifestPaths(node.children, [...parent, node.key], label);\n continue;\n }\n if (!samePath(node.path, [...parent, node.path.at(-1)!])) {\n throw new Error(\n `${label} Capability \"${node.id}\" declares path \"${node.path.join(\".\")}\" that does not match its manifest placement`,\n );\n }\n }\n}\n\nfunction collectManifestConflicts(\n sources: readonly ApplicationManifestSource[],\n): readonly string[] {\n const conflicts: string[] = [];\n for (const { manifest } of sources) {\n try {\n validateManifest(manifest, manifest.name);\n } catch (error) {\n conflicts.push(error instanceof Error ? error.message : String(error));\n }\n }\n const capabilities = sources.flatMap(({ manifest, owners }, source) =>\n flattenManifestCapabilities(manifest.capabilities).map((capability) => ({\n capability,\n source,\n owner: requiredOwner(owners, capability.id, manifest.name),\n label: manifest.name,\n }))\n );\n for (let leftIndex = 0; leftIndex < capabilities.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < capabilities.length;\n rightIndex++\n ) {\n const left = capabilities[leftIndex]!;\n const right = capabilities[rightIndex]!;\n if (left.source === right.source) continue;\n const sameId = left.capability.id === right.capability.id;\n const sameCapabilityPath = samePath(\n left.capability.path,\n right.capability.path,\n );\n if (sameCapabilityPath) {\n conflicts.push(\n sameId\n ? `Capability \"${left.capability.id}\" is placed twice at \"${left.capability.path.join(\".\")}\" by \"${left.label}\" and \"${right.label}\"`\n : `Path \"${left.capability.path.join(\".\")}\" contains both \"${left.capability.id}\" from \"${left.label}\" and \"${right.capability.id}\" from \"${right.label}\"`,\n );\n continue;\n }\n if (sameId) {\n if (left.owner !== right.owner) {\n conflicts.push(\n `Capability id \"${left.capability.id}\" is owned by different Apps at \"${left.capability.path.join(\".\")}\" in \"${left.label}\" and \"${right.capability.path.join(\".\")}\"`,\n );\n }\n }\n if (\n isPathPrefix(left.capability.path, right.capability.path) ||\n isPathPrefix(right.capability.path, left.capability.path)\n ) {\n const leaf = left.capability.path.length < right.capability.path.length\n ? left\n : right;\n const subtree = leaf === left ? right : left;\n conflicts.push(\n `Leaf \"${leaf.capability.path.join(\".\")}\" from \"${leaf.label}\" collides with subtree Capability \"${subtree.capability.path.join(\".\")}\" from \"${subtree.label}\"`,\n );\n }\n }\n }\n return [...new Set(conflicts)];\n}\n\nfunction requiredOwner(\n owners: ReadonlyMap<string, object>,\n capabilityId: string,\n application: string,\n): object {\n const owner = owners.get(capabilityId);\n if (!owner) {\n throw new Error(\n `Missing execution owner for Capability \"${capabilityId}\" in \"${application}\"`,\n );\n }\n return owner;\n}\n\nfunction sameCapabilityContract(\n left: ManifestCapability,\n right: ManifestCapability,\n): boolean {\n const { path: _leftPath, customization: _leftCustomization, ...leftContract } = left;\n const { path: _rightPath, customization: _rightCustomization, ...rightContract } = right;\n return JSON.stringify(leftContract) === JSON.stringify(rightContract);\n}\n\nfunction mergeManifestNodes(\n nodes: readonly ManifestNode[],\n): readonly ManifestNode[] {\n const merged = new Map<string, ManifestNode>();\n for (const node of nodes) {\n const key = node.type === \"group\" ? node.key : node.path.at(-1)!;\n const previous = merged.get(key);\n if (!previous) {\n merged.set(key, node);\n continue;\n }\n if (previous.type !== \"group\" || node.type !== \"group\") {\n throw new Error(`Manifest node collision at \"${key}\"`);\n }\n merged.set(key, Object.freeze({\n type: \"group\",\n key,\n ...mergeGroupField(\"title\", previous.title, node.title, key),\n ...mergeGroupField(\n \"description\",\n previous.description,\n node.description,\n key,\n ),\n meta: mergeGroupMeta(previous.meta, node.meta, key),\n children: mergeManifestNodes([...previous.children, ...node.children]),\n }));\n }\n return [...merged.values()];\n}\n\nfunction mergeGroupField(\n field: \"title\" | \"description\",\n left: string | undefined,\n right: string | undefined,\n path: string,\n): Record<string, string> {\n if (left && right && left !== right) {\n throw new Error(`Group \"${path}\" has conflicting ${field}`);\n }\n const value = left ?? right;\n return value ? { [field]: value } : {};\n}\n\nfunction mergeGroupMeta(\n left: Readonly<Record<string, unknown>>,\n right: Readonly<Record<string, unknown>>,\n path: string,\n): Readonly<Record<string, unknown>> {\n const merged: Record<string, unknown> = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (\n key in merged &&\n JSON.stringify(merged[key]) !== JSON.stringify(value)\n ) {\n throw new Error(\n `Group \"${path}\" has conflicting metadata for \"${key}\"`,\n );\n }\n merged[key] = value;\n }\n return Object.freeze(merged);\n}\n\nfunction filterManifestNodes(\n nodes: readonly ManifestNode[],\n selection: {\n readonly include?: unknown;\n readonly exclude?: unknown;\n },\n): readonly ManifestNode[] {\n const filtered: ManifestNode[] = [];\n for (const node of nodes) {\n if (node.type === \"capability\") {\n const included = selection.include\n ? matchesManifestSelection(selection.include, node.path)\n : true;\n if (\n included && !matchesManifestSelection(selection.exclude, node.path)\n ) {\n filtered.push(node);\n }\n continue;\n }\n const children = filterManifestNodes(node.children, selection);\n if (children.length) filtered.push(Object.freeze({ ...node, children }));\n }\n return filtered;\n}\n\nfunction matchesManifestSelection(\n tree: unknown,\n path: readonly string[],\n): boolean {\n let current = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction samePath(\n left: readonly string[],\n right: readonly string[],\n): boolean {\n return left.length === right.length &&\n left.every((segment, index) => segment === right[index]);\n}\n\nfunction isPathPrefix(\n prefix: readonly string[],\n path: readonly string[],\n): boolean {\n return prefix.length < path.length &&\n prefix.every((segment, index) => segment === path[index]);\n}\n","import {\n CapableError,\n executeLocatedCapability,\n normalizePresentation,\n subscribeLocatedCapability,\n type AnyCapability,\n type AnyObjectSchema,\n type AppDefinition,\n type AppContext,\n type InferSchemaInput,\n type LocatedCapability,\n type MaybePromise,\n type PresentationPart,\n type CapabilityDefinition,\n type CapabilityGroupDefinition,\n type CapabilityOutput,\n type CapabilityTree,\n type SubscribableCapability,\n} from \"@capable/core\";\nimport {\n createAppManifest,\n findManifestCapability,\n validateManifest,\n type ApplicationManifest,\n type ManifestCapability,\n} from \"./manifest.ts\";\n\nexport type CapabilityCall = {\n readonly id: string;\n readonly input?: unknown;\n readonly signal?: AbortSignal;\n readonly presentation?: boolean;\n};\n\nexport type CapabilityResult = {\n readonly output: unknown;\n readonly presentation?: readonly PresentationPart[];\n};\n\nexport interface ApplicationTransport {\n manifest(\n options?: { readonly signal?: AbortSignal },\n ): Promise<ApplicationManifest>;\n call(call: CapabilityCall): Promise<CapabilityResult>;\n subscribe(\n call: CapabilityCall,\n ): Promise<AsyncIterableIterator<CapabilityResult>>;\n}\n\nexport type ResolvedCapability = {\n readonly capability: ManifestCapability;\n readonly transport: ApplicationTransport;\n};\n\n/** The in-process runtime can bind one path without resolving sibling Apps. */\nexport interface ApplicationRuntime extends ApplicationTransport {\n resolve(path: readonly string[]): Promise<ResolvedCapability | undefined>;\n}\n\nfunction mapAsyncIterator<TInput, TOutput>(\n source: AsyncIterableIterator<TInput>,\n transform: (value: TInput) => TOutput | Promise<TOutput>,\n transformError: (error: unknown) => unknown = (error) => error,\n): AsyncIterableIterator<TOutput> {\n let failed = false;\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n async next() {\n try {\n const result = await source.next();\n return result.done\n ? { done: true, value: undefined }\n : { done: false, value: await transform(result.value) };\n } catch (error) {\n failed = true;\n await source.return?.().catch(() => undefined);\n throw transformError(error);\n }\n },\n async return() {\n if (failed) return { done: true, value: undefined };\n try {\n await source.return?.();\n return { done: true, value: undefined };\n } catch (error) {\n throw transformError(error);\n }\n },\n };\n}\n\nexport const APP_RUNTIME_SYMBOL: unique symbol = Symbol.for(\n \"capable.app.runtime\",\n) as never;\nexport const APP_CAPABILITIES_SYMBOL: unique symbol = Symbol.for(\n \"capable.app.capabilities\",\n) as never;\nconst APP_CALL_SYMBOL = Symbol.for(\"capable.app.call\");\n\nexport type CapabilityBinding = {\n readonly runtime: ApplicationRuntime;\n readonly path: readonly string[];\n};\n\n/** @internal Shared by composition and subscriptions; ordinary functions are not references. */\nexport function getCapabilityBinding(\n value: unknown,\n): CapabilityBinding | undefined {\n return typeof value === \"function\"\n ? (value as unknown as Record<symbol, CapabilityBinding>)[APP_CALL_SYMBOL]\n : undefined;\n}\n\nexport type AppCapabilityReference<\n TCapability extends AnyCapability = AnyCapability,\n> = {\n readonly \"~capable/capability\": TCapability;\n};\n\ntype AppCapabilityInput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends AnyObjectSchema\n ? InferSchemaInput<TInput>\n : Record<never, never>\n : never;\n\ntype AppCapabilityOutput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, any, infer TOutput, any, any>\n ? TOutput\n : never;\n\ntype AppCapabilityOptions = { readonly signal?: AbortSignal };\n\ntype AppCapabilityArgs<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends undefined\n ? [\n input?: Record<never, never>,\n options?: AppCapabilityOptions,\n ]\n : Record<never, never> extends AppCapabilityInput<TCapability>\n ? [\n input?: AppCapabilityInput<TCapability>,\n options?: AppCapabilityOptions,\n ]\n : [\n input: AppCapabilityInput<TCapability>,\n options?: AppCapabilityOptions,\n ]\n : never;\n\nexport type AppCapabilityCall<TCapability extends AnyCapability> = ((\n ...args: AppCapabilityArgs<TCapability>\n) => Promise<AppCapabilityOutput<TCapability>>) &\n AppCapabilityReference<TCapability>;\n\nexport type AppCapabilityIsSubscribable<TCall> =\n TCall extends AppCapabilityReference<infer TCapability>\n ? TCapability[\"execution\"] extends \"live\" | \"events\" ? true : false\n : false;\n\nexport type AppCapabilityIsLive<TCall> =\n TCall extends AppCapabilityReference<infer TCapability>\n ? TCapability[\"execution\"] extends \"live\" ? true : false\n : false;\n\nexport type CallableTree<TTree> =\n TTree extends AnyCapability\n ? TTree[\"execution\"] extends \"events\"\n ? AppCapabilityReference<TTree>\n : AppCapabilityCall<TTree>\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CallableTree<TCapabilities>\n : TTree extends CapabilityTree\n ? { readonly [TKey in keyof TTree]: CallableTree<TTree[TKey]> }\n : never;\n\nexport type App<\n TCapabilities extends CapabilityTree = CapabilityTree,\n> = CallableTree<TCapabilities> & {\n readonly [APP_RUNTIME_SYMBOL]: ApplicationTransport;\n readonly [APP_CAPABILITIES_SYMBOL]?: TCapabilities;\n};\n\nexport type AnyApp = {\n readonly [APP_RUNTIME_SYMBOL]: ApplicationTransport;\n readonly [APP_CAPABILITIES_SYMBOL]?: CapabilityTree;\n};\n\ntype DefinitionCapabilities<TDefinition extends AppDefinition<any, any>> =\n TDefinition extends AppDefinition<infer TCapabilities>\n ? TCapabilities\n : never;\n\nexport type AppCapabilities<\n TApplication extends AnyApp,\n> = TApplication extends {\n readonly [APP_CAPABILITIES_SYMBOL]?: infer TCapabilities extends CapabilityTree;\n}\n ? TCapabilities\n : never;\n\nexport function getAppRuntime(\n app: AnyApp,\n): ApplicationTransport {\n return app[APP_RUNTIME_SYMBOL];\n}\n\n/** @internal Composition uses path bindings without exposing them to transports. */\nexport function getInternalAppRuntime(\n app: AnyApp,\n): ApplicationRuntime {\n const runtime = app[APP_RUNTIME_SYMBOL];\n if (!(\"resolve\" in runtime) || typeof runtime.resolve !== \"function\") {\n throw new TypeError(\"Capable App is missing its internal path resolver\");\n }\n return runtime as ApplicationRuntime;\n}\n\nexport function isApp(value: unknown): value is AnyApp {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n (value as Partial<AnyApp>)[APP_RUNTIME_SYMBOL],\n );\n}\n\nexport function appFromRuntime<\n TCapabilities extends CapabilityTree,\n>(\n runtime: ApplicationRuntime,\n): App<TCapabilities> {\n const read = (path: readonly string[], root: boolean, key: PropertyKey) => {\n if (root && key === APP_RUNTIME_SYMBOL) return runtime;\n if (!root && key === APP_CALL_SYMBOL) return { runtime, path };\n if (key === \"then\") return undefined;\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key], false);\n };\n\n const proxy = (path: readonly string[], root: boolean): unknown => {\n if (root) {\n return new Proxy({}, {\n get(_target, key) {\n return read(path, true, key);\n },\n });\n }\n return new Proxy(() => undefined, {\n get(_target, key) {\n return read(path, false, key);\n },\n async apply(_target, _this, args: [unknown?, { signal?: AbortSignal }?]) {\n const signal = args[1]?.signal;\n const binding = await runtime.resolve(path);\n if (!binding) {\n throw new Error(`No Capability exists at \"${path.join(\".\")}\"`);\n }\n if (binding.capability.execution === \"events\") {\n throw wrongExecutionMode(binding.capability.id, \"subscribe\");\n }\n const result = await binding.transport.call({\n id: binding.capability.id,\n input: args[0] ?? {},\n ...(signal ? { signal } : {}),\n });\n return result.output;\n },\n });\n };\n\n return proxy([], true) as App<TCapabilities>;\n}\n\nexport function subscribe<\n const TCapability extends SubscribableCapability,\n>(\n capabilityCall: AppCapabilityReference<TCapability>,\n ...args: AppCapabilityArgs<TCapability>\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const binding = getCapabilityBinding(capabilityCall);\n if (!binding) {\n throw new Error(\"subscribe() requires a Capability call from a Capable App\");\n }\n\n return (async function* () {\n const signal = args[1]?.signal;\n const resolved = await binding.runtime.resolve(binding.path);\n if (!resolved) {\n throw new Error(`No Capability exists at \"${binding.path.join(\".\")}\"`);\n }\n if (resolved.capability.execution === \"unary\") {\n throw wrongExecutionMode(resolved.capability.id, \"call\");\n }\n const stream = await resolved.transport.subscribe({\n id: resolved.capability.id,\n input: args[0] ?? {},\n ...(signal ? { signal } : {}),\n });\n yield* mapAsyncIterator(\n stream,\n (result) => result.output as CapabilityOutput<TCapability>,\n );\n })();\n}\n\nexport type AppContextProvider<TContext> = (call: {\n readonly id: string;\n readonly signal?: AbortSignal;\n}) => MaybePromise<TContext>;\n\ntype CreateAppOptions<TContext> = {\n readonly context: AppContextProvider<TContext>;\n};\n\ntype CreateAppArgs<TContext> = [TContext] extends [undefined]\n ? [options?: Partial<CreateAppOptions<TContext>>]\n : [options: CreateAppOptions<TContext>];\n\nconst localManifestCache = new WeakMap<object, ApplicationManifest>();\nconst localCapabilityCache = new WeakMap<\n object,\n ReadonlyMap<string, LocatedCapability>\n>();\n\nexport function createApp<\n const TDefinition extends AppDefinition<any, any>,\n>(\n definition: TDefinition,\n ...[options]: CreateAppArgs<AppContext<TDefinition>>\n): App<DefinitionCapabilities<TDefinition>> {\n let manifest = localManifestCache.get(definition);\n if (!manifest) {\n manifest = createAppManifest(definition);\n localManifestCache.set(definition, manifest);\n }\n let byId = localCapabilityCache.get(definition);\n if (!byId) {\n byId = new Map(\n definition.locatedCapabilities.map((entry) => [entry.capability.id, entry]),\n );\n localCapabilityCache.set(definition, byId);\n }\n const runtime: ApplicationRuntime = Object.freeze({\n async manifest() {\n return manifest;\n },\n async resolve(path: readonly string[]) {\n const capability = findManifestCapability(manifest.capabilities, path);\n return capability ? { capability, transport: runtime } : undefined;\n },\n async call({ id, input = {}, signal, presentation: wantsPresentation }: CapabilityCall) {\n const located = byId.get(id);\n if (!located) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n if (located.capability.execution === \"events\") {\n throw wrongExecutionMode(id, \"subscribe\");\n }\n\n let context: unknown;\n try {\n context = options?.context\n ? await options.context({\n id,\n ...(signal ? { signal } : {}),\n })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n let output: unknown;\n try {\n output = await executeLocatedCapability(located, input, {\n context,\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n if (error instanceof CapableError) {\n throw new TransportError(error.code, {\n ...(error.message ? { message: error.message } : {}),\n ...(typeof error.status === \"number\"\n ? { status: error.status }\n : {}),\n ...(error.data === undefined ? {} : { data: error.data }),\n cause: error,\n });\n }\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n const presentation = await materializePresentation(\n located.capability,\n output,\n context,\n wantsPresentation,\n );\n\n return {\n output,\n ...(presentation ? { presentation } : {}),\n };\n },\n async subscribe({\n id,\n input = {},\n signal,\n presentation: wantsPresentation,\n }: CapabilityCall) {\n const located = byId.get(id);\n if (!located) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n if (!located.capability.subscribe) {\n throw wrongExecutionMode(id, \"call\");\n }\n\n let context: unknown;\n try {\n context = options?.context\n ? await options.context({\n id,\n ...(signal ? { signal } : {}),\n })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n let stream: AsyncIterableIterator<unknown>;\n try {\n stream = await subscribeLocatedCapability(located, input, {\n context,\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n throw toTransportError(error);\n }\n return mapAsyncIterator(\n stream,\n async (output) => {\n const presentation = await materializePresentation(\n located.capability,\n output,\n context,\n wantsPresentation,\n );\n return {\n output,\n ...(presentation ? { presentation } : {}),\n };\n },\n toTransportError,\n );\n },\n });\n return appFromRuntime(runtime);\n}\n\nexport function createRemoteApp<\n TDefinition extends AppDefinition<any, any> = AppDefinition<CapabilityTree>,\n>(\n transport: ApplicationTransport,\n): App<DefinitionCapabilities<TDefinition>> {\n const manifest = cacheAsync(async () => {\n const manifest = await transport.manifest();\n validateManifest(manifest, \"Remote App\");\n return manifest;\n });\n const runtime: ApplicationRuntime = Object.freeze({\n manifest,\n async resolve(path: readonly string[]) {\n const capability = findManifestCapability(\n (await manifest()).capabilities,\n path,\n );\n return capability ? { capability, transport } : undefined;\n },\n async call(call: CapabilityCall) {\n await manifest();\n return transport.call(call);\n },\n async subscribe(call: CapabilityCall) {\n await manifest();\n return transport.subscribe(call);\n },\n });\n return appFromRuntime(runtime);\n}\n\nexport function cacheAsync<T>(\n load: () => Promise<T>,\n): () => Promise<T> {\n let cached: Promise<T> | undefined;\n return () => {\n if (cached) return cached;\n const attempt = Promise.resolve().then(load);\n cached = attempt;\n void attempt.catch(() => {\n if (cached === attempt) cached = undefined;\n });\n return attempt;\n };\n}\n\nexport class TransportError extends Error {\n readonly code: string;\n readonly status: number | undefined;\n readonly data: unknown;\n\n constructor(\n code: string,\n options: {\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n readonly cause?: unknown;\n } = {},\n ) {\n super(options.message ?? code, { cause: options.cause });\n this.name = \"TransportError\";\n this.code = code;\n this.status = options.status;\n this.data = options.data;\n }\n}\n\nasync function materializePresentation(\n capability: AnyCapability,\n output: unknown,\n context: unknown,\n requested: boolean | undefined,\n): Promise<readonly PresentationPart[] | undefined> {\n if (!requested || !capability.toPresentation) return undefined;\n try {\n const presentation = normalizePresentation(\n await capability.toPresentation(output, { context }),\n );\n return presentation.length > 0 ? presentation : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n}\n\nfunction toTransportError(error: unknown): TransportError {\n if (error instanceof TransportError) return error;\n if (error instanceof CapableError) {\n return new TransportError(error.code, {\n ...(error.message ? { message: error.message } : {}),\n ...(typeof error.status === \"number\" ? { status: error.status } : {}),\n ...(error.data === undefined ? {} : { data: error.data }),\n cause: error,\n });\n }\n return new TransportError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n}\n\nfunction wrongExecutionMode(\n id: string,\n supported: \"call\" | \"subscribe\",\n): TransportError {\n return new TransportError(\"METHOD_NOT_ALLOWED\", {\n status: 405,\n message: `Capability \"${id}\" only supports ${supported}`,\n });\n}\n","import type { AnyCapability } from \"@capable/core\";\nimport {\n getCapabilityBinding,\n type AppCapabilityReference,\n} from \"./runtime.ts\";\nimport type { ManifestCapability } from \"./manifest.ts\";\n\n// Global augmentation survives declaration bundling into capable-kit. Module\n// augmentations of private workspace paths do not survive that boundary.\ndeclare global {\n interface CapableCustomizationMeta {}\n}\n\nexport type CapabilityCustomization = {\n readonly title?: string;\n readonly description?: string;\n readonly meta?: keyof CapableCustomizationMeta extends never\n ? never\n : Partial<CapableCustomizationMeta>;\n};\n\nconst CUSTOMIZED_SYMBOL: unique symbol = Symbol.for(\"capable.customized\");\n\nexport type CustomizedCapability<TCapability extends AnyCapability = any> = {\n readonly [CUSTOMIZED_SYMBOL]: true;\n readonly reference: AppCapabilityReference<TCapability>;\n readonly customization: CapabilityCustomization;\n};\n\n/** Customize a bound local or remote reference without changing its execution. */\nexport function customize<TCapability extends AnyCapability>(\n reference:\n | AppCapabilityReference<TCapability>\n | CustomizedCapability<TCapability>,\n options: CapabilityCustomization,\n): CustomizedCapability<TCapability> {\n const previous = isCustomizedCapability(reference) ? reference : undefined;\n const original = (previous ? previous.reference : reference) as\n AppCapabilityReference<TCapability>;\n if (!getCapabilityBinding(original)) {\n throw new TypeError(\"customize() requires a Capability reference from a Capable App\");\n }\n if (!isRecord(options)) throw new TypeError(\"customize() options must be an object\");\n for (const key of Object.keys(options)) {\n if (key !== \"title\" && key !== \"description\" && key !== \"meta\") {\n throw new TypeError(`customize() does not support \"${key}\"`);\n }\n }\n for (const key of [\"title\", \"description\"] as const) {\n if (options[key] !== undefined && typeof options[key] !== \"string\") {\n throw new TypeError(`customize() ${key} must be a string`);\n }\n }\n if (options.meta !== undefined && !isRecord(options.meta)) {\n throw new TypeError(\"customize() meta must be an object\");\n }\n return Object.freeze({\n [CUSTOMIZED_SYMBOL]: true as const,\n reference: original,\n customization: mergeCustomization(previous?.customization, options) as CapabilityCustomization,\n });\n}\n\nexport function isCustomizedCapability(value: unknown): value is CustomizedCapability {\n return isRecord(value) && value[CUSTOMIZED_SYMBOL] === true;\n}\n\ntype ManifestCustomization = NonNullable<ManifestCapability[\"customization\"]>;\n\n/** Outer customizations replace supplied namespaces; no generic deep merge. */\nexport function mergeCustomization(\n source: ManifestCustomization | undefined,\n override: ManifestCustomization,\n): ManifestCustomization {\n return snapshot({\n ...source,\n ...override,\n ...(source?.meta || override.meta\n ? { meta: { ...source?.meta, ...override.meta } }\n : {}),\n }) as ManifestCustomization;\n}\n\n/** Surface-facing fields only. Policies and executors retain the source contract. */\nexport function getCapabilityDisplay(capability: ManifestCapability): {\n readonly title?: string;\n readonly description?: string;\n readonly meta: Readonly<Record<string, unknown>>;\n} {\n const { customization } = capability;\n return {\n ...(capability.title !== undefined ? { title: capability.title } : {}),\n ...(capability.description !== undefined ? { description: capability.description } : {}),\n ...(customization?.title !== undefined ? { title: customization.title } : {}),\n ...(customization?.description !== undefined ? { description: customization.description } : {}),\n meta: { ...capability.meta, ...customization?.meta },\n };\n}\n\n/** Navigation overrides come from the destination only for relocated leaves. */\nexport function getCapabilityNavigationMeta<\n TSurface extends keyof CapableCustomizationMeta,\n>(\n capability: ManifestCapability,\n surface: TSurface,\n): CapableCustomizationMeta[TSurface] | undefined {\n const value = capability.customization?.navigation === \"destination\"\n ? capability.customization.meta?.[surface as string]\n : capability.meta[surface as string];\n return value as CapableCustomizationMeta[TSurface] | undefined;\n}\n\n// Copy and freeze only portable JSON values: callers cannot mutate cached help,\n// and re-exporting a composed manifest cannot silently discard executable values.\nfunction snapshot(value: unknown, ancestors = new Set<unknown>()): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (Array.isArray(value) || isRecord(value)) {\n if (ancestors.has(value)) throw new TypeError(\"customize() metadata must not contain cycles\");\n ancestors.add(value);\n const copy = Array.isArray(value)\n ? value.map((child) => snapshot(child, ancestors))\n : Object.fromEntries(Object.entries(value).filter(([, child]) => child !== undefined)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, child]) => [key, snapshot(child, ancestors)]));\n ancestors.delete(value);\n return Object.freeze(copy);\n }\n throw new TypeError(\"customize() metadata must contain only JSON values\");\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return value !== null && typeof value === \"object\" &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n}\n","import type {\n AnyCapability,\n CapabilityGroupDefinition,\n CapabilityTree,\n} from \"@capable/core\";\nimport {\n appFromRuntime,\n cacheAsync,\n getInternalAppRuntime,\n getCapabilityBinding,\n type AppCapabilityReference,\n isApp,\n TransportError,\n type AnyApp,\n type App,\n type AppCapabilities,\n type ApplicationRuntime,\n type ApplicationTransport,\n type CapabilityCall,\n} from \"./runtime.ts\";\nimport {\n flattenManifestCapabilities,\n composeApplicationManifests,\n findManifestCapability,\n findManifestNode,\n selectManifest,\n type ApplicationManifest,\n type ManifestNode,\n type ManifestCapability,\n type ManifestGroup,\n} from \"./manifest.ts\";\n\nimport {\n isCustomizedCapability,\n mergeCustomization,\n type CapabilityCustomization,\n type CustomizedCapability,\n} from \"./customization.ts\";\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\ntype AppComposition = AnyApp | {\n readonly [key: string]: AppComposition | AppCapabilityReference | CustomizedCapability;\n};\n\ntype ComposedNode<TNode> = TNode extends AnyApp\n ? AppCapabilities<TNode>\n : TNode extends CustomizedCapability<infer TCapability>\n ? TCapability\n : TNode extends AppCapabilityReference<infer TCapability>\n ? TCapability\n : TNode extends Readonly<Record<string, unknown>>\n ? { readonly [TKey in keyof TNode]: ComposedNode<TNode[TKey]> }\n : never;\n\ntype ComposedCapabilities<\n TNodes extends readonly AppComposition[],\n> = UnionToIntersection<ComposedNode<TNodes[number]>> extends\n infer TCapabilities extends CapabilityTree ? TCapabilities : never;\n\n/** Compose executable Apps, subtrees, and Capability references into one tree. */\nexport function composeApps<\n const TNodes extends readonly [\n AppComposition,\n ...AppComposition[],\n ],\n>(\n ...nodes: TNodes\n): App<ComposedCapabilities<TNodes>> {\n const placements = nodes.flatMap((node) => collectPlacements(node, []));\n const uniquePlacements = placements.filter((placement, index) =>\n placements.findIndex((candidate) =>\n candidate.runtime === placement.runtime &&\n samePath(candidate.path, placement.path) &&\n samePath(candidate.sourcePath, placement.sourcePath) &&\n JSON.stringify(candidate.customization) === JSON.stringify(placement.customization)\n ) === index\n );\n return appFromRuntime(\n createCompositionRuntime(uniquePlacements),\n ) as App<ComposedCapabilities<TNodes>>;\n}\n\ntype AppPlacement = {\n readonly path: readonly string[];\n readonly runtime: ApplicationRuntime;\n readonly sourcePath: readonly string[];\n readonly customization?: CapabilityCustomization;\n};\n\nfunction collectPlacements(\n node: AppComposition | AppCapabilityReference | CustomizedCapability,\n path: readonly string[],\n): readonly AppPlacement[] {\n const customized = isCustomizedCapability(node) ? node : undefined;\n const binding = getCapabilityBinding(customized ? customized.reference : node);\n if (binding) {\n return [{\n path: Object.freeze(path),\n runtime: binding.runtime,\n sourcePath: Object.freeze(binding.path),\n ...(customized ? { customization: customized.customization } : {}),\n }];\n }\n if (isApp(node)) {\n return [{\n path: Object.freeze(path),\n runtime: getInternalAppRuntime(node),\n sourcePath: Object.freeze([]),\n }];\n }\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n throw new TypeError(\n \"composeApps() entries must be Apps, executable subtree references, Capability references, or named object trees\",\n );\n }\n const entries = Object.entries(node);\n if (entries.length === 0) {\n throw new Error(\n `composeApps() contains an empty object at \"${path.join(\".\") || \"<root>\"}\"`,\n );\n }\n return entries.flatMap(([key, child]) => {\n if (!key) throw new Error(\"composeApps() keys must not be empty\");\n if (key === \"then\") {\n throw new Error('composeApps() uses reserved key \"then\"');\n }\n return collectPlacements(child, [...path, key]);\n });\n}\n\nfunction createCompositionRuntime(\n placements: readonly AppPlacement[],\n): ApplicationRuntime {\n return derivedRuntime(async () => {\n const sources = await Promise.all(placements.map(resolvePlacement));\n const manifest = composeApplicationManifests(sources);\n const dispatch = new Map<string, ApplicationTransport>();\n for (const { owners } of sources) {\n for (const [id, target] of owners) {\n dispatch.set(id, target);\n }\n }\n return { manifest, dispatch };\n }, async (path) => {\n const matches = (await Promise.all(\n placements\n .filter((placement) => isPathPrefixOrEqual(placement.path, path))\n .map(async (placement) => {\n const resolved = await placement.runtime.resolve(\n [\n ...placement.sourcePath,\n ...path.slice(placement.path.length),\n ],\n );\n if (!resolved) return undefined;\n const relocatedLeaf = samePath(placement.path, path);\n if (placement.customization && !relocatedLeaf) {\n throw new TypeError(\n \"customize() requires a Capability reference, not an App subtree\",\n );\n }\n return {\n transport: resolved.transport,\n capability: placeCapability(resolved.capability, {\n path,\n relocatedLeaf,\n ...(relocatedLeaf && placement.customization\n ? { customization: placement.customization }\n : {}),\n }),\n };\n }),\n )).filter((match) => match !== undefined).filter((match, index, all) =>\n all.findIndex((candidate) =>\n candidate.capability.id === match.capability.id &&\n candidate.transport === match.transport &&\n JSON.stringify(candidate.capability.customization) === JSON.stringify(match.capability.customization)\n ) === index\n );\n if (matches.length > 1) throw new Error(`Cannot resolve ambiguous App path \"${path.join(\".\")}\"`);\n return matches[0];\n });\n}\n\nasync function resolvePlacement(placement: AppPlacement): Promise<{\n readonly manifest: ApplicationManifest;\n readonly application: object;\n readonly owners: ReadonlyMap<string, ApplicationTransport>;\n}> {\n const source = await placement.runtime.manifest();\n const placed = placeSourceManifest(source, placement);\n const targets = new Map<string, ApplicationTransport>();\n for (const capability of placed.sourceCapabilities) {\n const resolved = await placement.runtime.resolve(capability.path);\n if (!resolved) throw missingReference(capability.path);\n const previous = targets.get(capability.id);\n if (previous && previous !== resolved.transport) {\n throw new Error(\n `Capability id \"${capability.id}\" has multiple execution owners in \"${source.name}\"`,\n );\n }\n targets.set(capability.id, resolved.transport);\n }\n return {\n manifest: placed.manifest,\n application: placement.runtime,\n owners: targets,\n };\n}\n\nfunction placeSourceManifest(\n source: ApplicationManifest,\n placement: AppPlacement,\n): {\n readonly manifest: ApplicationManifest;\n readonly sourceCapabilities: readonly ManifestCapability[];\n} {\n if (placement.sourcePath.length === 0) {\n return {\n manifest: placeManifest(placement.path, source),\n sourceCapabilities: flattenManifestCapabilities(source.capabilities),\n };\n }\n\n const node = findManifestNode(source.capabilities, placement.sourcePath);\n if (!node) throw missingReference(placement.sourcePath);\n if (node.type === \"capability\") {\n if (placement.path.length === 0) {\n throw new TypeError(\"Capability references require a named key in composeApps()\");\n }\n return {\n manifest: Object.freeze({\n ...source,\n capabilities: wrapGroups(\n Object.freeze([placeCapability(node, {\n path: placement.path,\n relocatedLeaf: true,\n ...(placement.customization\n ? { customization: placement.customization }\n : {}),\n })]),\n placement.path.slice(0, -1),\n ),\n }),\n sourceCapabilities: Object.freeze([node]),\n };\n }\n\n if (placement.customization) {\n throw new TypeError(\"customize() requires a Capability reference, not an App subtree\");\n }\n return {\n manifest: Object.freeze({\n ...source,\n capabilities: placeGroup(node, placement.sourcePath, placement.path),\n }),\n sourceCapabilities: flattenManifestCapabilities(node.children),\n };\n}\n\nfunction placeGroup(\n group: ManifestGroup,\n sourcePath: readonly string[],\n path: readonly string[],\n): readonly ManifestNode[] {\n if (path.length === 0) {\n return rebaseManifestPaths(group.children, sourcePath, []);\n }\n const placed = Object.freeze({\n ...group,\n key: path.at(-1)!,\n // The placed node is named by its destination key. Nested Groups retain\n // their authored presentation and navigation metadata.\n meta: Object.freeze({}),\n children: rebaseManifestPaths(group.children, sourcePath, path),\n });\n return wrapGroups(Object.freeze([placed]), path.slice(0, -1));\n}\n\nfunction placeCapability(\n capability: ManifestCapability,\n placement: {\n readonly path: readonly string[];\n readonly relocatedLeaf: boolean;\n readonly customization?: CapabilityCustomization;\n },\n): ManifestCapability {\n return Object.freeze({\n ...capability,\n path: placement.path,\n ...(placement.relocatedLeaf\n ? {\n customization: mergeCustomization(capability.customization, {\n ...placement.customization,\n navigation: \"destination\",\n }),\n }\n : {}),\n });\n}\n\nfunction missingReference(path: readonly string[]): Error {\n return new Error(`No executable App node exists at \"${path.join(\".\")}\"`);\n}\n\n/** One cached manifest/dispatch snapshot for both composition and selection. */\nfunction derivedRuntime(\n load: () => Promise<{\n readonly manifest: ApplicationManifest;\n readonly dispatch: ReadonlyMap<string, ApplicationTransport>;\n }>,\n resolve: ApplicationRuntime[\"resolve\"],\n): ApplicationRuntime {\n const snapshot = cacheAsync(load);\n const target = async (id: string) => {\n const runtime = (await snapshot()).dispatch.get(id);\n if (!runtime) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n return runtime;\n };\n return Object.freeze({\n manifest: async () => (await snapshot()).manifest,\n resolve,\n async call(call: CapabilityCall) {\n return (await target(call.id)).call(call);\n },\n async subscribe(call: CapabilityCall) {\n return (await target(call.id)).subscribe(call);\n },\n });\n}\n\ntype SelectionNode<TTree> =\n TTree extends AnyCapability\n ? true\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? true | SelectionNode<TCapabilities>\n : TTree extends CapabilityTree\n ? true | {\n readonly [TKey in keyof TTree]?: SelectionNode<TTree[TKey]>;\n }\n : never;\n\nexport type ApplicationSelection<\n TCapabilities extends CapabilityTree = CapabilityTree,\n> = {\n readonly include?: Exclude<SelectionNode<TCapabilities>, true>;\n readonly exclude?: Exclude<SelectionNode<TCapabilities>, true>;\n};\n\nexport function selectApp<\n const TCapabilities extends CapabilityTree,\n>(\n application: App<TCapabilities>,\n selection: ApplicationSelection<TCapabilities>,\n): App<TCapabilities> {\n const runtime = getInternalAppRuntime(application);\n const manifest = cacheAsync(async () => selectManifest(await runtime.manifest(), selection));\n return appFromRuntime(derivedRuntime(async () => {\n const selected = await manifest();\n return {\n manifest: selected,\n dispatch: new Map(flattenManifestCapabilities(selected.capabilities)\n .map((capability) => [capability.id, runtime])),\n };\n }, async (path) => {\n if (!findManifestCapability((await manifest()).capabilities, path)) return undefined;\n return runtime.resolve(path);\n }));\n}\n\nfunction placeManifest(\n path: readonly string[],\n source: ApplicationManifest,\n): ApplicationManifest {\n if (path.length === 0) return source;\n return Object.freeze({\n ...source,\n capabilities: wrapGroups(\n rebaseManifestPaths(source.capabilities, [], path),\n path,\n source,\n ),\n });\n}\n\nfunction wrapGroups(\n nodes: readonly ManifestNode[],\n path: readonly string[],\n source?: ApplicationManifest,\n): readonly ManifestNode[] {\n let capabilities = nodes;\n for (let index = path.length - 1; index >= 0; index--) {\n const leaf = index === path.length - 1;\n capabilities = Object.freeze([Object.freeze({\n type: \"group\" as const,\n key: path[index]!,\n ...(leaf && source ? { title: source.name } : {}),\n ...(leaf && source?.description ? { description: source.description } : {}),\n meta: Object.freeze({}),\n children: capabilities,\n })]);\n }\n return capabilities;\n}\n\nfunction rebaseManifestPaths(\n nodes: readonly ManifestNode[],\n sourcePath: readonly string[],\n destinationPath: readonly string[],\n): readonly ManifestNode[] {\n return Object.freeze(nodes.map((node) =>\n node.type === \"capability\"\n ? Object.freeze({\n ...node,\n path: Object.freeze([\n ...destinationPath,\n ...node.path.slice(sourcePath.length),\n ]),\n })\n : Object.freeze({\n ...node,\n children: rebaseManifestPaths(\n node.children,\n sourcePath,\n destinationPath,\n ),\n })\n ));\n}\n\nfunction isPathPrefixOrEqual(\n prefix: readonly string[],\n path: readonly string[],\n): boolean {\n return prefix.length <= path.length &&\n prefix.every((segment, index) => segment === path[index]);\n}\n\nfunction samePath(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length &&\n left.every((segment, index) => segment === right[index]);\n}\n"],"mappings":";;AA4DA,SAAgB,kBACd,YACqB;CACrB,MAAM,eAAe,IAAI,IACvB,WAAW,oBAAoB,KAAK,UAAU,CAAC,MAAM,YAAY,KAAK,CAAC,CACzE;CACA,OAAO,OAAO,OAAO;EACnB,UAAU;EACV,MAAM,WAAW;EACjB,SAAS,WAAW;EACpB,GAAI,WAAW,cA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AAW,GAAG,OAAO;CAC9B,OAAO,OAAO,OAAO;EACnB,GAAG;EACH,cAAc,WACZ,oBAAoB,OAAO,cAAc,CAAC,GAAG,IAAI,GACjD,MACA,MACF;CACF,CAAC;AACH;AAEA,SAAS,WACP,OACA,MACA,QACyB;CACzB,IAAI,eAAe;CACnB,KAAK,IAAI,QAAQ,KAAK,SAAS,GAAG,SAAS,GAAG,SAAS;EACrD,MAAM,OAAO,UAAU,KAAK,SAAS;EACrC,eAAe,OAAO,OAAO,CAAC,OAAO,OAAO;GAC1C,MAAM;GACN,KAAK,KAAK;GACV,GAAI,QAAQ,SAAS,EAAE,OAAO,OAAO,KAAK,IAAI,CAAC;GAC/C,GAAI,QAAQ,QAAQ,cAAc,EAAE,aAAa,OAAO,YAAY,IAAI,CAAC;GACzE,MAAM,OAAO,OAAO,CAAC,CAAC;GACtB,UAAU;EACZ,CAAC,CAAC,CAAC;CACL;CACA,OAAO;AACT;AAEA,SAAS,oBACP,OACA,YACA,iBACyB;CACzB,OAAO,OAAO,OAAO,MAAM,KAAK,SAC9B,KAAK,SAAS,eACV,OAAO,OAAO;EACZ,GAAG;EACH,MAAM,OAAO,OAAO,CAClB,GAAG,iBACH,GAAG,KAAK,KAAK,MAAM,WAAW,MAAM,CACtC,CAAC;CACH,CAAC,IACD,OAAO,OAAO;EACZ,GAAG;EACH,UAAU,oBACR,KAAK,UACL,YACA,eACF;CACF,CAAC,CACP,CAAC;AACH;AAEA,SAAS,oBACP,QACA,MACS;CACT,OAAO,OAAO,UAAU,KAAK,UAC3B,OAAO,OAAO,SAAS,UAAU,YAAY,KAAK,MAAM;AAC5D;AAEA,SAAS,SAAS,MAAyB,OAAmC;CAC5E,OAAO,KAAK,WAAW,MAAM,UAC3B,KAAK,OAAO,SAAS,UAAU,YAAY,MAAM,MAAM;AAC3D"}
@@ -1,5 +1,5 @@
1
- import { _ as normalizePresentation, h as schemaToJsonSchema, l as executeLocatedCapability, x as CapableError, y as renderPresentationMarkdown } from "./src-D-cm2gQ6.mjs";
2
- import { a as TransportError, c as getAppRuntime, l as isApp } from "./src-betOfnDL.mjs";
1
+ import { _ as normalizePresentation, h as schemaToJsonSchema, l as executeLocatedCapability, x as CapableError, y as renderPresentationMarkdown } from "./src-B2WeUwUT.mjs";
2
+ import { c as TransportError, d as getAppRuntime, f as isApp, h as flattenManifestCapabilities } from "./src-DePlcG_t.mjs";
3
3
  import SuperJSON from "superjson";
4
4
  //#region packages/fetch/src/error-response.ts
5
5
  function capabilityErrorData(error, fallbackStatus = 500) {
@@ -55,13 +55,15 @@ function createProtocolHandler(application, options = {}) {
55
55
  let stream;
56
56
  try {
57
57
  const body = await protocolRequestJson(request, codec);
58
- stream = runtime.subscribe({
58
+ const execution = flattenManifestCapabilities((await runtime.manifest()).capabilities).find((candidate) => candidate.id === id)?.execution;
59
+ stream = await runtime.subscribe({
59
60
  id,
60
61
  input: body.input ?? {},
61
62
  ...body.presentation ? { presentation: true } : {},
62
63
  signal: AbortSignal.any([request.signal, controller.signal])
63
64
  });
64
- const first = await stream.next();
65
+ let first;
66
+ if (execution === "live") first = await stream.next();
65
67
  return subscriptionResponse(stream, first, controller, codec);
66
68
  } catch (error) {
67
69
  controller.abort();
@@ -176,7 +178,7 @@ function createHttpTransport(options) {
176
178
  ...body.presentation ? { presentation: body.presentation } : {}
177
179
  };
178
180
  },
179
- async *subscribe({ id, input = {}, signal, presentation }) {
181
+ async subscribe({ id, input = {}, signal, presentation }) {
180
182
  const response = await request(`subscribe/${encodeURIComponent(id)}`, {
181
183
  method: "POST",
182
184
  headers: {
@@ -192,18 +194,23 @@ function createHttpTransport(options) {
192
194
  });
193
195
  if (!response.ok) throw await responseError(response, codec);
194
196
  assertResponseCodec(response, codec);
195
- yield* decodeEventStream(response, codec);
197
+ return decodeEventStream(response, codec);
196
198
  }
197
199
  });
198
200
  }
199
201
  function subscriptionResponse(stream, first, subscriptionController, codec) {
200
202
  const encoder = new TextEncoder();
201
203
  let initial = first;
204
+ let cancelled = false;
202
205
  return new Response(new ReadableStream({
206
+ start(controller) {
207
+ if (!first) controller.enqueue(encoder.encode(": capable\n\n"));
208
+ },
203
209
  async pull(controller) {
204
210
  try {
205
211
  const result = initial ?? await stream.next();
206
212
  initial = void 0;
213
+ if (cancelled) return;
207
214
  if (result.done) {
208
215
  subscriptionController.abort();
209
216
  controller.close();
@@ -211,6 +218,7 @@ function subscriptionResponse(stream, first, subscriptionController, codec) {
211
218
  }
212
219
  controller.enqueue(encoder.encode(sseFrame("output", result.value, codec)));
213
220
  } catch (error) {
221
+ if (cancelled) return;
214
222
  subscriptionController.abort();
215
223
  controller.enqueue(encoder.encode(sseFrame("error", capabilityErrorData(error), codec)));
216
224
  controller.close();
@@ -218,6 +226,7 @@ function subscriptionResponse(stream, first, subscriptionController, codec) {
218
226
  }
219
227
  },
220
228
  async cancel() {
229
+ cancelled = true;
221
230
  subscriptionController.abort();
222
231
  await stream.return?.();
223
232
  }
@@ -227,7 +236,7 @@ function subscriptionResponse(stream, first, subscriptionController, codec) {
227
236
  "content-type": "text/event-stream; charset=utf-8"
228
237
  } });
229
238
  }
230
- async function* decodeEventStream(response, codec) {
239
+ function decodeEventStream(response, codec) {
231
240
  if (!response.headers.get("content-type")?.includes("text/event-stream")) throw new TransportError("TRANSPORT_ERROR", {
232
241
  status: response.status,
233
242
  message: "Subscription response is not an event stream"
@@ -236,7 +245,10 @@ async function* decodeEventStream(response, codec) {
236
245
  status: response.status,
237
246
  message: "Subscription response has no body"
238
247
  });
239
- const reader = response.body.getReader();
248
+ return decodeEventStreamBody(response.body, codec);
249
+ }
250
+ async function* decodeEventStreamBody(body, codec) {
251
+ const reader = body.getReader();
240
252
  const decoder = new TextDecoder();
241
253
  let buffer = "";
242
254
  try {
@@ -398,7 +410,13 @@ function normalizePath$1(value) {
398
410
  //#region packages/fetch/src/http.ts
399
411
  function createHttpHandler(app, options = {}) {
400
412
  const basePath = normalizePath(options.basePath ?? "/api");
401
- const selected = selectCapabilities(app.locatedCapabilities, options.selection).filter((entry) => capabilityHttp(entry) !== false);
413
+ const selected = selectCapabilities(app.locatedCapabilities, options.selection).filter((entry) => {
414
+ const meta = capabilityHttp(entry);
415
+ if (meta === false) return false;
416
+ if (entry.capability.execution !== "events") return true;
417
+ if (meta !== void 0) throw new Error(`Event Capability "${entry.capability.id}" cannot be exposed as a unary HTTP route`);
418
+ return false;
419
+ });
402
420
  const routes = selected.map((entry) => compileHttpRoute(entry, basePath));
403
421
  assertUniqueRoutes(routes);
404
422
  if (options.requireExplicitRoutes) {
@@ -594,4 +612,4 @@ function joinPath(...parts) {
594
612
  //#endregion
595
613
  export { defineProtocolCodec as i, createHttpTransport as n, createProtocolHandler as r, createHttpHandler as t };
596
614
 
597
- //# sourceMappingURL=src-rkr5j_NH.mjs.map
615
+ //# sourceMappingURL=src-_6OmFRYa.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-_6OmFRYa.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/codec.ts","../../fetch/src/capable.ts","../../fetch/src/http.ts"],"sourcesContent":["import { CapableError } from \"@capable/core\";\nimport { TransportError } from \"@capable/app\";\n\nexport type CapabilityErrorData = {\n readonly code: string;\n readonly message: string;\n readonly status: number;\n readonly data?: unknown;\n};\n\nexport function capabilityErrorData(\n error: unknown,\n fallbackStatus = 500,\n): CapabilityErrorData {\n const capable = error instanceof CapableError || error instanceof TransportError\n ? error\n : new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n return {\n code: capable.code,\n message: capable.message,\n status: capable.status ?? fallbackStatus,\n ...(capable.data === undefined ? {} : { data: capable.data }),\n };\n}\n\nexport function capabilityErrorResponse(\n error: unknown,\n fallbackStatus = 500,\n): Response {\n const data = capabilityErrorData(error, fallbackStatus);\n return Response.json({\n ok: false,\n error: data,\n }, { status: data.status });\n}\n","import SuperJSON, {\n type SuperJSONResult,\n type SuperJSONValue,\n} from \"superjson\";\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport type ProtocolCodec = {\n /** Stable identity used to reject mismatched protocol peers. */\n readonly id: string;\n /** Converts a runtime value into JSON-compatible protocol data. */\n encode(value: unknown): JsonValue;\n /** Restores a runtime value from JSON-compatible protocol data. */\n decode(value: JsonValue): unknown;\n};\n\nexport function defineProtocolCodec(\n codec: ProtocolCodec,\n): ProtocolCodec {\n if (!codec.id.trim()) throw new Error(\"Protocol codec id must not be empty\");\n return Object.freeze({\n id: codec.id,\n encode: codec.encode,\n decode: codec.decode,\n });\n}\n\nconst richJson = new SuperJSON();\n\nexport const capableRichJsonCodec: ProtocolCodec = defineProtocolCodec({\n id: \"capable.rich-json.v1\",\n encode(value) {\n return richJson.serialize(value as SuperJSONValue) as unknown as JsonValue;\n },\n decode(value) {\n return richJson.deserialize(value as unknown as SuperJSONResult);\n },\n});\n","import {\n getAppRuntime,\n isApp,\n TransportError,\n flattenManifestCapabilities,\n type ApplicationManifest,\n type ApplicationTransport,\n type AnyApp,\n type CapabilityCall,\n type CapabilityResult,\n} from \"@capable/app\";\nimport type { PresentationPart } from \"@capable/core\";\nimport { capabilityErrorData } from \"./error-response.ts\";\nimport {\n capableRichJsonCodec,\n type JsonValue,\n type ProtocolCodec,\n} from \"./codec.ts\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nconst PROTOCOL_CODEC_HEADER = \"capable-codec\";\n\nexport function createProtocolHandler(\n application:\n | AnyApp\n | ((request: Request) => AnyApp | Promise<AnyApp>),\n options: {\n readonly basePath?: string;\n readonly codec?: ProtocolCodec;\n } = {},\n): {\n readonly fetch: FetchHandler;\n} {\n const basePath = normalizePath(options.basePath ?? \"/~capable\");\n const codec = options.codec ?? capableRichJsonCodec;\n\n const fetch: FetchHandler = async (request) => {\n const url = new URL(request.url);\n const app = isApp(application)\n ? application\n : await application(request);\n const runtime = getAppRuntime(app);\n if (url.pathname === `${basePath}/manifest` && request.method === \"GET\") {\n return Response.json(await runtime.manifest(), {\n headers: { [PROTOCOL_CODEC_HEADER]: codec.id },\n });\n }\n const subscribePrefix = `${basePath}/subscribe/`;\n if (\n url.pathname.startsWith(subscribePrefix) &&\n request.method === \"POST\"\n ) {\n const id = decodeURIComponent(\n url.pathname.slice(subscribePrefix.length),\n );\n const controller = new AbortController();\n let stream: AsyncIterableIterator<CapabilityResult> | undefined;\n try {\n const body = await protocolRequestJson(request, codec) as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n const execution = flattenManifestCapabilities(\n (await runtime.manifest()).capabilities,\n ).find((candidate) => candidate.id === id)?.execution;\n stream = await runtime.subscribe({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n let first: IteratorResult<CapabilityResult> | undefined;\n if (execution === \"live\") {\n first = await stream.next();\n }\n return subscriptionResponse(stream, first, controller, codec);\n } catch (error) {\n controller.abort();\n await stream?.return?.().catch(() => undefined);\n return protocolErrorResponse(error, codec);\n }\n }\n const callPrefix = `${basePath}/call/`;\n if (!url.pathname.startsWith(callPrefix) || request.method !== \"POST\") {\n return new Response(\"Not Found\", { status: 404 });\n }\n const id = decodeURIComponent(url.pathname.slice(callPrefix.length));\n try {\n const body = await protocolRequestJson(request, codec) as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n const result = await runtime.call({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: request.signal,\n });\n return protocolResponse(codec, {\n ok: true,\n ...result,\n });\n } catch (error) {\n return protocolErrorResponse(error, codec);\n }\n };\n\n return { fetch };\n}\n\nasync function protocolRequestJson(\n request: Request,\n codec: ProtocolCodec,\n): Promise<Record<string, unknown>> {\n const received = request.headers.get(PROTOCOL_CODEC_HEADER);\n if (received !== codec.id) {\n throw new TransportError(\"UNSUPPORTED_CODEC\", {\n status: 415,\n message:\n `Protocol codec mismatch: expected \"${codec.id}\", received \"${received ?? \"none\"}\"`,\n data: { expected: codec.id, received },\n });\n }\n let decoded: unknown;\n try {\n decoded = codec.decode(await request.json() as JsonValue);\n } catch (cause) {\n throw new TransportError(\"BAD_REQUEST\", {\n status: 400,\n message: \"Protocol request could not be decoded\",\n cause,\n });\n }\n if (!decoded || typeof decoded !== \"object\" || Array.isArray(decoded)) {\n throw new TransportError(\"BAD_REQUEST\", {\n status: 400,\n message: \"Protocol request must decode to an object\",\n });\n }\n return decoded as Record<string, unknown>;\n}\n\nfunction protocolResponse(\n codec: ProtocolCodec,\n value: unknown,\n init: ResponseInit = {},\n): Response {\n const headers = new Headers(init.headers);\n headers.set(PROTOCOL_CODEC_HEADER, codec.id);\n return Response.json(codec.encode(value), { ...init, headers });\n}\n\nfunction protocolErrorResponse(\n error: unknown,\n codec: ProtocolCodec,\n): Response {\n const data = capabilityErrorData(error);\n return protocolResponse(codec, {\n ok: false,\n error: data,\n }, { status: data.status });\n}\n\nexport type TransportHeaders =\n | HeadersInit\n | (() => HeadersInit | Promise<HeadersInit>);\n\nexport function createHttpTransport(options: {\n readonly url: string | URL | (() => string | URL);\n readonly fetch?: (request: Request) => Response | Promise<Response>;\n readonly headers?: TransportHeaders;\n readonly codec?: ProtocolCodec;\n}): ApplicationTransport {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n const codec = options.codec ?? capableRichJsonCodec;\n\n async function request(\n path: string,\n init: RequestInit,\n ): Promise<Response> {\n const base = normalizeUrl(\n typeof options.url === \"function\" ? options.url() : options.url,\n );\n const configured = typeof options.headers === \"function\"\n ? await options.headers()\n : options.headers;\n const headers = new Headers(configured);\n new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n return fetchImplementation(\n new Request(new URL(path, base), { ...init, headers }),\n );\n }\n\n return Object.freeze({\n async manifest(\n { signal }: { readonly signal?: AbortSignal } = {},\n ) {\n const response = await request(\"manifest\", {\n method: \"GET\",\n headers: { [PROTOCOL_CODEC_HEADER]: codec.id },\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n if (response.headers.get(\"content-type\")?.includes(\"json\")) {\n assertResponseCodec(response, codec);\n }\n return await responseJson<ApplicationManifest>(\n response,\n \"Application manifest\",\n );\n },\n async call({\n id,\n input = {},\n signal,\n presentation,\n }: CapabilityCall) {\n const response = await request(`call/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n [PROTOCOL_CODEC_HEADER]: codec.id,\n },\n body: JSON.stringify(codec.encode({\n input,\n ...(presentation ? { presentation } : {}),\n })),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response, codec);\n const body = await protocolResponseJson<\n | {\n readonly ok: true;\n readonly output: unknown;\n readonly presentation?: readonly PresentationPart[];\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n }\n >(response, codec, \"Capability call\");\n if (!body.ok) {\n throw new TransportError(body.error.code, body.error);\n }\n return {\n output: body.output,\n ...(body.presentation ? { presentation: body.presentation } : {}),\n };\n },\n async subscribe({\n id,\n input = {},\n signal,\n presentation,\n }: CapabilityCall) {\n const response = await request(`subscribe/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n [PROTOCOL_CODEC_HEADER]: codec.id,\n },\n body: JSON.stringify(codec.encode({\n input,\n ...(presentation ? { presentation } : {}),\n })),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response, codec);\n assertResponseCodec(response, codec);\n return decodeEventStream(response, codec);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult> | undefined,\n subscriptionController: AbortController,\n codec: ProtocolCodec,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n let cancelled = false;\n\n return new Response(new ReadableStream({\n start(controller) {\n // Flush headers through HTTP hosts without manufacturing a canonical event.\n if (!first) controller.enqueue(encoder.encode(\": capable\\n\\n\"));\n },\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\n if (cancelled) return;\n if (result.done) {\n subscriptionController.abort();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(\n sseFrame(\"output\", result.value, codec),\n ));\n } catch (error) {\n if (cancelled) return;\n subscriptionController.abort();\n controller.enqueue(encoder.encode(\n sseFrame(\"error\", capabilityErrorData(error), codec),\n ));\n controller.close();\n await stream.return?.();\n }\n },\n async cancel() {\n cancelled = true;\n subscriptionController.abort();\n await stream.return?.();\n },\n }, {\n highWaterMark: 0,\n }), {\n headers: {\n \"cache-control\": \"no-cache\",\n [PROTOCOL_CODEC_HEADER]: codec.id,\n \"content-type\": \"text/event-stream; charset=utf-8\",\n },\n });\n}\n\nfunction decodeEventStream(\n response: Response,\n codec: ProtocolCodec,\n): AsyncIterableIterator<CapabilityResult> {\n if (!response.headers.get(\"content-type\")?.includes(\"text/event-stream\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response is not an event stream\",\n });\n }\n if (!response.body) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response has no body\",\n });\n }\n\n return decodeEventStreamBody(response.body, codec);\n}\n\nasync function* decodeEventStreamBody(\n body: ReadableStream<Uint8Array>,\n codec: ProtocolCodec,\n): AsyncIterableIterator<CapabilityResult> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done });\n let boundary = eventBoundary(buffer);\n while (boundary) {\n const block = buffer.slice(0, boundary.index);\n buffer = buffer.slice(boundary.index + boundary.length);\n const event = parseEventBlock(block, codec);\n if (event) {\n if (event.type === \"error\") {\n throw new TransportError(event.error.code, event.error);\n }\n yield event.result;\n }\n boundary = eventBoundary(buffer);\n }\n if (done) break;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n}\n\nfunction eventBoundary(\n value: string,\n): { readonly index: number; readonly length: number } | undefined {\n const lf = value.indexOf(\"\\n\\n\");\n const crlf = value.indexOf(\"\\r\\n\\r\\n\");\n if (lf < 0 && crlf < 0) {\n return undefined;\n }\n if (crlf >= 0 && (lf < 0 || crlf < lf)) {\n return { index: crlf, length: 4 };\n }\n return { index: lf, length: 2 };\n}\n\nfunction parseEventBlock(block: string, codec: ProtocolCodec):\n | { readonly type: \"output\"; readonly result: CapabilityResult }\n | {\n readonly type: \"error\";\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n }\n | undefined {\n let type = \"message\";\n const data: string[] = [];\n for (const line of block.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) type = line.slice(6).trim();\n if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (!data.length) return undefined;\n let value: any;\n try {\n value = codec.decode(JSON.parse(data.join(\"\\n\")) as JsonValue);\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n message: \"Subscription event could not be decoded\",\n cause,\n });\n }\n return type === \"error\"\n ? { type: \"error\", error: value }\n : { type: \"output\", result: value };\n}\n\nfunction sseFrame(\n event: string,\n data: unknown,\n codec: ProtocolCodec,\n): string {\n return `event: ${event}\\ndata: ${JSON.stringify(codec.encode(data))}\\n\\n`;\n}\n\nfunction normalizeUrl(value: string | URL): URL {\n let url: URL;\n try {\n url = typeof window === \"undefined\"\n ? new URL(value)\n : new URL(value, window.location.origin);\n } catch (cause) {\n throw new TypeError(\n \"Capable transport URLs must be absolute when no browser origin is \" +\n \"available. Pass an absolute URL or return one from the `url` function.\",\n { cause },\n );\n }\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\nfunction assertResponseCodec(\n response: Response,\n codec: ProtocolCodec,\n): void {\n const received = response.headers.get(PROTOCOL_CODEC_HEADER);\n if (received === codec.id) return;\n throw new TransportError(\"UNSUPPORTED_CODEC\", {\n status: response.status,\n message:\n `Protocol codec mismatch: expected \"${codec.id}\", received \"${received ?? \"none\"}\"`,\n data: { expected: codec.id, received },\n });\n}\n\nasync function protocolResponseJson<T>(\n response: Response,\n codec: ProtocolCodec,\n label: string,\n): Promise<T> {\n assertResponseCodec(response, codec);\n const encoded = await responseJson<JsonValue>(response, label);\n try {\n return codec.decode(encoded) as T;\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `${label} response could not be decoded`,\n cause,\n });\n }\n}\n\nasync function responseError(\n response: Response,\n codec?: ProtocolCodec,\n): Promise<TransportError> {\n if (codec) {\n try {\n assertResponseCodec(response, codec);\n } catch (error) {\n return error as TransportError;\n }\n }\n const text = await response.text().catch(() => \"\");\n let data: unknown = text;\n let parsed = false;\n try {\n data = JSON.parse(text);\n parsed = true;\n } catch {\n // Preserve the response text as transport diagnostics.\n }\n if (codec && parsed) {\n try {\n data = codec.decode(data as JsonValue);\n } catch (cause) {\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Transport error response could not be decoded\",\n cause,\n });\n }\n }\n if (\n data &&\n typeof data === \"object\" &&\n \"ok\" in data &&\n data.ok === false &&\n \"error\" in data &&\n data.error &&\n typeof data.error === \"object\" &&\n \"code\" in data.error &&\n typeof data.error.code === \"string\"\n ) {\n const error = data.error as {\n readonly code: string;\n readonly message?: unknown;\n readonly status?: unknown;\n readonly data?: unknown;\n };\n return new TransportError(error.code, {\n ...(typeof error.message === \"string\"\n ? { message: error.message }\n : {}),\n status: typeof error.status === \"number\"\n ? error.status\n : response.status,\n ...(\"data\" in error ? { data: error.data } : {}),\n });\n }\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `Transport request failed with ${response.status}`,\n data,\n });\n}\n\nasync function responseJson<T>(\n response: Response,\n label: string,\n): Promise<T> {\n const contentType = response.headers.get(\"content-type\");\n if (!contentType?.toLowerCase().includes(\"json\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message:\n `${label} request returned ${contentType ?? \"a non-JSON response\"}${\n response.url ? ` from ${response.url}` : \"\"\n }`,\n });\n }\n try {\n return await response.json() as T;\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `${label} response contained invalid JSON`,\n cause,\n });\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n","import {\n executeLocatedCapability,\n normalizePresentation,\n renderPresentationMarkdown,\n schemaToJsonSchema,\n type AppDefinition,\n type GroupMetaRegistry,\n type LocatedCapability,\n type CapabilityMetaRegistry,\n type CapabilityTree,\n} from \"@capable/core\";\nimport type { ApplicationSelection, JsonSchema } from \"@capable/app\";\nimport {\n capabilityErrorResponse,\n} from \"./error-response.ts\";\nimport type { FetchHandler } from \"./capable.ts\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type HttpCapabilityMeta =\n | false\n | {\n readonly method?: HttpMethod;\n readonly route?: string;\n readonly status?: number;\n };\n\nexport type HttpGroupMeta = {\n readonly prefix?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly http?: HttpCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly http?: HttpGroupMeta;\n }\n}\n\nexport type ContextProvider<TContext> = (args: {\n readonly request: Request;\n}) => TContext | Promise<TContext>;\n\nexport type CapabilitySelection<\n TTree extends CapabilityTree = CapabilityTree,\n> = ApplicationSelection<TTree>;\n\nexport type CompiledHttpRoute = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly capability: LocatedCapability;\n};\n\nexport function createHttpHandler<\n const TCapabilities extends CapabilityTree,\n TContext,\n>(\n app: AppDefinition<TCapabilities, TContext>,\n options: {\n readonly context?: ContextProvider<TContext>;\n readonly basePath?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection<TCapabilities>;\n } = {},\n): {\n readonly fetch: FetchHandler;\n readonly routes: readonly CompiledHttpRoute[];\n readonly openapi: Readonly<Record<string, unknown>>;\n} {\n const basePath = normalizePath(options.basePath ?? \"/api\");\n const selected = selectCapabilities(app.locatedCapabilities, options.selection)\n .filter((entry) => {\n const meta = capabilityHttp(entry);\n if (meta === false) return false;\n if (entry.capability.execution !== \"events\") return true;\n if (meta !== undefined) {\n throw new Error(\n `Event Capability \"${entry.capability.id}\" cannot be exposed as a unary HTTP route`,\n );\n }\n return false;\n });\n const routes = selected.map((entry) => compileHttpRoute(entry, basePath));\n assertUniqueRoutes(routes);\n if (options.requireExplicitRoutes) {\n const implicit = selected.find((entry) => {\n const meta = capabilityHttp(entry);\n return !meta || !meta.method || !meta.route;\n });\n if (implicit) {\n throw new Error(\n `Capability \"${implicit.capability.id}\" requires an explicit HTTP method and route`,\n );\n }\n }\n const openapi = createOpenApi(app, routes);\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n\n return {\n routes,\n openapi,\n async fetch(request) {\n const url = new URL(request.url);\n if (\n openapiPath &&\n url.pathname === openapiPath &&\n request.method === \"GET\"\n ) {\n return Response.json(openapi);\n }\n const match = routes\n .map((route) => ({ route, params: matchPath(route.path, url.pathname) }))\n .find(({ route, params }) => route.method === request.method && params);\n if (!match?.params) return new Response(\"Not Found\", { status: 404 });\n\n try {\n const input = await readHttpInput(\n request,\n match.params,\n match.route.capability.capability.input,\n );\n const context = options.context\n ? await options.context({ request })\n : undefined as TContext;\n const output = await executeLocatedCapability(match.route.capability, input, {\n context,\n signal: request.signal,\n });\n if (\n request.headers.get(\"accept\")?.includes(\"text/markdown\") &&\n match.route.capability.capability.toPresentation\n ) {\n const presentation = normalizePresentation(\n await match.route.capability.capability.toPresentation(output, {\n context,\n }),\n );\n if (presentation.length > 0) {\n return new Response(\n renderPresentationMarkdown(presentation),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\n },\n );\n }\n }\n return Response.json(output, {\n status: httpSuccessStatus(match.route.capability),\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n },\n };\n}\n\nfunction compileHttpRoute(\n entry: LocatedCapability,\n basePath: string,\n): CompiledHttpRoute {\n const meta = capabilityHttp(entry);\n const defaultPath = entry.path.flatMap((segment, index) => {\n const groupIndex = entry.groupPaths.findIndex(\n (path) => path.length === index + 1,\n );\n const prefix = groupIndex >= 0\n ? (entry.groups[groupIndex]?.meta.http as HttpGroupMeta | undefined)\n ?.prefix\n : undefined;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [segment];\n }).join(\"/\");\n const groupPrefix = entry.groups.flatMap((group) => {\n const prefix = (group.meta.http as HttpGroupMeta | undefined)?.prefix;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [];\n }).join(\"/\");\n const authoredRoute = meta && meta.route ? meta.route : defaultPath;\n assertPathParameters(entry, authoredRoute);\n return Object.freeze({\n method: meta && meta.method\n ? meta.method\n : entry.capability.effect === \"read\"\n ? \"GET\"\n : \"POST\",\n path: joinPath(\n basePath,\n meta && meta.route ? groupPrefix : \"\",\n authoredRoute,\n ),\n capability: entry,\n });\n}\n\nfunction capabilityHttp(entry: LocatedCapability): HttpCapabilityMeta | undefined {\n return entry.capability.meta.http as HttpCapabilityMeta | undefined;\n}\n\nfunction httpSuccessStatus(entry: LocatedCapability): number {\n const meta = capabilityHttp(entry);\n return meta && typeof meta.status === \"number\" ? meta.status : 200;\n}\n\nasync function readHttpInput(\n request: Request,\n params: Record<string, string>,\n schema: LocatedCapability[\"capability\"][\"input\"],\n): Promise<Record<string, unknown>> {\n const url = new URL(request.url);\n const jsonSchema = schema\n ? schemaToJsonSchema(schema, \"input\")\n : undefined;\n const properties = jsonSchema?.properties as\n | Record<string, Readonly<Record<string, unknown>>>\n | undefined;\n const coerceEntries = (entries: Iterable<readonly [string, string]>) =>\n Object.fromEntries(\n [...entries].map(([key, value]) => [\n key,\n coerceHttpValue(value, properties?.[key]),\n ]),\n );\n const rest: Record<string, unknown> =\n request.method === \"GET\"\n ? coerceEntries(url.searchParams)\n : request.headers.get(\"content-type\")?.includes(\"application/json\")\n ? await request.json() as Record<string, unknown>\n : {};\n return {\n ...rest,\n ...coerceEntries(Object.entries(params)),\n };\n}\n\nfunction coerceHttpValue(\n value: string,\n schema: Readonly<Record<string, unknown>> | undefined,\n): unknown {\n if (schema?.type === \"boolean\") return value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : value;\n if (schema?.type === \"integer\" || schema?.type === \"number\") {\n const number = Number(value);\n return Number.isFinite(number) ? number : value;\n }\n return value;\n}\n\nfunction assertPathParameters(\n entry: LocatedCapability,\n path: string,\n): void {\n const parameters = [...path.matchAll(/:([^/]+)/g)].map((match) => match[1]!);\n if (parameters.length === 0) return;\n const schema = entry.capability.input\n ? schemaToJsonSchema(entry.capability.input, \"input\")\n : undefined;\n const properties = schema?.properties as\n | Record<string, unknown>\n | undefined;\n for (const parameter of parameters) {\n if (!properties?.[parameter]) {\n throw new Error(\n `HTTP path parameter \":${parameter}\" is not present in Capability \"${entry.capability.id}\" input`,\n );\n }\n }\n}\n\nfunction matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const expected = pattern.split(\"/\").filter(Boolean);\n const actual = pathname.split(\"/\").filter(Boolean);\n if (expected.length !== actual.length) return undefined;\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const token = expected[index]!;\n const value = actual[index]!;\n if (token.startsWith(\":\")) params[token.slice(1)] = decodeURIComponent(value);\n else if (token !== value) return undefined;\n }\n return params;\n}\n\nfunction createOpenApi(\n app: AppDefinition<any, any>,\n routes: readonly CompiledHttpRoute[],\n): Readonly<Record<string, unknown>> {\n const paths: Record<string, unknown> = {};\n for (const route of routes) {\n const method = route.method.toLowerCase();\n const path = route.path.replace(/:([^/]+)/g, \"{$1}\");\n const capability = route.capability.capability;\n const input = capability.input\n ? schemaToJsonSchema(capability.input, \"input\")\n : undefined;\n const properties = (input?.properties ?? {}) as Record<string, JsonSchema>;\n const required = new Set((input?.required ?? []) as readonly string[]);\n const pathNames = new Set(\n [...route.path.matchAll(/:([^/]+)/g)].map((match) => match[1]!),\n );\n const parameters = [...pathNames].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? {},\n }));\n const remaining = Object.fromEntries(\n Object.entries(properties).filter(([name]) => !pathNames.has(name)),\n );\n if (route.method === \"GET\") {\n parameters.push(\n ...Object.entries(remaining).map(([name, schema]) => ({\n name,\n in: \"query\",\n required: required.has(name),\n schema,\n })),\n );\n }\n const responses: Record<string, unknown> = {\n [String(httpSuccessStatus(route.capability))]: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: capability.output\n ? schemaToJsonSchema(capability.output, \"output\")\n : {},\n },\n },\n },\n };\n for (const [code, error] of Object.entries(route.capability.errors)) {\n const status = typeof error.status === \"number\"\n ? String(error.status)\n : \"default\";\n responses[status] ??= {\n description: error.message ?? code,\n };\n }\n const current = paths[path] as Record<string, unknown> | undefined ?? {};\n current[method] = {\n capabilityId: capability.id,\n ...(capability.title ? { summary: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(parameters.length ? { parameters } : {}),\n ...(route.method !== \"GET\" && Object.keys(remaining).length\n ? {\n requestBody: {\n required: [...required].some((name) => !pathNames.has(name)),\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: remaining,\n required: [...required].filter((name) =>\n !pathNames.has(name)\n ),\n },\n },\n },\n },\n }\n : {}),\n responses,\n };\n paths[path] = current;\n }\n return {\n openapi: \"3.1.0\",\n info: { title: app.name, version: app.version },\n paths,\n };\n}\n\nfunction selectCapabilities(\n capabilities: readonly LocatedCapability[],\n selection: CapabilitySelection | undefined,\n): readonly LocatedCapability[] {\n return capabilities.filter((entry) => {\n const included = selection?.include\n ? matchesTree(selection.include, entry.path)\n : true;\n return included && !matchesTree(selection?.exclude, entry.path);\n });\n}\n\nfunction matchesTree(\n tree: Readonly<Record<string, unknown>> | undefined,\n path: readonly string[],\n): boolean {\n if (!tree) return false;\n let current: unknown = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction assertUniqueRoutes(routes: readonly CompiledHttpRoute[]): void {\n const seen = new Set<string>();\n for (const route of routes) {\n const identity = `${route.method} ${route.path}`;\n if (seen.has(identity)) throw new Error(`Duplicate HTTP route ${identity}`);\n seen.add(identity);\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction joinPath(...parts: readonly string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n"],"mappings":";;;;AAUA,SAAgB,oBACd,OACA,iBAAiB,KACI;CACrB,MAAM,UAAU,iBAAiB,gBAAgB,iBAAiB,iBAC9D,QACA,IAAI,aAAa,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC9D,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ,UAAU;EAC1B,GAAI,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC7D;AACF;AAEA,SAAgB,wBACd,OACA,iBAAiB,KACP;CACV,MAAM,OAAO,oBAAoB,OAAO,cAAc;CACtD,OAAO,SAAS,KAAK;EACnB,IAAI;EACJ,OAAO;CACT,GAAG,EAAE,QAAQ,KAAK,OAAO,CAAC;AAC5B;;;ACZA,SAAgB,oBACd,OACe;CACf,IAAI,CAAC,MAAM,GAAG,KAAK,GAAG,MAAM,IAAI,MAAM,qCAAqC;CAC3E,OAAO,OAAO,OAAO;EACnB,IAAI,MAA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AAC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GAClE,OAAO;EAET,UAAW,QAAoC;CACjD;CACA,OAAO,YAAY,QACjB,QAAQ,OAAO,KAAK,OAAO,YAAY,YAAY,CAAC,MAAM,QAAQ,OAAO;AAE7E;AAEA,SAAS,mBAAmB,QAA4C;CACtE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,GAAG,MAAM,OAAO,GAAG,MAAM;EAC1C,IAAI,KAAK,IAAI,QAAQ,GAAG,MAAM,IAAI,MAAM,wBAAwB,UAAU;EAC1E,KAAK,IAAI,QAAQ;CACnB;AACF;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACtD;AAEA,SAAS,SAAS,GAAG,OAAkC;CACrD,OAAO,cAAc,MAAM,KAAK,GAAG,CAAC;AACtC"}
@@ -1,4 +1,4 @@
1
- import { q as MaybePromise } from "./index-_qKFfWV4.mjs";
1
+ import { Y as MaybePromise } from "./index-WiBWfyTn.mjs";
2
2
  //#region packages/core/src/subscription.d.ts
3
3
  type WatchQueryOptions<TOutput> = {
4
4
  readonly snapshot: () => MaybePromise<TOutput>;
@@ -15,4 +15,4 @@ type WatchQueryOptions<TOutput> = {
15
15
  declare function watchQuery<TOutput>(options: WatchQueryOptions<TOutput>): AsyncIterableIterator<TOutput>;
16
16
  //#endregion
17
17
  export { watchQuery as n, WatchQueryOptions as t };
18
- //# sourceMappingURL=subscription-B-auXJbm.d.mts.map
18
+ //# sourceMappingURL=subscription-DPdwovhw.d.mts.map
package/dist/swr.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { u as AppCapabilityIsSubscribable } from "./index-F4ba_olD.mjs";
1
+ import { _ as AppCapabilityReference, h as AppCapabilityIsLive } from "./index-1A44jLuE.mjs";
2
2
  import { Fetcher, SWRConfiguration } from "swr";
3
3
  import { MutationFetcher, SWRMutationConfiguration } from "swr/mutation";
4
4
  import { SWRSubscription } from "swr/subscription";
@@ -26,7 +26,7 @@ type SWRLiveCapability<TCall extends CapabilityCall> = SWRCapability<TCall> & {
26
26
  subscription(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>];
27
27
  subscription<const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>, options: TOptions];
28
28
  };
29
- type SWRNode<TValue> = TValue extends CapabilityCall ? AppCapabilityIsSubscribable<TValue> extends true ? SWRLiveCapability<TValue> : SWRCapability<TValue> : TValue extends object ? { readonly [TKey in Extract<keyof TValue, string>]: SWRNode<TValue[TKey]>; } : never;
29
+ type SWRNode<TValue> = TValue extends CapabilityCall ? AppCapabilityIsLive<TValue> extends true ? SWRLiveCapability<TValue> : SWRCapability<TValue> : TValue extends object ? { readonly [TKey in Extract<keyof TValue, string> as TValue[TKey] extends AppCapabilityReference ? TValue[TKey] extends CapabilityCall ? TKey : never : TKey]: SWRNode<TValue[TKey]>; } : never;
30
30
  type SWRApp<TApp extends object> = SWRNode<TApp>;
31
31
  declare function createSWR<const TApp extends object>(app: TApp, options?: {
32
32
  readonly keyPrefix?: readonly unknown[];
package/dist/swr.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { u as subscribe } from "./src-betOfnDL.mjs";
1
+ import { p as subscribe } from "./src-DePlcG_t.mjs";
2
2
  //#region packages/swr/src/index.ts
3
3
  const subscribeCall = subscribe;
4
4
  function createSWR(app, options = {}) {
package/dist/swr.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type AppCapabilityIsSubscribable,\n} from \"@capable/app\";\nimport type {\n Fetcher,\n SWRConfiguration,\n} from \"swr\";\nimport type {\n MutationFetcher,\n SWRMutationConfiguration,\n} from \"swr/mutation\";\nimport type { SWRSubscription } from \"swr/subscription\";\n\ntype CapabilityCall = (...args: any[]) => Promise<any>;\n\nconst subscribeCall = subscribe as unknown as (\n capabilityCall: CapabilityCall,\n input: unknown,\n options: { readonly signal: AbortSignal },\n) => AsyncIterableIterator<unknown>;\n\ntype CapabilityInput<TCall extends CapabilityCall> =\n Exclude<Parameters<TCall>[0], undefined>;\n\ntype CapabilityVariables<TCall extends CapabilityCall> =\n undefined extends Parameters<TCall>[0]\n ? Exclude<Parameters<TCall>[0], undefined> | void\n : Parameters<TCall>[0];\n\ntype CapabilityOutput<TCall extends CapabilityCall> =\n Awaited<ReturnType<TCall>>;\n\nexport type CapabilitySWRKey = readonly [unknown, ...unknown[]];\n\ntype CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey\n>;\n\ntype CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey,\n CapabilityVariables<TCall>\n>;\n\nexport type CapabilitySWRConfiguration<\n TCall extends CapabilityCall,\n> = Omit<\n SWRConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilityFetcher<TCall>\n >,\n \"fetcher\"\n>;\n\nexport type CapabilitySWRMutationConfiguration<\n TCall extends CapabilityCall,\n TSWRData = CapabilityOutput<TCall>,\n> = SWRMutationConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilitySWRKey,\n CapabilityVariables<TCall>,\n TSWRData\n> & {\n readonly throwOnError?: boolean;\n};\n\nexport type CapabilitySWRSubscriptionConfiguration<\n TCall extends CapabilityCall,\n> = SWRConfiguration<CapabilityOutput<TCall>, Error>;\n\nexport type SWRCapability<TCall extends CapabilityCall> = {\n key(input?: CapabilityInput<TCall>): CapabilitySWRKey;\n swr(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n ];\n swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n options: TOptions,\n ];\n mutation(): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n ];\n mutation<TSWRData = CapabilityOutput<TCall>>(\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ];\n};\n\nexport type SWRLiveCapability<TCall extends CapabilityCall> =\n SWRCapability<TCall> & {\n subscription(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n ];\n subscription<\n const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>,\n >(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n options: TOptions,\n ];\n };\n\ntype SWRNode<TValue> =\n TValue extends CapabilityCall\n ? AppCapabilityIsSubscribable<TValue> extends true\n ? SWRLiveCapability<TValue>\n : SWRCapability<TValue>\n : TValue extends object\n ? {\n readonly [TKey in Extract<keyof TValue, string>]:\n SWRNode<TValue[TKey]>;\n }\n : never;\n\nexport type SWRApp<TApp extends object> = SWRNode<TApp>;\n\nexport function createSWR<const TApp extends object>(\n app: TApp,\n options: {\n readonly keyPrefix?: readonly unknown[];\n } = {},\n): SWRApp<TApp> {\n const keyPrefix = Object.freeze([...(options.keyPrefix ?? [\"capable\"])]);\n\n const callableAt = (path: readonly string[]): CapabilityCall => {\n let current: unknown = app;\n for (const segment of path) {\n current = (current as Record<string, unknown>)[segment];\n }\n return current as CapabilityCall;\n };\n\n const capabilityKey = (\n path: readonly string[],\n input?: unknown,\n ): CapabilitySWRKey => Object.freeze([\n ...keyPrefix,\n ...path,\n ...(input === undefined ? [] : [input]),\n ]) as CapabilitySWRKey;\n\n const withOptions = (\n key: CapabilitySWRKey,\n operation: (...args: any[]) => unknown,\n hookOptions: unknown,\n ): readonly unknown[] => hookOptions === undefined\n ? [key, operation]\n : [key, operation, hookOptions];\n\n const proxy = (path: readonly string[]): unknown =>\n new Proxy({}, {\n get(_target, key) {\n if (key === \"then\") return undefined;\n if (key === \"key\") {\n return (input?: unknown) => capabilityKey(path, input);\n }\n if (key === \"swr\") {\n return (input: unknown, swrOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n () => callableAt(path)(input),\n swrOptions,\n );\n }\n if (key === \"mutation\") {\n return (mutationOptions?: unknown) => withOptions(\n capabilityKey(path),\n (_key: CapabilitySWRKey, { arg }: { readonly arg?: unknown }) =>\n callableAt(path)(arg),\n mutationOptions,\n );\n }\n if (key === \"subscription\") {\n return (input: unknown, subscriptionOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n (\n _key: CapabilitySWRKey,\n { next }: {\n readonly next: (error?: Error | null, data?: unknown) => void;\n },\n ) => {\n const controller = new AbortController();\n\n void (async () => {\n try {\n for await (const output of subscribeCall(\n callableAt(path),\n input,\n { signal: controller.signal },\n )) {\n next(null, output);\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n next(toError(error));\n }\n }\n })();\n\n return () => controller.abort();\n },\n subscriptionOptions,\n );\n }\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key]);\n },\n });\n\n return proxy([]) as SWRApp<TApp>;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n"],"mappings":";;AAgBA,MAAM,gBAAgB;AA6HtB,SAAgB,UACd,KACA,UAEI,CAAC,GACS;CACd,MAAM,YAAY,OAAO,OAAO,CAAC,GAAI,QAAQ,a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EACpC,OAAO,MAAM,CAAC,GAAG,MAAM,GAAG,CAAC;CAC7B,EACF,CAAC;CAEH,OAAO,MAAM,CAAC,CAAC;AACjB;AAEA,SAAS,QAAQ,OAAuB;CACtC,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE"}
1
+ {"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type AppCapabilityIsLive,\n type AppCapabilityReference,\n} from \"@capable/app\";\nimport type {\n Fetcher,\n SWRConfiguration,\n} from \"swr\";\nimport type {\n MutationFetcher,\n SWRMutationConfiguration,\n} from \"swr/mutation\";\nimport type { SWRSubscription } from \"swr/subscription\";\n\ntype CapabilityCall = (...args: any[]) => Promise<any>;\n\nconst subscribeCall = subscribe as unknown as (\n capabilityCall: CapabilityCall,\n input: unknown,\n options: { readonly signal: AbortSignal },\n) => AsyncIterableIterator<unknown>;\n\ntype CapabilityInput<TCall extends CapabilityCall> =\n Exclude<Parameters<TCall>[0], undefined>;\n\ntype CapabilityVariables<TCall extends CapabilityCall> =\n undefined extends Parameters<TCall>[0]\n ? Exclude<Parameters<TCall>[0], undefined> | void\n : Parameters<TCall>[0];\n\ntype CapabilityOutput<TCall extends CapabilityCall> =\n Awaited<ReturnType<TCall>>;\n\nexport type CapabilitySWRKey = readonly [unknown, ...unknown[]];\n\ntype CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey\n>;\n\ntype CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey,\n CapabilityVariables<TCall>\n>;\n\nexport type CapabilitySWRConfiguration<\n TCall extends CapabilityCall,\n> = Omit<\n SWRConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilityFetcher<TCall>\n >,\n \"fetcher\"\n>;\n\nexport type CapabilitySWRMutationConfiguration<\n TCall extends CapabilityCall,\n TSWRData = CapabilityOutput<TCall>,\n> = SWRMutationConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilitySWRKey,\n CapabilityVariables<TCall>,\n TSWRData\n> & {\n readonly throwOnError?: boolean;\n};\n\nexport type CapabilitySWRSubscriptionConfiguration<\n TCall extends CapabilityCall,\n> = SWRConfiguration<CapabilityOutput<TCall>, Error>;\n\nexport type SWRCapability<TCall extends CapabilityCall> = {\n key(input?: CapabilityInput<TCall>): CapabilitySWRKey;\n swr(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n ];\n swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n options: TOptions,\n ];\n mutation(): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n ];\n mutation<TSWRData = CapabilityOutput<TCall>>(\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ];\n};\n\nexport type SWRLiveCapability<TCall extends CapabilityCall> =\n SWRCapability<TCall> & {\n subscription(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n ];\n subscription<\n const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>,\n >(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n options: TOptions,\n ];\n };\n\ntype SWRNode<TValue> =\n TValue extends CapabilityCall\n ? AppCapabilityIsLive<TValue> extends true\n ? SWRLiveCapability<TValue>\n : SWRCapability<TValue>\n : TValue extends object\n ? {\n readonly [TKey in Extract<keyof TValue, string> as\n TValue[TKey] extends AppCapabilityReference\n ? TValue[TKey] extends CapabilityCall ? TKey : never\n : TKey]: SWRNode<TValue[TKey]>;\n }\n : never;\n\nexport type SWRApp<TApp extends object> = SWRNode<TApp>;\n\nexport function createSWR<const TApp extends object>(\n app: TApp,\n options: {\n readonly keyPrefix?: readonly unknown[];\n } = {},\n): SWRApp<TApp> {\n const keyPrefix = Object.freeze([...(options.keyPrefix ?? [\"capable\"])]);\n\n const callableAt = (path: readonly string[]): CapabilityCall => {\n let current: unknown = app;\n for (const segment of path) {\n current = (current as Record<string, unknown>)[segment];\n }\n return current as CapabilityCall;\n };\n\n const capabilityKey = (\n path: readonly string[],\n input?: unknown,\n ): CapabilitySWRKey => Object.freeze([\n ...keyPrefix,\n ...path,\n ...(input === undefined ? [] : [input]),\n ]) as CapabilitySWRKey;\n\n const withOptions = (\n key: CapabilitySWRKey,\n operation: (...args: any[]) => unknown,\n hookOptions: unknown,\n ): readonly unknown[] => hookOptions === undefined\n ? [key, operation]\n : [key, operation, hookOptions];\n\n const proxy = (path: readonly string[]): unknown =>\n new Proxy({}, {\n get(_target, key) {\n if (key === \"then\") return undefined;\n if (key === \"key\") {\n return (input?: unknown) => capabilityKey(path, input);\n }\n if (key === \"swr\") {\n return (input: unknown, swrOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n () => callableAt(path)(input),\n swrOptions,\n );\n }\n if (key === \"mutation\") {\n return (mutationOptions?: unknown) => withOptions(\n capabilityKey(path),\n (_key: CapabilitySWRKey, { arg }: { readonly arg?: unknown }) =>\n callableAt(path)(arg),\n mutationOptions,\n );\n }\n if (key === \"subscription\") {\n return (input: unknown, subscriptionOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n (\n _key: CapabilitySWRKey,\n { next }: {\n readonly next: (error?: Error | null, data?: unknown) => void;\n },\n ) => {\n const controller = new AbortController();\n\n void (async () => {\n try {\n for await (const output of subscribeCall(\n callableAt(path),\n input,\n { signal: controller.signal },\n )) {\n next(null, output);\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n next(toError(error));\n }\n }\n })();\n\n return () => controller.abort();\n },\n subscriptionOptions,\n );\n }\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key]);\n },\n });\n\n return proxy([]) as SWRApp<TApp>;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n"],"mappings":";;AAiBA,MAAM,gBAAgB;AA+HtB,SAAgB,UACd,KACA,UAEI,CAAC,GACS;CACd,MAAM,YAAY,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,CAAC,SAAS,CAAE,CAAC;CAEvE,MAAM,cAAc,SAA4C;EAC9D,IAAI,UAAmB;EACvB,KAAK,MAAM,WAAW,MACpB,UAAW,QAAoC;EAEjD,OAAO;CACT;CAEA,MAAM,iBACJ,MACA,UACqB,OAAO,OAAO;EACnC,GAAG;EACH,GAAG;EACH,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK;CACvC,CAAC;CAED,MAAM,eACJ,KACA,WACA,gBACuB,gBAAgB,KAAA,IACrC,CAAC,KAAK,SAAS,IACf;EAAC;EAAK;EAAW;CAAW;CAEhC,MAAM,SAAS,SACb,IAAI,MAAM,CAAC,GAAG,EACZ,IAAI,SAAS,KAAK;EAChB,IAAI,QAAQ,QAAQ,OAAO,KAAA;EAC3B,IAAI,QAAQ,OACV,QAAQ,UAAoB,cAAc,MAAM,KAAK;EAEvD,IAAI,QAAQ,OACV,QAAQ,OAAgB,eAAyB,YAC/C,cAAc,MAAM,KAAK,SACnB,WAAW,IAAI,CAAC,CAAC,KAAK,GAC5B,UACF;EAEF,IAAI,QAAQ,YACV,QAAQ,oBAA8B,YACpC,cAAc,IAAI,IACjB,MAAwB,EAAE,UACzB,WAAW,IAAI,CAAC,CAAC,GAAG,GACtB,eACF;EAEF,IAAI,QAAQ,gBACV,QAAQ,OAAgB,wBAAkC,YACxD,cAAc,MAAM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