capable-kit 0.0.1-alpha.6 → 0.0.1-alpha.8

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 (88) hide show
  1. package/dist/ai-sdk.d.mts +2 -2
  2. package/dist/ai-sdk.mjs +1 -1
  3. package/dist/app.d.mts +1 -1
  4. package/dist/app.mjs +1 -1
  5. package/dist/bin.mjs +12 -9
  6. package/dist/bin.mjs.map +1 -1
  7. package/dist/cli.d.mts +1 -1
  8. package/dist/cli.mjs +1 -1
  9. package/dist/core.d.mts +2 -2
  10. package/dist/core.mjs +1 -1
  11. package/dist/eve.d.mts +1 -1
  12. package/dist/eve.mjs +1 -1
  13. package/dist/http.d.mts +2 -2
  14. package/dist/http.mjs +2 -2
  15. package/dist/{index-DwXlaTXI.d.mts → index-Dl4NK9G0.d.mts} +20 -4
  16. package/dist/{index-Dbc4g9WM.d.mts → index-F4ba_olD.d.mts} +3 -3
  17. package/dist/{index-Be8-UVBC.d.mts → index-_qKFfWV4.d.mts} +4 -2
  18. package/dist/{index-D2CRRUzH.d.mts → index-hdH_K5Zc.d.mts} +6 -5
  19. package/dist/index.d.mts +3 -3
  20. package/dist/index.mjs +2 -2
  21. package/dist/mcp.d.mts +35 -5
  22. package/dist/mcp.mjs +1 -1
  23. package/dist/mount-CEFAplR5.mjs +227 -0
  24. package/dist/mount-CEFAplR5.mjs.map +1 -0
  25. package/dist/next.d.mts +14 -0
  26. package/dist/next.mjs +16 -0
  27. package/dist/next.mjs.map +1 -0
  28. package/dist/react-query.d.mts +34 -0
  29. package/dist/react-query.mjs +47 -0
  30. package/dist/react-query.mjs.map +1 -0
  31. package/dist/runtime-support.d.mts +1 -1
  32. package/dist/runtime-support.mjs +8 -8
  33. package/dist/runtime-support.mjs.map +1 -1
  34. package/dist/server.d.mts +1 -1
  35. package/dist/server.mjs +1 -1
  36. package/dist/{src-CDxL6w3d.mjs → src-BWxDO2Ua.mjs} +9 -6
  37. package/dist/src-BWxDO2Ua.mjs.map +1 -0
  38. package/dist/{src-DdV82An-.mjs → src-D-cm2gQ6.mjs} +6 -3
  39. package/dist/src-D-cm2gQ6.mjs.map +1 -0
  40. package/dist/{src-Db6-XSnU.mjs → src-D_0PIhqq.mjs} +3 -3
  41. package/dist/{src-Db6-XSnU.mjs.map → src-D_0PIhqq.mjs.map} +1 -1
  42. package/dist/{src-C2MGIlT0.mjs → src-betOfnDL.mjs} +25 -8
  43. package/dist/src-betOfnDL.mjs.map +1 -0
  44. package/dist/{src-BF70JLxI.mjs → src-rkr5j_NH.mjs} +162 -33
  45. package/dist/src-rkr5j_NH.mjs.map +1 -0
  46. package/dist/{subscription-Bq792Ad2.d.mts → subscription-B-auXJbm.d.mts} +2 -2
  47. package/dist/swr.d.mts +36 -0
  48. package/dist/swr.mjs +48 -0
  49. package/dist/swr.mjs.map +1 -0
  50. package/docs/CONTEXT.md +3 -1
  51. package/docs/internal/adr/0002-version-the-capable-value-codec.md +24 -0
  52. package/docs/internal/architecture.md +34 -3
  53. package/docs/internal/capability-first-model.md +1 -1
  54. package/docs/internal/implementation-friction.md +110 -0
  55. package/docs/site/capable-orpc-and-trpc.mdx +3 -3
  56. package/docs/site/concepts/apps.mdx +10 -7
  57. package/docs/site/concepts/architecture.mdx +1 -1
  58. package/docs/site/hosting/any-fetch-host.mdx +2 -2
  59. package/docs/site/hosting/next-js.mdx +38 -4
  60. package/docs/site/hosting/standalone-server.mdx +2 -2
  61. package/docs/site/introduction.mdx +9 -6
  62. package/docs/site/patterns/composition.mdx +7 -3
  63. package/docs/site/patterns/remote-apps.mdx +62 -8
  64. package/docs/site/patterns/subscriptions.mdx +2 -2
  65. package/docs/site/quickstart.mdx +18 -13
  66. package/docs/site/reference/packages-and-entry-points.mdx +2 -2
  67. package/docs/site/reference/surface-metadata.mdx +7 -2
  68. package/docs/site/reference/the-cap-cli.mdx +2 -2
  69. package/docs/site/surfaces/ai-sdk.mdx +3 -3
  70. package/docs/site/surfaces/cli.mdx +3 -3
  71. package/docs/site/surfaces/eve.mdx +5 -5
  72. package/docs/site/surfaces/mcp.mdx +73 -5
  73. package/docs/site/surfaces/react-query.mdx +3 -3
  74. package/docs/site/surfaces/swr.mdx +3 -3
  75. package/docs/site/surfaces/typescript.mdx +5 -5
  76. package/docs/site/surfaces.mdx +1 -1
  77. package/package-docs.mjs +137 -0
  78. package/package.json +7 -3
  79. package/prepare-package.mjs +21 -0
  80. package/src/mcp.ts +4 -0
  81. package/src/package.test.ts +44 -8
  82. package/verify-package-exports.mjs +37 -0
  83. package/dist/mount-xvMsjz1B.mjs +0 -178
  84. package/dist/mount-xvMsjz1B.mjs.map +0 -1
  85. package/dist/src-BF70JLxI.mjs.map +0 -1
  86. package/dist/src-C2MGIlT0.mjs.map +0 -1
  87. package/dist/src-CDxL6w3d.mjs.map +0 -1
  88. package/dist/src-DdV82An-.mjs.map +0 -1
@@ -1,5 +1,6 @@
1
- import { _ as normalizePresentation, h as schemaToJsonSchema, l as executeLocatedCapability, x as CapableError, y as renderPresentationMarkdown } from "./src-DdV82An-.mjs";
2
- import { a as TransportError, c as getAppRuntime, l as isApp } from "./src-C2MGIlT0.mjs";
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";
3
+ import SuperJSON from "superjson";
3
4
  //#region packages/fetch/src/error-response.ts
4
5
  function capabilityErrorData(error, fallbackStatus = 500) {
5
6
  const capable = error instanceof CapableError || error instanceof TransportError ? error : new CapableError("INTERNAL_SERVER_ERROR", { cause: error });
@@ -18,20 +19,42 @@ function capabilityErrorResponse(error, fallbackStatus = 500) {
18
19
  }, { status: data.status });
19
20
  }
20
21
  //#endregion
22
+ //#region packages/fetch/src/codec.ts
23
+ function defineProtocolCodec(codec) {
24
+ if (!codec.id.trim()) throw new Error("Protocol codec id must not be empty");
25
+ return Object.freeze({
26
+ id: codec.id,
27
+ encode: codec.encode,
28
+ decode: codec.decode
29
+ });
30
+ }
31
+ const richJson = new SuperJSON();
32
+ const capableRichJsonCodec = defineProtocolCodec({
33
+ id: "capable.rich-json.v1",
34
+ encode(value) {
35
+ return richJson.serialize(value);
36
+ },
37
+ decode(value) {
38
+ return richJson.deserialize(value);
39
+ }
40
+ });
41
+ //#endregion
21
42
  //#region packages/fetch/src/capable.ts
43
+ const PROTOCOL_CODEC_HEADER = "capable-codec";
22
44
  function createProtocolHandler(application, options = {}) {
23
- const basePath = normalizePath$1(options.basePath ?? "/_capable");
45
+ const basePath = normalizePath$1(options.basePath ?? "/~capable");
46
+ const codec = options.codec ?? capableRichJsonCodec;
24
47
  const fetch = async (request) => {
25
48
  const url = new URL(request.url);
26
49
  const runtime = getAppRuntime(isApp(application) ? application : await application(request));
27
- if (url.pathname === `${basePath}/manifest` && request.method === "GET") return Response.json(await runtime.manifest());
50
+ if (url.pathname === `${basePath}/manifest` && request.method === "GET") return Response.json(await runtime.manifest(), { headers: { [PROTOCOL_CODEC_HEADER]: codec.id } });
28
51
  const subscribePrefix = `${basePath}/subscribe/`;
29
52
  if (url.pathname.startsWith(subscribePrefix) && request.method === "POST") {
30
53
  const id = decodeURIComponent(url.pathname.slice(subscribePrefix.length));
31
54
  const controller = new AbortController();
32
55
  let stream;
33
56
  try {
34
- const body = await request.json();
57
+ const body = await protocolRequestJson(request, codec);
35
58
  stream = runtime.subscribe({
36
59
  id,
37
60
  input: body.input ?? {},
@@ -39,36 +62,78 @@ function createProtocolHandler(application, options = {}) {
39
62
  signal: AbortSignal.any([request.signal, controller.signal])
40
63
  });
41
64
  const first = await stream.next();
42
- return subscriptionResponse(stream, first, controller);
65
+ return subscriptionResponse(stream, first, controller, codec);
43
66
  } catch (error) {
44
67
  controller.abort();
45
68
  await stream?.return?.().catch(() => void 0);
46
- return capabilityErrorResponse(error);
69
+ return protocolErrorResponse(error, codec);
47
70
  }
48
71
  }
49
72
  const callPrefix = `${basePath}/call/`;
50
73
  if (!url.pathname.startsWith(callPrefix) || request.method !== "POST") return new Response("Not Found", { status: 404 });
51
74
  const id = decodeURIComponent(url.pathname.slice(callPrefix.length));
52
75
  try {
53
- const body = await request.json();
76
+ const body = await protocolRequestJson(request, codec);
54
77
  const result = await runtime.call({
55
78
  id,
56
79
  input: body.input ?? {},
57
80
  ...body.presentation ? { presentation: true } : {},
58
81
  signal: request.signal
59
82
  });
60
- return Response.json({
83
+ return protocolResponse(codec, {
61
84
  ok: true,
62
85
  ...result
63
86
  });
64
87
  } catch (error) {
65
- return capabilityErrorResponse(error);
88
+ return protocolErrorResponse(error, codec);
66
89
  }
67
90
  };
68
91
  return { fetch };
69
92
  }
93
+ async function protocolRequestJson(request, codec) {
94
+ const received = request.headers.get(PROTOCOL_CODEC_HEADER);
95
+ if (received !== codec.id) throw new TransportError("UNSUPPORTED_CODEC", {
96
+ status: 415,
97
+ message: `Protocol codec mismatch: expected "${codec.id}", received "${received ?? "none"}"`,
98
+ data: {
99
+ expected: codec.id,
100
+ received
101
+ }
102
+ });
103
+ let decoded;
104
+ try {
105
+ decoded = codec.decode(await request.json());
106
+ } catch (cause) {
107
+ throw new TransportError("BAD_REQUEST", {
108
+ status: 400,
109
+ message: "Protocol request could not be decoded",
110
+ cause
111
+ });
112
+ }
113
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new TransportError("BAD_REQUEST", {
114
+ status: 400,
115
+ message: "Protocol request must decode to an object"
116
+ });
117
+ return decoded;
118
+ }
119
+ function protocolResponse(codec, value, init = {}) {
120
+ const headers = new Headers(init.headers);
121
+ headers.set(PROTOCOL_CODEC_HEADER, codec.id);
122
+ return Response.json(codec.encode(value), {
123
+ ...init,
124
+ headers
125
+ });
126
+ }
127
+ function protocolErrorResponse(error, codec) {
128
+ const data = capabilityErrorData(error);
129
+ return protocolResponse(codec, {
130
+ ok: false,
131
+ error: data
132
+ }, { status: data.status });
133
+ }
70
134
  function createHttpTransport(options) {
71
135
  const fetchImplementation = options.fetch ?? globalThis.fetch;
136
+ const codec = options.codec ?? capableRichJsonCodec;
72
137
  async function request(path, init) {
73
138
  const base = normalizeUrl(typeof options.url === "function" ? options.url() : options.url);
74
139
  const configured = typeof options.headers === "function" ? await options.headers() : options.headers;
@@ -83,21 +148,28 @@ function createHttpTransport(options) {
83
148
  async manifest({ signal } = {}) {
84
149
  const response = await request("manifest", {
85
150
  method: "GET",
151
+ headers: { [PROTOCOL_CODEC_HEADER]: codec.id },
86
152
  ...signal ? { signal } : {}
87
153
  });
88
154
  if (!response.ok) throw await responseError(response);
155
+ if (response.headers.get("content-type")?.includes("json")) assertResponseCodec(response, codec);
89
156
  return await responseJson(response, "Application manifest");
90
157
  },
91
158
  async call({ id, input = {}, signal, presentation }) {
92
- const body = await (await request(`call/${encodeURIComponent(id)}`, {
159
+ const response = await request(`call/${encodeURIComponent(id)}`, {
93
160
  method: "POST",
94
- headers: { "content-type": "application/json" },
95
- body: JSON.stringify({
161
+ headers: {
162
+ "content-type": "application/json",
163
+ [PROTOCOL_CODEC_HEADER]: codec.id
164
+ },
165
+ body: JSON.stringify(codec.encode({
96
166
  input,
97
167
  ...presentation ? { presentation } : {}
98
- }),
168
+ })),
99
169
  ...signal ? { signal } : {}
100
- })).json();
170
+ });
171
+ if (!response.ok) throw await responseError(response, codec);
172
+ const body = await protocolResponseJson(response, codec, "Capability call");
101
173
  if (!body.ok) throw new TransportError(body.error.code, body.error);
102
174
  return {
103
175
  output: body.output,
@@ -109,20 +181,22 @@ function createHttpTransport(options) {
109
181
  method: "POST",
110
182
  headers: {
111
183
  accept: "text/event-stream",
112
- "content-type": "application/json"
184
+ "content-type": "application/json",
185
+ [PROTOCOL_CODEC_HEADER]: codec.id
113
186
  },
114
- body: JSON.stringify({
187
+ body: JSON.stringify(codec.encode({
115
188
  input,
116
189
  ...presentation ? { presentation } : {}
117
- }),
190
+ })),
118
191
  ...signal ? { signal } : {}
119
192
  });
120
- if (!response.ok) throw await responseError(response);
121
- yield* decodeEventStream(response);
193
+ if (!response.ok) throw await responseError(response, codec);
194
+ assertResponseCodec(response, codec);
195
+ yield* decodeEventStream(response, codec);
122
196
  }
123
197
  });
124
198
  }
125
- function subscriptionResponse(stream, first, subscriptionController) {
199
+ function subscriptionResponse(stream, first, subscriptionController, codec) {
126
200
  const encoder = new TextEncoder();
127
201
  let initial = first;
128
202
  return new Response(new ReadableStream({
@@ -135,10 +209,10 @@ function subscriptionResponse(stream, first, subscriptionController) {
135
209
  controller.close();
136
210
  return;
137
211
  }
138
- controller.enqueue(encoder.encode(sseFrame("output", result.value)));
212
+ controller.enqueue(encoder.encode(sseFrame("output", result.value, codec)));
139
213
  } catch (error) {
140
214
  subscriptionController.abort();
141
- controller.enqueue(encoder.encode(sseFrame("error", capabilityErrorData(error))));
215
+ controller.enqueue(encoder.encode(sseFrame("error", capabilityErrorData(error), codec)));
142
216
  controller.close();
143
217
  await stream.return?.();
144
218
  }
@@ -149,10 +223,11 @@ function subscriptionResponse(stream, first, subscriptionController) {
149
223
  }
150
224
  }, { highWaterMark: 0 }), { headers: {
151
225
  "cache-control": "no-cache",
226
+ [PROTOCOL_CODEC_HEADER]: codec.id,
152
227
  "content-type": "text/event-stream; charset=utf-8"
153
228
  } });
154
229
  }
155
- async function* decodeEventStream(response) {
230
+ async function* decodeEventStream(response, codec) {
156
231
  if (!response.headers.get("content-type")?.includes("text/event-stream")) throw new TransportError("TRANSPORT_ERROR", {
157
232
  status: response.status,
158
233
  message: "Subscription response is not an event stream"
@@ -172,7 +247,7 @@ async function* decodeEventStream(response) {
172
247
  while (boundary) {
173
248
  const block = buffer.slice(0, boundary.index);
174
249
  buffer = buffer.slice(boundary.index + boundary.length);
175
- const event = parseEventBlock(block);
250
+ const event = parseEventBlock(block, codec);
176
251
  if (event) {
177
252
  if (event.type === "error") throw new TransportError(event.error.code, event.error);
178
253
  yield event.result;
@@ -198,7 +273,7 @@ function eventBoundary(value) {
198
273
  length: 2
199
274
  };
200
275
  }
201
- function parseEventBlock(block) {
276
+ function parseEventBlock(block, codec) {
202
277
  let type = "message";
203
278
  const data = [];
204
279
  for (const line of block.replace(/\r\n/g, "\n").split("\n")) {
@@ -207,7 +282,15 @@ function parseEventBlock(block) {
207
282
  if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
208
283
  }
209
284
  if (!data.length) return void 0;
210
- const value = JSON.parse(data.join("\n"));
285
+ let value;
286
+ try {
287
+ value = codec.decode(JSON.parse(data.join("\n")));
288
+ } catch (cause) {
289
+ throw new TransportError("TRANSPORT_ERROR", {
290
+ message: "Subscription event could not be decoded",
291
+ cause
292
+ });
293
+ }
211
294
  return type === "error" ? {
212
295
  type: "error",
213
296
  error: value
@@ -216,22 +299,68 @@ function parseEventBlock(block) {
216
299
  result: value
217
300
  };
218
301
  }
219
- function sseFrame(event, data) {
220
- return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
302
+ function sseFrame(event, data, codec) {
303
+ return `event: ${event}\ndata: ${JSON.stringify(codec.encode(data))}\n\n`;
221
304
  }
222
305
  function normalizeUrl(value) {
223
- const url = new URL(value);
306
+ let url;
307
+ try {
308
+ url = typeof window === "undefined" ? new URL(value) : new URL(value, window.location.origin);
309
+ } catch (cause) {
310
+ throw new TypeError("Capable transport URLs must be absolute when no browser origin is available. Pass an absolute URL or return one from the `url` function.", { cause });
311
+ }
224
312
  if (!url.pathname.endsWith("/")) url.pathname += "/";
225
313
  url.search = "";
226
314
  url.hash = "";
227
315
  return url;
228
316
  }
229
- async function responseError(response) {
317
+ function assertResponseCodec(response, codec) {
318
+ const received = response.headers.get(PROTOCOL_CODEC_HEADER);
319
+ if (received === codec.id) return;
320
+ throw new TransportError("UNSUPPORTED_CODEC", {
321
+ status: response.status,
322
+ message: `Protocol codec mismatch: expected "${codec.id}", received "${received ?? "none"}"`,
323
+ data: {
324
+ expected: codec.id,
325
+ received
326
+ }
327
+ });
328
+ }
329
+ async function protocolResponseJson(response, codec, label) {
330
+ assertResponseCodec(response, codec);
331
+ const encoded = await responseJson(response, label);
332
+ try {
333
+ return codec.decode(encoded);
334
+ } catch (cause) {
335
+ throw new TransportError("TRANSPORT_ERROR", {
336
+ status: response.status,
337
+ message: `${label} response could not be decoded`,
338
+ cause
339
+ });
340
+ }
341
+ }
342
+ async function responseError(response, codec) {
343
+ if (codec) try {
344
+ assertResponseCodec(response, codec);
345
+ } catch (error) {
346
+ return error;
347
+ }
230
348
  const text = await response.text().catch(() => "");
231
349
  let data = text;
350
+ let parsed = false;
232
351
  try {
233
352
  data = JSON.parse(text);
353
+ parsed = true;
234
354
  } catch {}
355
+ if (codec && parsed) try {
356
+ data = codec.decode(data);
357
+ } catch (cause) {
358
+ return new TransportError("TRANSPORT_ERROR", {
359
+ status: response.status,
360
+ message: "Transport error response could not be decoded",
361
+ cause
362
+ });
363
+ }
235
364
  if (data && typeof data === "object" && "ok" in data && data.ok === false && "error" in data && data.error && typeof data.error === "object" && "code" in data.error && typeof data.error.code === "string") {
236
365
  const error = data.error;
237
366
  return new TransportError(error.code, {
@@ -463,6 +592,6 @@ function joinPath(...parts) {
463
592
  return normalizePath(parts.join("/"));
464
593
  }
465
594
  //#endregion
466
- export { createHttpTransport as n, createProtocolHandler as r, createHttpHandler as t };
595
+ export { defineProtocolCodec as i, createHttpTransport as n, createProtocolHandler as r, createHttpHandler as t };
467
596
 
468
- //# sourceMappingURL=src-BF70JLxI.mjs.map
597
+ //# sourceMappingURL=src-rkr5j_NH.mjs.map
@@ -0,0 +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,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,I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C.mjs";
1
+ import { q as MaybePromise } from "./index-_qKFfWV4.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-Bq792Ad2.d.mts.map
18
+ //# sourceMappingURL=subscription-B-auXJbm.d.mts.map
package/dist/swr.d.mts ADDED
@@ -0,0 +1,36 @@
1
+ import { u as AppCapabilityIsSubscribable } from "./index-F4ba_olD.mjs";
2
+ import { Fetcher, SWRConfiguration } from "swr";
3
+ import { MutationFetcher, SWRMutationConfiguration } from "swr/mutation";
4
+ import { SWRSubscription } from "swr/subscription";
5
+ //#region packages/swr/src/index.d.ts
6
+ type CapabilityCall = (...args: any[]) => Promise<any>;
7
+ type CapabilityInput<TCall extends CapabilityCall> = Exclude<Parameters<TCall>[0], undefined>;
8
+ type CapabilityVariables<TCall extends CapabilityCall> = undefined extends Parameters<TCall>[0] ? Exclude<Parameters<TCall>[0], undefined> | void : Parameters<TCall>[0];
9
+ type CapabilityOutput<TCall extends CapabilityCall> = Awaited<ReturnType<TCall>>;
10
+ type CapabilitySWRKey = readonly [unknown, ...unknown[]];
11
+ type CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<CapabilityOutput<TCall>, CapabilitySWRKey>;
12
+ type CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<CapabilityOutput<TCall>, CapabilitySWRKey, CapabilityVariables<TCall>>;
13
+ type CapabilitySWRConfiguration<TCall extends CapabilityCall> = Omit<SWRConfiguration<CapabilityOutput<TCall>, Error, CapabilityFetcher<TCall>>, "fetcher">;
14
+ type CapabilitySWRMutationConfiguration<TCall extends CapabilityCall, TSWRData = CapabilityOutput<TCall>> = SWRMutationConfiguration<CapabilityOutput<TCall>, Error, CapabilitySWRKey, CapabilityVariables<TCall>, TSWRData> & {
15
+ readonly throwOnError?: boolean;
16
+ };
17
+ type CapabilitySWRSubscriptionConfiguration<TCall extends CapabilityCall> = SWRConfiguration<CapabilityOutput<TCall>, Error>;
18
+ type SWRCapability<TCall extends CapabilityCall> = {
19
+ key(input?: CapabilityInput<TCall>): CapabilitySWRKey;
20
+ swr(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, fetcher: CapabilityFetcher<TCall>];
21
+ swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, fetcher: CapabilityFetcher<TCall>, options: TOptions];
22
+ mutation(): readonly [key: CapabilitySWRKey, fetcher: CapabilityMutationFetcher<TCall>];
23
+ mutation<TSWRData = CapabilityOutput<TCall>>(options: CapabilitySWRMutationConfiguration<TCall, TSWRData>): readonly [key: CapabilitySWRKey, fetcher: CapabilityMutationFetcher<TCall>, options: CapabilitySWRMutationConfiguration<TCall, TSWRData>];
24
+ };
25
+ type SWRLiveCapability<TCall extends CapabilityCall> = SWRCapability<TCall> & {
26
+ subscription(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>];
27
+ subscription<const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>, options: TOptions];
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;
30
+ type SWRApp<TApp extends object> = SWRNode<TApp>;
31
+ declare function createSWR<const TApp extends object>(app: TApp, options?: {
32
+ readonly keyPrefix?: readonly unknown[];
33
+ }): SWRApp<TApp>;
34
+ //#endregion
35
+ export { CapabilitySWRConfiguration, CapabilitySWRKey, CapabilitySWRMutationConfiguration, CapabilitySWRSubscriptionConfiguration, SWRApp, SWRCapability, SWRLiveCapability, createSWR };
36
+ //# sourceMappingURL=swr.d.mts.map
package/dist/swr.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import { u as subscribe } from "./src-betOfnDL.mjs";
2
+ //#region packages/swr/src/index.ts
3
+ const subscribeCall = subscribe;
4
+ function createSWR(app, options = {}) {
5
+ const keyPrefix = Object.freeze([...options.keyPrefix ?? ["capable"]]);
6
+ const callableAt = (path) => {
7
+ let current = app;
8
+ for (const segment of path) current = current[segment];
9
+ return current;
10
+ };
11
+ const capabilityKey = (path, input) => Object.freeze([
12
+ ...keyPrefix,
13
+ ...path,
14
+ ...input === void 0 ? [] : [input]
15
+ ]);
16
+ const withOptions = (key, operation, hookOptions) => hookOptions === void 0 ? [key, operation] : [
17
+ key,
18
+ operation,
19
+ hookOptions
20
+ ];
21
+ const proxy = (path) => new Proxy({}, { get(_target, key) {
22
+ if (key === "then") return void 0;
23
+ if (key === "key") return (input) => capabilityKey(path, input);
24
+ if (key === "swr") return (input, swrOptions) => withOptions(capabilityKey(path, input), () => callableAt(path)(input), swrOptions);
25
+ if (key === "mutation") return (mutationOptions) => withOptions(capabilityKey(path), (_key, { arg }) => callableAt(path)(arg), mutationOptions);
26
+ if (key === "subscription") return (input, subscriptionOptions) => withOptions(capabilityKey(path, input), (_key, { next }) => {
27
+ const controller = new AbortController();
28
+ (async () => {
29
+ try {
30
+ for await (const output of subscribeCall(callableAt(path), input, { signal: controller.signal })) next(null, output);
31
+ } catch (error) {
32
+ if (!controller.signal.aborted) next(toError(error));
33
+ }
34
+ })();
35
+ return () => controller.abort();
36
+ }, subscriptionOptions);
37
+ if (typeof key !== "string") return void 0;
38
+ return proxy([...path, key]);
39
+ } });
40
+ return proxy([]);
41
+ }
42
+ function toError(error) {
43
+ return error instanceof Error ? error : new Error(String(error));
44
+ }
45
+ //#endregion
46
+ export { createSWR };
47
+
48
+ //# sourceMappingURL=swr.mjs.map
@@ -0,0 +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,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,KAAK,IAEvB,MACA,EAAE,WAGC;GACH,MAAM,aAAa,IAAI,gBAAgB;GAEvC,CAAM,YAAY;IAChB,IAAI;KACF,WAAW,MAAM,UAAU,cACzB,WAAW,IAAI,GACf,OACA,EAAE,QAAQ,WAAW,OAAO,CAC9B,GACE,KAAK,MAAM,MAAM;IAErB,SAAS,OAAO;KACd,IAAI,CAAC,WAAW,OAAO,SACrB,KAAK,QAAQ,KAAK,CAAC;IAEvB;GACF,EAAA,CAAG;GAEH,aAAa,WAAW,MAAM;EAChC,GACA,mBACF;EAEF,IAAI,OAAO,QAAQ,UAAU,OAAO,KAAA;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"}
package/docs/CONTEXT.md CHANGED
@@ -55,7 +55,9 @@ leaf/subtree conflicts fail when the merged manifest first resolves.
55
55
  `call()`, and `subscribe()`. `createRemoteApp()` wraps and caches it without
56
56
  turning module evaluation into a network boundary. Its HTTP client/server
57
57
  encoding lives in `@capable/fetch` as server plumbing, separate from authored
58
- HTTP APIs and from transport-neutral App semantics.
58
+ HTTP APIs and from transport-neutral App semantics. Its versioned value codec
59
+ preserves runtime values across calls, errors, and subscriptions; custom codecs
60
+ must identify themselves and match on both peers.
59
61
 
60
62
  **HTTP projection**: a server mount that derives routes from the Application
61
63
  tree and `effect`, then applies optional `meta.http` overrides. It also owns
@@ -0,0 +1,24 @@
1
+ ---
2
+ status: accepted
3
+ ---
4
+
5
+ # Version the Capable transport value codec
6
+
7
+ The private Capable HTTP transport encodes calls, results, declared-error data,
8
+ and subscription frames with a versioned value codec. Its default codec is
9
+ `capable.rich-json.v1`, implemented with an isolated SuperJSON instance. This
10
+ preserves runtime values such as `Date` without teaching `@capable/core` about a
11
+ wire format or maintaining a home-grown metadata protocol.
12
+
13
+ The client sends the codec ID and the server repeats it in the
14
+ `capable-codec` header. Peers reject a missing or different ID instead of
15
+ silently interpreting another encoding. Changing the default wire format
16
+ requires a new codec ID and Capable manifest protocol version.
17
+
18
+ `defineProtocolCodec()` is the extension seam. A custom codec is configured on
19
+ both `protocol({ codec })` and `createHttpTransport({ codec })`; Capable owns the
20
+ HTTP and SSE framing while the codec owns only JSON-compatible value
21
+ transformation.
22
+
23
+ Authored HTTP routes and OpenAPI remain ordinary JSON projections. Their
24
+ interoperability contract is separate from the private remote-App protocol.