capable-kit 0.0.1-alpha.8 → 0.1.0-alpha.9

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 (78) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +6 -0
  3. package/dist/ai-sdk.d.mts +2 -2
  4. package/dist/ai-sdk.mjs +1 -1
  5. package/dist/app.d.mts +2 -2
  6. package/dist/app.mjs +2 -2
  7. package/dist/bin.mjs +4 -4
  8. package/dist/cli.d.mts +4 -1
  9. package/dist/cli.mjs +1 -1
  10. package/dist/core.d.mts +2 -2
  11. package/dist/core.mjs +1 -1
  12. package/dist/eve.d.mts +82 -5
  13. package/dist/eve.mjs +358 -19
  14. package/dist/eve.mjs.map +1 -1
  15. package/dist/http.d.mts +1 -1
  16. package/dist/http.mjs +1 -1
  17. package/dist/{index-F4ba_olD.d.mts → index-D63DSGZG.d.mts} +10 -5
  18. package/dist/{index-Dl4NK9G0.d.mts → index-D8DWjQ9f.d.mts} +3 -3
  19. package/dist/{index-hdH_K5Zc.d.mts → index-DgxvtAmv.d.mts} +4 -4
  20. package/dist/{index-_qKFfWV4.d.mts → index-ftQx6OMr.d.mts} +23 -13
  21. package/dist/index.d.mts +4 -4
  22. package/dist/index.mjs +3 -3
  23. package/dist/mcp.d.mts +2 -2
  24. package/dist/mcp.mjs +1 -1
  25. package/dist/{mount-CEFAplR5.mjs → mount-B9TrHWHh.mjs} +3 -3
  26. package/dist/{mount-CEFAplR5.mjs.map → mount-B9TrHWHh.mjs.map} +1 -1
  27. package/dist/react-query.d.mts +1 -1
  28. package/dist/react-query.mjs +1 -1
  29. package/dist/runtime-support.d.mts +1 -1
  30. package/dist/runtime-support.mjs +3 -3
  31. package/dist/server.d.mts +1 -1
  32. package/dist/server.mjs +1 -1
  33. package/dist/{src-betOfnDL.mjs → src-B592M-6b.mjs} +143 -44
  34. package/dist/src-B592M-6b.mjs.map +1 -0
  35. package/dist/{src-D-cm2gQ6.mjs → src-Bd1Vnze8.mjs} +16 -2
  36. package/dist/src-Bd1Vnze8.mjs.map +1 -0
  37. package/dist/{src-BWxDO2Ua.mjs → src-CKC1BdXO.mjs} +3 -3
  38. package/dist/{src-BWxDO2Ua.mjs.map → src-CKC1BdXO.mjs.map} +1 -1
  39. package/dist/{src-D_0PIhqq.mjs → src-CL9eA6_p.mjs} +42 -25
  40. package/dist/src-CL9eA6_p.mjs.map +1 -0
  41. package/dist/{src-rkr5j_NH.mjs → src-Hw9WBgEW.mjs} +3 -3
  42. package/dist/{src-rkr5j_NH.mjs.map → src-Hw9WBgEW.mjs.map} +1 -1
  43. package/dist/{subscription-B-auXJbm.d.mts → subscription-DbnHcm7C.d.mts} +2 -2
  44. package/dist/swr.d.mts +1 -1
  45. package/dist/swr.mjs +1 -1
  46. package/docs/CONTEXT.md +17 -10
  47. package/docs/README.md +3 -0
  48. package/docs/internal/README.md +3 -0
  49. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  50. package/docs/internal/architecture.md +11 -10
  51. package/docs/internal/capability-first-model.md +31 -8
  52. package/docs/internal/eve-recovery-validation.md +86 -0
  53. package/docs/internal/feedback/v-ray/README.md +258 -0
  54. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  55. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  56. package/docs/internal/implementation-friction.md +301 -1
  57. package/docs/internal/releases.md +79 -0
  58. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  59. package/docs/site/concepts/apps.mdx +6 -0
  60. package/docs/site/concepts/architecture.mdx +1 -1
  61. package/docs/site/concepts/capabilities.mdx +39 -2
  62. package/docs/site/concepts/errors.mdx +11 -1
  63. package/docs/site/concepts/presentations.mdx +16 -0
  64. package/docs/site/patterns/composition.mdx +50 -8
  65. package/docs/site/patterns/remote-apps.mdx +1 -1
  66. package/docs/site/quickstart.mdx +1 -1
  67. package/docs/site/reference/packages-and-entry-points.mdx +11 -3
  68. package/docs/site/surfaces/cli.mdx +33 -0
  69. package/docs/site/surfaces/eve.mdx +65 -18
  70. package/docs/site/surfaces/typescript.mdx +1 -1
  71. package/package-docs.mjs +3 -0
  72. package/package.json +10 -11
  73. package/src/bin.ts +0 -0
  74. package/src/index.test.ts +1 -1
  75. package/src/index.ts +1 -1
  76. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  77. package/dist/src-D_0PIhqq.mjs.map +0 -1
  78. package/dist/src-betOfnDL.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"src-rkr5j_NH.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 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 stream = runtime.subscribe({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n const first = await stream.next();\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 yield* decodeEventStream(response, codec);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult>,\n subscriptionController: AbortController,\n codec: ProtocolCodec,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n\n return new Response(new ReadableStream({\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\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 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 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\nasync function* 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 const reader = response.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 {\n type ApplicationSelection,\n type JsonSchema,\n} 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) => capabilityHttp(entry) !== false);\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,MA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AAoC;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
+ {"version":3,"file":"src-Hw9WBgEW.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 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 stream = runtime.subscribe({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n const first = await stream.next();\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 yield* decodeEventStream(response, codec);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult>,\n subscriptionController: AbortController,\n codec: ProtocolCodec,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n\n return new Response(new ReadableStream({\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\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 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 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\nasync function* 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 const reader = response.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 {\n type ApplicationSelection,\n type JsonSchema,\n} 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) => capabilityHttp(entry) !== false);\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,MAAM;EACV,QAAQ,MAAM;EACd,QAAQ,MAAM;CAChB,CAAC;AACH;AAEA,MAAM,WAAW,IAAI,UAAU;AAE/B,MAAa,uBAAsC,oBAAoB;CACrE,IAAI;CACJ,OAAO,OAAO;EACZ,OAAO,SAAS,UAAU,KAAuB;CACnD;CACA,OAAO,OAAO;EACZ,OAAO,SAAS,YAAY,KAAmC;CACjE;AACF,CAAC;;;ACvBD,MAAM,wBAAwB;AAE9B,SAAgB,sBACd,aAGA,UAGI,CAAC,GAGL;CACA,MAAM,WAAWA,gBAAc,QAAQ,YAAY,WAAW;CAC9D,MAAM,QAAQ,QAAQ,SAAS;CAE/B,MAAM,QAAsB,OAAO,YAAY;EAC7C,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAI/B,MAAM,UAAU,cAHJ,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S,MAAM,IAAI;CAChE,CAAC;AACH;AAEA,SAAS,YACP,MACA,MACS;CACT,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,UAAmB;CACvB,KAAK,MAAM,WAAW,MAAM;EAC1B,IAAI,YAAY,MAAM,OAAO;EAC7B,IAAI,CAAC,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 { q as MaybePromise } from "./index-ftQx6OMr.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-DbnHcm7C.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 { u as AppCapabilityIsSubscribable } from "./index-D63DSGZG.mjs";
2
2
  import { Fetcher, SWRConfiguration } from "swr";
3
3
  import { MutationFetcher, SWRMutationConfiguration } from "swr/mutation";
4
4
  import { SWRSubscription } from "swr/subscription";
package/dist/swr.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { u as subscribe } from "./src-betOfnDL.mjs";
1
+ import { u as subscribe } from "./src-B592M-6b.mjs";
2
2
  //#region packages/swr/src/index.ts
3
3
  const subscribeCall = subscribe;
4
4
  function createSWR(app, options = {}) {
package/docs/CONTEXT.md CHANGED
@@ -8,18 +8,20 @@ It has no canonical HTTP method or path.
8
8
 
9
9
  **App Definition**: immutable named object nesting created by `defineApp()`
10
10
  whose leaves are Capabilities. It carries no context provider or execution
11
- placement. Its paths drive navigational interfaces and surface defaults.
11
+ placement. It can contribute app-wide middleware and declared errors. Its paths
12
+ drive navigational interfaces and surface defaults.
12
13
 
13
14
  **Group**: an anonymous decorated subtree created with `group()`. It has no ID.
14
15
  It contributes semantic middleware and errors and exposes its metadata ancestry
15
16
  to surface compilers.
16
17
 
17
- **Capability ID**: canonical execution and transport identity. IDs are unique
18
- within an Application.
18
+ **Capability ID**: canonical execution and transport identity. One ID has one
19
+ execution owner within an Application.
19
20
 
20
- **Application path**: the unique object path to a Capability, such as
21
+ **Application path**: an object path to a Capability, such as
21
22
  `admin.users.create`. It drives direct App calls, CLI, and MCP navigation but
22
- is not the Capability's identity.
23
+ is not the Capability's identity. One Capability may have multiple paths when
24
+ the same App runtime is deliberately composed under aliases.
23
25
 
24
26
  **Effect**: optional `read`, `write`, or `destructive` intent. HTTP may derive
25
27
  GET only from `read`; MCP may derive safety hints. Absence means unknown.
@@ -43,13 +45,16 @@ stores no provider.
43
45
  **App**: a context-erased typed callable object tree. `createApp()` closes over
44
46
  direct execution and its provider; `createRemoteApp()` wraps a transport
45
47
  without performing I/O. Remote manifest discovery is lazy, validated, and
46
- cached. `mergeApps()` returns the same shape. A low-level
48
+ cached. `composeApps()` returns the same shape. A low-level
47
49
  `manifest() + call() + subscribe()` runtime lives behind internal symbols for
48
50
  surfaces and composition.
49
51
 
50
- **Application merge**: strict root-tree combination through `mergeApps()`.
51
- Calls dispatch by immutable Capability ID. All path, ID, double-mount, and
52
- leaf/subtree conflicts fail when the merged manifest first resolves.
52
+ **Application composition**: strict tree-shaped combination through
53
+ `composeApps()`. App arguments contribute at the root; object keys place Apps
54
+ beneath navigational branches. Calls dispatch by immutable Capability ID. One
55
+ ID has exactly one execution owner but may appear at multiple paths through
56
+ aliases. Conflicting ownership, path, and leaf/subtree conflicts fail when the
57
+ composed manifest first resolves.
53
58
 
54
59
  **Capable transport**: an asynchronous boundary exposing `manifest()`,
55
60
  `call()`, and `subscribe()`. `createRemoteApp()` wraps and caches it without
@@ -99,7 +104,9 @@ keeps App navigation collision-free.
99
104
  - App Definitions never carry context providers.
100
105
  - A context-free `createApp()` needs no provider; a contextual one satisfies
101
106
  and erases only its own context before merging.
102
- - A Capability object and ID may each occur only once in an Application.
107
+ - A Capability ID has exactly one execution owner in an Application. Reusing
108
+ that App runtime at another path creates an alias; another runtime claiming
109
+ the same ID is invalid.
103
110
  - Handlers receive only `{ input, context, signal }`.
104
111
  - Semantic middleware and declared errors execute identically for every
105
112
  surface.
package/docs/README.md CHANGED
@@ -8,6 +8,9 @@ the npm package is packed. It matches the installed package version.
8
8
  Do not rely on remembered Capable APIs. Read the relevant bundled guide and
9
9
  inspect `../src/` when you need a detail the guides do not cover.
10
10
 
11
+ Before upgrading, read [the versioned changelog](../CHANGELOG.md). Apply all
12
+ entries after the installed version through the target version, oldest first.
13
+
11
14
  Start here:
12
15
 
13
16
  1. [Introduction](./site/introduction.mdx)
@@ -10,7 +10,10 @@ docs:dev`). This directory is for people working *on* Capable.
10
10
  | [architecture.md](./architecture.md) | How the packages are layered and why |
11
11
  | [adr/](./adr) | Accepted decisions |
12
12
  | [implementation-friction.md](./implementation-friction.md) | Live log of awkward or leaky implementation work |
13
+ | [feedback/v-ray/](./feedback/v-ray/README.md) | Reproduced migration feedback, compiler matrix, and prioritized proposals |
13
14
  | [why-capable.md](./why-capable.md) | The original internal argument for the project |
14
15
 
15
16
  If a change contradicts CONTEXT.md, change CONTEXT.md in the same commit or do
16
17
  not make the change.
18
+
19
+ See [Releases](./releases.md) for changesets, alpha publishing, and migration notes.
@@ -19,6 +19,6 @@ not enter the handler contract or canonical output.
19
19
  App Definitions do not own context provision. `createApp()` satisfies one
20
20
  definition's context and erases it into a directly callable App;
21
21
  `createRemoteApp()` returns the same callable shape while lazily discovering
22
- and validating transport execution. `mergeApps()` combines these
22
+ and validating transport execution. `composeApps()` combines these
23
23
  context-erased Apps, so unrelated local contexts never become one giant merged
24
24
  context.
@@ -17,7 +17,7 @@ App Definition ──────────────► createServer(defini
17
17
  └─ createRemoteApp(transport)
18
18
  │ lazy manifest discovery
19
19
  │
20
- mergeApps / selectApp
20
+ composeApps / selectApp
21
21
  │
22
22
  ▼
23
23
  App (typed callable object tree)
@@ -46,7 +46,7 @@ as `capable-kit/server`, `capable-kit/next`, and `capable-kit/swr`.
46
46
  | `@capable/cli` | Command derivation, parsing, help, and rendering |
47
47
  | `@capable/mcp` | Tool derivation and the Streamable HTTP mount |
48
48
  | `@capable/ai-sdk` | Typed AI SDK v7 tool projection |
49
- | `@capable/eve` | Native in-process Eve tool projection |
49
+ | `@capable/eve` | Native Eve tool projection and caller-scoped agent lifecycle Apps |
50
50
  | `@capable/react-query` | Query keys, query options, mutations, live queries |
51
51
  | `@capable/swr` | SWR keys, fetchers, mutations, and subscriptions |
52
52
  | `@capable/next` | Method-export translation for the App Router |
@@ -135,20 +135,21 @@ began uses a typed SSE error frame.
135
135
 
136
136
  ## Composition
137
137
 
138
- `mergeApps(a, b)` merges root trees rather than building a pipeline. It returns
139
- synchronously and resolves its inputs together when its manifest is first
140
- needed. Path and ID conflicts therefore fail at that discovery boundary, before
141
- the first Capability is dispatched. Namespaces belong in the authored App
142
- Definition:
138
+ `composeApps(a, b, { remote })` combines executable Apps into one tree rather
139
+ than building a pipeline. App arguments contribute at the root; object keys
140
+ place Apps beneath navigational branches. It returns synchronously and resolves
141
+ its inputs together when its complete manifest is first needed. Path and ID
142
+ conflicts therefore fail at that discovery boundary. A direct call under a
143
+ named branch resolves only that branch:
143
144
 
144
145
  ```ts
145
146
  const remote = createRemoteApp<AppDefinition>(transport);
146
- const app = mergeApps(
147
- remote,
147
+ const app = composeApps(
148
148
  createApp(localDefinition, { context: createLocalContext }),
149
+ { remote },
149
150
  );
150
151
 
151
- await app.local.login({ token });
152
+ await app.remote.todos.list();
152
153
  ```
153
154
 
154
155
  ## Surface compilation
@@ -59,10 +59,29 @@ treated as no Presentation, so surfaces use their canonical-output fallback.
59
59
 
60
60
  ## Execution
61
61
 
62
- Input is parsed once, group middleware wraps capability middleware, the handler
62
+ Input is parsed once, app middleware wraps outer-to-inner group middleware and
63
+ capability middleware, the handler
63
64
  runs, thrown errors are normalized against the located error sets, and output is
64
65
  validated. Every surface enters this same lifecycle.
65
66
 
67
+ App Definitions accept `middleware` and `errors` using the same inheritance
68
+ rules as Groups. Middleware at every scope receives a readonly `capability`
69
+ descriptor (`id`, `effect`) and execution `mode` (`call` or `subscribe`).
70
+ The descriptor does not expose executable definitions or application paths.
71
+ Middleware consumes the existing Context contract; it cannot refine downstream
72
+ Context types or introduce Context requirements on the App Definition.
73
+
74
+ ```ts
75
+ const definition = defineApp({
76
+ capabilities: { todos },
77
+ errors: AccessErrors,
78
+ middleware: [({ capability, context, next }) => {
79
+ if (!canCall(context.user, capability.id)) throw AccessErrors.FORBIDDEN();
80
+ return next();
81
+ }],
82
+ });
83
+ ```
84
+
66
85
  A Capability executes without an Application:
67
86
 
68
87
  ```ts
@@ -70,7 +89,7 @@ await executeCapability(deleteTodo, { input, context, signal });
70
89
  ```
71
90
 
72
91
  That boundary applies the Capability's own validation, middleware, and declared
73
- errors. Group middleware and Group error sets are properties of placement and
92
+ errors. App and Group middleware and error sets are properties of placement and
74
93
  therefore require execution through the tree.
75
94
 
76
95
  ## Errors
@@ -88,26 +107,30 @@ if (TodoErrors.NOT_FOUND.is(error)) console.error(error.data.todoId);
88
107
  Declared error data is validated by the executor. Anything outside the located
89
108
  Capability's error sets becomes `INTERNAL_SERVER_ERROR`, retaining the original
90
109
  value only as a server-side `cause`. A Group and a Capability may not declare
91
- the same code twice; the conflict fails when the definition is created.
110
+ the same code twice; the conflict fails when the definition is created. The same
111
+ rule applies to App errors inherited by Groups and Capabilities.
92
112
 
93
113
  ## Context and placement
94
114
 
95
115
  `defineApp()` stores no context provider. `createApp()` supplies and erases one
96
116
  context; `createRemoteApp()` returns a lazy, transport-backed App. Unrelated
97
- local contexts are erased before `mergeApps()` and never become one combined
117
+ local contexts are erased before `composeApps()` and never become one combined
98
118
  context:
99
119
 
100
120
  ```ts
101
121
  const remote = createRemoteApp<AppDefinition>(transport);
102
- const app = mergeApps(
122
+ const app = composeApps(
103
123
  remote,
104
124
  createApp(localDefinition, { context: createLocalContext }),
105
125
  );
106
126
  ```
107
127
 
108
- Merging validates path, ID, double-mount, and leaf/subtree conflicts when its
109
- manifest first resolves, then dispatches by Capability ID. It never repositions
110
- trees or rewrites IDs; namespaces belong in the authored definition.
128
+ Composition validates path, ID ownership, and leaf/subtree conflicts when its
129
+ complete manifest first resolves, then dispatches by Capability ID. App
130
+ arguments contribute at the root; object keys reposition Apps beneath
131
+ navigational namespaces without rewriting IDs. Reusing one App runtime creates
132
+ aliases; distinct runtimes cannot claim the same ID. Direct calls beneath a
133
+ namespace resolve only the branches that can contribute to that path.
111
134
 
112
135
  ## Replacement subscriptions
113
136
 
@@ -0,0 +1,86 @@
1
+ # Capable reproduction for Eve PR #2981
2
+
3
+ The integration uses `defineDurableCallback` from the PR at
4
+ `8e6964036657082ce1405864cf3313ad11fc8d60`, backported onto Eve 0.52.3 with the
5
+ checked-in pnpm patch. No Eve lifecycle code is changed.
6
+
7
+ User API:
8
+
9
+ ```ts
10
+ export default createEveTools(({ session }) =>
11
+ appForUser(session.auth.current!.principalId), {
12
+ approval: capability =>
13
+ capability.effect === "destructive" ? approvalPolicy : undefined,
14
+ });
15
+ ```
16
+
17
+ Internally, the adapter uses `session.started` for recoverable discovery and
18
+ persists `{ id: capability.id }` in its generated execution callback. On recovery,
19
+ Eve reruns the resolver to register the current implementation. The App provider
20
+ is invoked again with the live execution session before the handler runs.
21
+ The app's code is reconstructable; its data resides outside the function process.
22
+
23
+ A regression surfaced during testing: an unauthorized approval attempt triggered
24
+ recovery with that responder as the current user. Holding onto the App from that
25
+ resolver caused later, legitimately approved execution to use the wrong user's
26
+ context. Recreating the execution App from `ToolContext.session` fixed it.
27
+
28
+ ## Local test
29
+
30
+ ```sh
31
+ pnpm install --frozen-lockfile
32
+ pnpm run build
33
+ pnpm --dir examples/eve run test:recovery
34
+ ```
35
+
36
+ Requires an AI Gateway credential. The test:
37
+
38
+ 1. Creates a persistent todo and starts an agent deletion through the CLI.
39
+ 2. Waits for an actual tool-approval request and a durable waiting event.
40
+ 3. Stops Eve and verifies its health endpoint is unreachable.
41
+ 4. Starts a fresh server with the same workflow and todo storage.
42
+ 5. Submits an approval as another authenticated user and checks rejection.
43
+ 6. Approves as the initiator and checks the original call's successful result.
44
+ 7. Verifies the deletion receipt names the initiating user and the new instance.
45
+ 8. Reads the completed result through a fresh CLI process.
46
+
47
+ ## Vercel test
48
+
49
+ `examples/eve/vercel-recovery.e2e.ts` separates `prepare` and `resume` so a new
50
+ preview can be deployed while the call is paused. The driver uses the same
51
+ private Blob store as the deployed app. It checks the same request/call identity,
52
+ rejected responder, successful original-user execution, and persistent deletion.
53
+ It fails if the approval and execution instance markers are identical.
54
+
55
+ The test project is `timo-lins-projects/capable-eve-recovery`. Its routes require
56
+ new demo bearer credentials, and its Blob store is private. See the demo README
57
+ for environment variables and commands. Gateway credentials remain in sensitive
58
+ Preview environment variables; no credentials belong in a reproduction or PR.
59
+
60
+ No issue or PR comment has been posted by this task.
61
+
62
+ ## Recorded result — September 9, 2026
63
+
64
+ Both the local stop/start test and the deployed two-phase test passed. The normal
65
+ CLI E2E also passed, alongside 126 unit tests, 5 auth integration tests,
66
+ typechecking, and the package build.
67
+
68
+ Deployed run: `wrun_41M22YGA1Q0GGVQMMJRQF13QQV`.
69
+
70
+ - Prepared on this immutable preview:
71
+ https://capable-eve-recovery-pilxxx6pq-timo-lins-projects.vercel.app
72
+ - Resumed through a newly deployed preview:
73
+ https://capable-eve-recovery-1qtw73tiv-timo-lins-projects.vercel.app
74
+ - Approval runtime marker: `16cfe5b5-ee66-4914-807b-7f15549f292b`.
75
+ - Execution runtime marker: `9f0c5a38-a12d-46e2-a1de-47bed69dd513`.
76
+ - Execution principal: `demo-user`.
77
+ - A fresh combined-CLI process subsequently read `status: "completed"` from
78
+ the deployed run and returned the deletion confirmation.
79
+ - The other authenticated principal's approval was rejected before execution.
80
+ - The successful result kept the original pending request's tool-call ID.
81
+ - The private Blob record contained the deletion, and the normal todo list no
82
+ longer contained that item.
83
+
84
+ These markers identify initialized demo runtime instances. The separate local
85
+ test additionally verifies that the original server process was actually stopped.
86
+ This is a focused approval-recovery test, not load or exhaustive replay testing.